content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def deleteNode(self, root: TreeNode, key: int) -> TreeNode: """ https://leetcode-cn.com/problems/del...
class Treenode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def delete_node(self, root: TreeNode, key: int) -> TreeNode: """ https://leetcode-cn.com/problems/delete-node-in-a-bst/solution/yong-qia...
# Definition for a binary tree node class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def __repr__(self): return "{}".format(self.val) class Solution(object): def kthSmallest(self, root, k): """ :type root: Tree...
class Treenode(object): def __init__(self, x): self.val = x self.left = None self.right = None def __repr__(self): return '{}'.format(self.val) class Solution(object): def kth_smallest(self, root, k): """ :type root: TreeNode :type k: int :...
users = [] class User(): def __init__(self, username, password): self.username = username self.password = password users.append(User("spudmix", "asd")) current_user = None def check_user_exists(username): return username in [user.username for user in users] def get_user(username): return...
users = [] class User: def __init__(self, username, password): self.username = username self.password = password users.append(user('spudmix', 'asd')) current_user = None def check_user_exists(username): return username in [user.username for user in users] def get_user(username): return [...
# Flask server Configuration DEBUG = False SQLALCHEMY_ECHO = False SECRET_KEY = "REPLACE BY SOMETHING SECURE" SQLALCHEMY_DATABASE_URI = "sqlite:///:memory" SQLALCHEMY_TRACK_MODIFICATIONS = False # Files configuration FILESTORE_DIR = "filestore" # folder name on disk FILESTORE_PATH = "/file" # URL path prefix MAX_UP...
debug = False sqlalchemy_echo = False secret_key = 'REPLACE BY SOMETHING SECURE' sqlalchemy_database_uri = 'sqlite:///:memory' sqlalchemy_track_modifications = False filestore_dir = 'filestore' filestore_path = '/file' max_upload_size = 32 * 1024 * 1024 initial_year = 2010 file_icons = {'audio/': 'file-audio', 'video/'...
# # @lc app=leetcode.cn id=71 lang=python3 # # [71] simplify-path # None # @lc code=end
None
#!/usr/bin/env python3 #encoding=utf-8 #------------------------------------------------------ # Usage: python3 4-metaclass5.py # Description: overloading class creation calls with metaclass #------------------------------------------------------ ''' Since they participate in normal OOP mechanics, it's also possibl...
""" Since they participate in normal OOP mechanics, it's also possible for metaclasses to catch the creation call at the end of a class statement directly, by redefining the type object's __call__. The redefinitions of both __new__ and __call__ must be careful to call back to their defaults in type if they mean to ma...
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
"""Abstract backend class definition.""" class Backend(object): """Abstract backend class definition.""" def __init__(self): self.inputs = [] self.outputs = [] def version(self): raise not_implemented_error('Backend:version') def name(self): raise not_implemented_erro...
# Helper to wrap utilities to parse measurments # Represent a measurement line output by hdrist cdfthe server/client. class Measurement: value = 0 percentage = 0 def __init__(self, oline): parsed_line = oline.rstrip('\n').replace('(', '').replace(')', '').split(', ') self.value = int(par...
class Measurement: value = 0 percentage = 0 def __init__(self, oline): parsed_line = oline.rstrip('\n').replace('(', '').replace(')', '').split(', ') self.value = int(parsed_line[0]) self.percentage = float(parsed_line[1]) def create_measurements_list(output): measurements = []...
# Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the License); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, so...
def accurate(flavors_list, max_ram, max_core): """ This is implementation of bounded multiobjective multidimension knapsack solution with dynamic programming Good place to start with one dimensional problem: http://rosettacode.org/wiki/Knapsack_problem/Bounded#Python """ state = [] f...
def draw_smpte_rects(draw, x, y, width, height, colors): for i in range(len(colors)): draw.rectangle([(x + (width * i), y), (x + (width * (i + 1)), y + height)], fill=colors[i], outline=colors[i]) def draw_smpte_pattern(draw): fb_width, fb_height = draw.im.size # top colors: grey/silver, yellow, c...
def draw_smpte_rects(draw, x, y, width, height, colors): for i in range(len(colors)): draw.rectangle([(x + width * i, y), (x + width * (i + 1), y + height)], fill=colors[i], outline=colors[i]) def draw_smpte_pattern(draw): (fb_width, fb_height) = draw.im.size y = 0 width = fb_width / 7 heig...
""" Answer: Family History Why? The most important feature would be the one which gives the highest accuracy when used alone. This makes Family History the most important feature using it alone results in an accuracy of 0.9 as opposed to 0.875 and 0.85 when using `Is_a_smoker` and `Is_young`, respectively """;
""" Answer: Family History Why? The most important feature would be the one which gives the highest accuracy when used alone. This makes Family History the most important feature using it alone results in an accuracy of 0.9 as opposed to 0.875 and 0.85 when using `Is_a_smoker` and `Is_young`, respectively """
class PluginError(RuntimeError): """ An error that has something to do with plugins. """ class DifferentLogicalDevices(RuntimeError): """ An attempt to move a file to a different logical device was made. """ class NoSuchAction(ValueError): """ An invalid or unknown action name was ...
class Pluginerror(RuntimeError): """ An error that has something to do with plugins. """ class Differentlogicaldevices(RuntimeError): """ An attempt to move a file to a different logical device was made. """ class Nosuchaction(ValueError): """ An invalid or unknown action name was spec...
def strip_space_tab(string: str): return string.replace(' ', '').replace('\t', '') def strip_space_tab_eol(string: str): return strip_space_tab(string).replace('\n', '') # see also: https://stackoverflow.com/questions/33659074/what-the-diff-python- # unittest-failing-due-to-leading-whitespace-in-multine # s...
def strip_space_tab(string: str): return string.replace(' ', '').replace('\t', '') def strip_space_tab_eol(string: str): return strip_space_tab(string).replace('\n', '') " For HTML and XML\nA better approach which I don't know how to do off the top of my head would be to\ncaniconalize the two strings. Clean Up...
# encoding: utf-8 # ============================[ General settings ]============================ SUPPORTED_FORMATS = ['png', 'jpg', 'jpeg'] DEFAULT_QUALITY = 80 DEFAULT_BG_COLOR = (255, 255, 255) MIN_BIG_IMG_SIZE = 80_000 MIN_BIG_IMG_AREA = 800 * 600 # ====================[ iOS/Pythonista specific settings ]=========...
supported_formats = ['png', 'jpg', 'jpeg'] default_quality = 80 default_bg_color = (255, 255, 255) min_big_img_size = 80000 min_big_img_area = 800 * 600 ipad_font_size = 15 iphone_font_size = 10 ios_workers = 2 ios_font = 'Menlo'
# # def func(d,c): # d['a']=10 # d['b']=20 # # c.append(4) # # c=[1] # d = {'a': 1, 'b': 2} # func(d,c) # print(d) # print(c) y=1 x='' a= x or None print(a)
y = 1 x = '' a = x or None print(a)
padding_left = 0 padding_right = 8 padding_top = 10 padding_bottom = 20
padding_left = 0 padding_right = 8 padding_top = 10 padding_bottom = 20
''' Greedy Algorithms: Example 2 - Giving change ''' def give_change(change, denominations): ''' returns a list of coins that make up the change in as few coins as possible ''' bag_of_coins = [] if change is None or change <= 0: return bag_of_coins denominations.sort(reverse = True) chang...
""" Greedy Algorithms: Example 2 - Giving change """ def give_change(change, denominations): """ returns a list of coins that make up the change in as few coins as possible """ bag_of_coins = [] if change is None or change <= 0: return bag_of_coins denominations.sort(reverse=True) change = ...
n = int(input()) for t in range(n): r, c = [int(x) for x in input().split()] grid = [] count1 = [0] * c for i in range(r): for i, x in enumerate(input()): count1[i] += 1 if x == '1' else 0 for x in count1: print('1' if x >= r / 2 else '0', end='') print()
n = int(input()) for t in range(n): (r, c) = [int(x) for x in input().split()] grid = [] count1 = [0] * c for i in range(r): for (i, x) in enumerate(input()): count1[i] += 1 if x == '1' else 0 for x in count1: print('1' if x >= r / 2 else '0', end='') print()
class Employee: def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '-' + last + '@gmail.com' def fullname(self): return '{} {}'.format(self.first, self.last) employee_1 = Employee('David', 'olatoye...
class Employee: def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '-' + last + '@gmail.com' def fullname(self): return '{} {}'.format(self.first, self.last) employee_1 = employee('David', 'olatoye', 500000) emp...
""" Pikalang to BF translator @author ymll """ class PikalangTranslator(): def __init__(self): self.bf_2_pika_dictionary = { '+': 'vu', '-': 'lp', '[': 'vulp', ']': 'ix', '>': 'vuvu', '<': 'vuix', ',': 'vulx', ...
""" Pikalang to BF translator @author ymll """ class Pikalangtranslator: def __init__(self): self.bf_2_pika_dictionary = {'+': 'vu', '-': 'lp', '[': 'vulp', ']': 'ix', '>': 'vuvu', '<': 'vuix', ',': 'vulx', '.': 'vulpix'} self.pika_2_bf_dictionary = {v: k for (k, v) in self.bf_2_pika_dictionary.it...
def count(n): dp = [0 for _ in range(n + 1)] for i in range(1, n + 1): if i <= 3: dp[i] = 1 elif i == 4: dp[i] = 2 else: dp[i] = dp[i - 1] + dp[i - 4] return dp[n] n = 5 print("Count of ways is"), print(count(n))
def count(n): dp = [0 for _ in range(n + 1)] for i in range(1, n + 1): if i <= 3: dp[i] = 1 elif i == 4: dp[i] = 2 else: dp[i] = dp[i - 1] + dp[i - 4] return dp[n] n = 5 (print('Count of ways is'),) print(count(n))
class PromptForFamilyInstancePlacementOptions(object,IDisposable): """ This class contains options to control the behavior of interactive placement of family instances. PromptForFamilyInstancePlacementOptions(other: PromptForFamilyInstancePlacementOptions) PromptForFamilyInstancePlacementOptions() """ ...
class Promptforfamilyinstanceplacementoptions(object, IDisposable): """ This class contains options to control the behavior of interactive placement of family instances. PromptForFamilyInstancePlacementOptions(other: PromptForFamilyInstancePlacementOptions) PromptForFamilyInstancePlacementOptions() """ ...
# # Copyright (c) 2021 Cisco Systems, Inc and its affiliates # All rights reserved # class Language: def __init__(self, id=None, name=None, description=None): self._id = id self._name = name self._description = description def to_dict(self): return { "id": self._id, "name": self._name, "description"...
class Language: def __init__(self, id=None, name=None, description=None): self._id = id self._name = name self._description = description def to_dict(self): return {'id': self._id, 'name': self._name, 'description': self._description}
class WeightedQuickUnionUF: def __init__(self, N: int): self._count = N self.id = [i for i in range(N)] self.sz = [1 for i in range(N)] def find(self, p: int): while p != self.id[p]: p = self.id[p] return p def union(self, p: int, q: int): i = se...
class Weightedquickunionuf: def __init__(self, N: int): self._count = N self.id = [i for i in range(N)] self.sz = [1 for i in range(N)] def find(self, p: int): while p != self.id[p]: p = self.id[p] return p def union(self, p: int, q: int): i = s...
"""Process data."""
"""Process data."""
# -*- coding: utf-8 -*- __author__ = 'PlanetaryPy Developers' __email__ = 'contact@planetarypy.com' __version__ = '0.1.0'
__author__ = 'PlanetaryPy Developers' __email__ = 'contact@planetarypy.com' __version__ = '0.1.0'
VOCS = { "Alpha (B.1.1.7)": "B.1.1.7", "Beta (B.1.351)": "B.1.351", "Gamma (P.1)": "P.1", "Delta (B.1.617.2)": "B.1.617.2", "Delta Subtypes (AY.*)": r"AY.*", "Omicron (B.1.1.529)": "B.1.1.529", "Omicron Subtypes (BA.*)": r"BA.*", }
vocs = {'Alpha (B.1.1.7)': 'B.1.1.7', 'Beta (B.1.351)': 'B.1.351', 'Gamma (P.1)': 'P.1', 'Delta (B.1.617.2)': 'B.1.617.2', 'Delta Subtypes (AY.*)': 'AY.*', 'Omicron (B.1.1.529)': 'B.1.1.529', 'Omicron Subtypes (BA.*)': 'BA.*'}
''' Created on 1.12.2016 @author: Darren '''''' Given a string containing only digits, restore it by returning all possible valid IP address combinations. For example: Given "25525511135", return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) " '''
""" Created on 1.12.2016 @author: Darren Given a string containing only digits, restore it by returning all possible valid IP address combinations. For example: Given "25525511135", return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) " """
""" Single point of truth for version information """ VERSION_NO = '3.5.1' VERSION_DESC = 'VAWS ' + VERSION_NO
""" Single point of truth for version information """ version_no = '3.5.1' version_desc = 'VAWS ' + VERSION_NO
# Note: math.inf doesn't seem to work, but this does :P inf = float("inf") class Point: """Represents a point on an elliptical curve """ def __init__(self, x, y, curve): """Initializes a point at a given (x, y) Args: x: a number for the x-coordinate of the point y...
inf = float('inf') class Point: """Represents a point on an elliptical curve """ def __init__(self, x, y, curve): """Initializes a point at a given (x, y) Args: x: a number for the x-coordinate of the point y: a number for the y-coordinate of the point ...
"""This package contains all the additional classes and functions that are used in the CGDAT data anaylsis tool. It contains the following components: **Modules:** .. autosummary:: :toctree: _autosummary cgdat.qt_custom.qt_dialogs cgdat.qt_custom.qt_extra cgdat.qt_custom.qt_thread """ # Set all __all...
"""This package contains all the additional classes and functions that are used in the CGDAT data anaylsis tool. It contains the following components: **Modules:** .. autosummary:: :toctree: _autosummary cgdat.qt_custom.qt_dialogs cgdat.qt_custom.qt_extra cgdat.qt_custom.qt_thread """ __all__ = ['qt_e...
DEBUG = True SECRET_KEY = 'secret_key' SQLALCHEMY_DATABASE_URI = 'sqlite:///app.db' DATABASE_CONNECT_OPTIONS = {} CSRF_ENABLED = True CSRF_SESSION_KEY = 'secret_key'
debug = True secret_key = 'secret_key' sqlalchemy_database_uri = 'sqlite:///app.db' database_connect_options = {} csrf_enabled = True csrf_session_key = 'secret_key'
def foo(): x = 1 y = 1 res = x + y return res x = 2 y = 2 def bar(arg=fo<caret>o()): return arg
def foo(): x = 1 y = 1 res = x + y return res x = 2 y = 2 def bar(arg=fo < caret > o()): return arg
rab = 35 chi = 35 while rab > 0: legs = 4*rab+2*chi if legs == 92: print (rab, chi) break rab-=1
rab = 35 chi = 35 while rab > 0: legs = 4 * rab + 2 * chi if legs == 92: print(rab, chi) break rab -= 1
num = int(input('Enter a number: ')) count = 0 for i in range(1,num+1): if num % i == 0: count += 1 if count == 2: print('yes') else: print('no')
num = int(input('Enter a number: ')) count = 0 for i in range(1, num + 1): if num % i == 0: count += 1 if count == 2: print('yes') else: print('no')
global indexString indexString = ''' <!DOCTYPE html> <html> <head> {%metas%} <title>US FARS Visualisation</title> {%favicon%} {%css%} </head> <body> {%app_entry%} <footer> {%config%} {%scripts%} {%renderer%} </footer...
global indexString index_string = '\n<!DOCTYPE html>\n<html>\n <head>\n {%metas%}\n <title>US FARS Visualisation</title>\n {%favicon%}\n {%css%}\n </head>\n <body>\n {%app_entry%}\n <footer>\n {%config%}\n {%scripts%}\n {%renderer%}\n ...
# # Using Trie and DFS # from collections import defaultdict # class TrieNode: # def __init__(self): # self.children = defaultdict(TrieNode) # self.isWord = False # self.finalWord = None # class Trie: # def __init__(self): # self.root = TrieNode() # def addWord(self, word):...
class Solution(object): def find_all_concatenated_words_in_a_dict(self, words): """ :type words: List[str] :rtype: List[str] """ d = set(words) def dfs(word): for i in range(1, len(word)): prefix = word[:i] suffix = word[i...
a, b, c = input().split(' ') a = int(a) b = int(b) c = int(c) maiorab = (a + b + abs(a-b)) / 2 maior = int((maiorab + c + abs(maiorab - c)) / 2) print(f'{maior} eh o maior')
(a, b, c) = input().split(' ') a = int(a) b = int(b) c = int(c) maiorab = (a + b + abs(a - b)) / 2 maior = int((maiorab + c + abs(maiorab - c)) / 2) print(f'{maior} eh o maior')
class ChordMessage(): # Message types FIND_SUCCESSOR = "FIND_SUCCESSOR" # Propogate a find successor message RETURN_SUCCESSOR = "RETURN_SUCCESSOR" # Return the result of a find successor query GET_PREDECESSOR = "GET_PREDECESSOR" # Request a node's predecessor RETURN_PREDECESSOR = "RETURN_PR...
class Chordmessage: find_successor = 'FIND_SUCCESSOR' return_successor = 'RETURN_SUCCESSOR' get_predecessor = 'GET_PREDECESSOR' return_predecessor = 'RETURN_PREDECESSOR' notify_predecessor = 'NOTIFY_PREDECESSOR' check_alive = 'CHECK_ALIVE' am_alive = 'AM_ALIVE' send_file = 'SEND_FILE' ...
def move(f,t): print("Move disc from {} to {}:".format(f,t)) def move_via(f,v,t): move(f,v) move(v,t) # move_via("A","B","C") # print("How many discs are being used? ") disc_amt = int(input()) def foo(x): foo(x) def hanoi(n,f,h,t): if n == 0: pass else: ...
def move(f, t): print('Move disc from {} to {}:'.format(f, t)) def move_via(f, v, t): move(f, v) move(v, t) print('How many discs are being used? ') disc_amt = int(input()) def foo(x): foo(x) def hanoi(n, f, h, t): if n == 0: pass else: hanoi(n - 1, f, t, h) move(f, t)...
# # PySNMP MIB module CISCO-RMON-CAPABILITY (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-RMON-CAPABILITY # Produced by pysmi-0.3.4 at Wed May 1 12:10:52 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, constraints_intersection, value_size_constraint, single_value_constraint, value_range_constraint) ...
# jewels and stones class Solution: def numJewelsInStones(self, J: str, S: str) -> int: js = set(J) j = 0 for s in S: if s in J: j += 1 return j J = "aAb" S = "aAAbbbb" s = Solution() print(s.numJewelsInStones(J,S))
class Solution: def num_jewels_in_stones(self, J: str, S: str) -> int: js = set(J) j = 0 for s in S: if s in J: j += 1 return j j = 'aAb' s = 'aAAbbbb' s = solution() print(s.numJewelsInStones(J, S))
#Programming I ############################# # Side Quest 5.1 # # Driverless Vehicle 2 # ############################# #Background #========== #Tom would like to enhance the safety of his driverless vehicle by applying braking when #the vehicle is less than 50 meters from an object. #Write a Python ...
def fail_safety_distance(roundTrips): round_trips = roundTrips.replace(' ', '') round_trips = roundTrips.split(',') i = 0 oj_index = 0 while i < 5: if len(roundTrips) < 5: closest_object = [-1, -1] else: short = roundTrips[0] for x in range(len(rou...
# test the testing system def capital_case(x): return x.capitalize() def test_capital_case(): assert capital_case("something") == 'Something'
def capital_case(x): return x.capitalize() def test_capital_case(): assert capital_case('something') == 'Something'
#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) 2012 Michal Kalewski <mkalewski at cs.put.poznan.pl> # # This file is a part of the Simple Network Simulator (sim2net) project. # USE, MODIFICATION, COPYING AND DISTRIBUTION OF THIS SOFTWARE IS SUBJECT TO # THE TERMS AND CONDITIONS OF THE MIT LICENSE. YOU SHOULD H...
""" Contains a collection of source code validation functions. """ __docformat__ = 'reStructuredText' def check_argument_type(function, parameter, expected_type, argument, logger=None): """ Checks whether a given argument is of a given type and raises an exception or reports a log message if the argument's...
str = 'X-DSPAM-Confidence:0.8475' # extracting portion the string after the colon first_index = str.find(':') str_portion = str[first_index + 1:] str_portion = float(str_portion) print(str_portion)
str = 'X-DSPAM-Confidence:0.8475' first_index = str.find(':') str_portion = str[first_index + 1:] str_portion = float(str_portion) print(str_portion)
_base_ = './retinanet_r50_fpn_1x_coco.py' model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint='checkpoints/resnet101-63fe2227.pth')))
_base_ = './retinanet_r50_fpn_1x_coco.py' model = dict(backbone=dict(depth=101, init_cfg=dict(type='Pretrained', checkpoint='checkpoints/resnet101-63fe2227.pth')))
binomski_slovar = {(1, 1): 1} for n in range(2, 101): for r in range(n + 1): if r == 0: binomski_slovar[(n, r)] = 1 elif r == 1: binomski_slovar[(n, r)] = n elif r == n: binomski_slovar[(n, r)] = binomski_slovar[(n - 1, r - 1)] else: ...
binomski_slovar = {(1, 1): 1} for n in range(2, 101): for r in range(n + 1): if r == 0: binomski_slovar[n, r] = 1 elif r == 1: binomski_slovar[n, r] = n elif r == n: binomski_slovar[n, r] = binomski_slovar[n - 1, r - 1] else: binomski_s...
def A(): vowels = "aeiou" a = input() b = input() if(len(a)!=len(b)): print("No") else: for i in range(len(a)): if((a[i] not in vowels and b[i] in vowels) or (a[i] in vowels and b[i] not in vowels)): print("No") return prin...
def a(): vowels = 'aeiou' a = input() b = input() if len(a) != len(b): print('No') else: for i in range(len(a)): if a[i] not in vowels and b[i] in vowels or (a[i] in vowels and b[i] not in vowels): print('No') return print('Yes') a(...
# LSM6DS33: ST's always-on 3D accelerometer and 3D gyroscope micropython drive # ver: 1.0 # License: MIT # Author: shaoziyang (shaoziyang@mail.micropython.org.cn) # v1.0 2019.5 LSM6DS33_ORIENT_CFG_G = const(0x0B) LSM6DS33_INT1_CTRL = const(0x0D) LSM6DS33_INT2_CTRL = const(0x0E) LSM6DS33_CTRL1_XL = const(0x10) LSM6DS33...
lsm6_ds33_orient_cfg_g = const(11) lsm6_ds33_int1_ctrl = const(13) lsm6_ds33_int2_ctrl = const(14) lsm6_ds33_ctrl1_xl = const(16) lsm6_ds33_ctrl2_g = const(17) lsm6_ds33_ctrl3_c = const(18) lsm6_ds33_ctrl4_c = const(19) lsm6_ds33_ctrl5_c = const(20) lsm6_ds33_ctrl6_c = const(21) lsm6_ds33_ctrl7_g = const(22) lsm6_ds33_...
class Ascent: def __init__(self, my_id, country, location, coords, style, grade, sign=None, category='n/a'): self.country = country self.location = location self.style = style self.grade = grade if sign: self.sign = sign ...
class Ascent: def __init__(self, my_id, country, location, coords, style, grade, sign=None, category='n/a'): self.country = country self.location = location self.style = style self.grade = grade if sign: self.sign = sign self.category = category ...
for i in range(1, 5): print(i) else: print('Petlja for je gotova.')
for i in range(1, 5): print(i) else: print('Petlja for je gotova.')
a=int(input("Enter a value")) b=int(input("Enter a value")) c=a+b print("Addition is",c)
a = int(input('Enter a value')) b = int(input('Enter a value')) c = a + b print('Addition is', c)
#!/Users/bernardroesler/anaconda3/envs/insight/bin/python3 #============================================================================== # File: sorting_algos.py # Created: 07/05/2018, 17:14 # Author: Bernie Roesler # """ Description: Sorting algorithms """ #==================================================...
""" Description: Sorting algorithms """ def bubble_sort(A): """Swap elements so that lesser elements 'float' to the top.""" while True: no_swaps = True for i in range(1, len(A)): if A[i - 1] > A[i]: (A[i - 1], A[i]) = (A[i], A[i - 1]) no_swaps = Fal...
cores = {'limpar': '\033[m', 'magenta': '\033[35m'} n1 = int(input('Primeiro valor: ')) n2 = int(input('Segundo valor: ')) n3 = int(input('Terceiro valor: ')) menor = n1 if n2 < n1 and n2 < n3: menor = n2 if n3 < n1 and n3 < n2: menor = n3 print(f'O menor valor digitado foi {cores["magenta"]}{menor}{co...
cores = {'limpar': '\x1b[m', 'magenta': '\x1b[35m'} n1 = int(input('Primeiro valor: ')) n2 = int(input('Segundo valor: ')) n3 = int(input('Terceiro valor: ')) menor = n1 if n2 < n1 and n2 < n3: menor = n2 if n3 < n1 and n3 < n2: menor = n3 print(f"O menor valor digitado foi {cores['magenta']}{menor}{cores['limp...
class Fileizer(): def __init__(self, output_path, profile_id): self.output_path = output_path self.profile_id = profile_id self.properties_to_fileize = dict() def _get_output_filename(self, postfix): return self.profile_id + postfix def _get_fullpath_target(self, postfix): if not self.output...
class Fileizer: def __init__(self, output_path, profile_id): self.output_path = output_path self.profile_id = profile_id self.properties_to_fileize = dict() def _get_output_filename(self, postfix): return self.profile_id + postfix def _get_fullpath_target(self, postfix): ...
#!/usr/bin/python3 def islower(c): chrcode = ord(c) if chrcode >= 97 and chrcode <= 122: return True else: return False
def islower(c): chrcode = ord(c) if chrcode >= 97 and chrcode <= 122: return True else: return False
class Result: score: float selected_groups: list[int] matching_percent: float matching_users: list[str] matching_users_count: int extraneous_percent: float extraneous_users: list[str] extraneous_users_count: int unmatched_users: list[str] unmatched_users_count: int def __in...
class Result: score: float selected_groups: list[int] matching_percent: float matching_users: list[str] matching_users_count: int extraneous_percent: float extraneous_users: list[str] extraneous_users_count: int unmatched_users: list[str] unmatched_users_count: int def __ini...
sexo = str(input("Informe seu sexo [M/F]: ")).strip().upper()[0] while sexo != 'M' or sexo != 'F': if sexo in "MmFf": print(f"O sexo {sexo} foi registrado") break else: sexo = str(input("Sexo invalido, por favor Informe seu sexo [M/F]: ")).strip().upper()[0]
sexo = str(input('Informe seu sexo [M/F]: ')).strip().upper()[0] while sexo != 'M' or sexo != 'F': if sexo in 'MmFf': print(f'O sexo {sexo} foi registrado') break else: sexo = str(input('Sexo invalido, por favor Informe seu sexo [M/F]: ')).strip().upper()[0]
{ 'targets': [ { 'target_name': 'slp', 'sources': [ 'src/node_slp.cc', 'src/api/baton.cc', 'src/api/findsrvs.cc', 'src/api/findsrvtypes.cc', 'src/api/findattrs.cc', 'src/api/reg.cc', 'src/api/dereg.cc', 'src/api/delattrs.cc' ], ...
{'targets': [{'target_name': 'slp', 'sources': ['src/node_slp.cc', 'src/api/baton.cc', 'src/api/findsrvs.cc', 'src/api/findsrvtypes.cc', 'src/api/findattrs.cc', 'src/api/reg.cc', 'src/api/dereg.cc', 'src/api/delattrs.cc'], 'libraries': ['-lslp']}]}
# generated with make_mock.py DEFLATED = 8 DEF_MEM_LEVEL = 8 MAX_WBITS = 15 ZLIB_VERSION = '1.2.3.4' Z_BEST_COMPRESSION = 9 Z_BEST_SPEED = 1 Z_DEFAULT_COMPRESSION = -1 Z_DEFAULT_STRATEGY = 0 Z_FILTERED = 1 Z_FINISH = 4 Z_FULL_FLUSH = 3 Z_HUFFMAN_ONLY = 2 Z_NO_FLUSH = 0 Z_SYNC_FLUSH = 2 class Compress(object): pas...
deflated = 8 def_mem_level = 8 max_wbits = 15 zlib_version = '1.2.3.4' z_best_compression = 9 z_best_speed = 1 z_default_compression = -1 z_default_strategy = 0 z_filtered = 1 z_finish = 4 z_full_flush = 3 z_huffman_only = 2 z_no_flush = 0 z_sync_flush = 2 class Compress(object): pass class Decompress(object): ...
def fib(n, scalar): f0, fn = 0, 1 for _ in range(1, n): f0, fn = fn, f0 * scalar + fn return n if n < 1 else fn def fib_gen(n, scalar): f0, fn = 0, 1 for i in range(n + 1): if i < 2: yield i * scalar else: f0, fn = fn, f0 * scalar + fn yi...
def fib(n, scalar): (f0, fn) = (0, 1) for _ in range(1, n): (f0, fn) = (fn, f0 * scalar + fn) return n if n < 1 else fn def fib_gen(n, scalar): (f0, fn) = (0, 1) for i in range(n + 1): if i < 2: yield (i * scalar) else: (f0, fn) = (fn, f0 * scalar + f...
# Python Program to Check If a number is Prime or Not. # A number is said to be prime if it is only divisible by 1 and itself. # Step 1: Take the input from User # Step 2: Check whether the number is greater than 1, if not than the number is not Prime # Step 3: Check if the number gets evenly divided by any numb...
num = 2 if num > 1: for i in range(2, num): if num % i == 0: print('{} is not a prime number'.format(num)) break else: print('{} is a Prime number'.format(num)) else: print(num, 'is not a prime number')
if self.frame.m_radioBox_type_use.GetSelection() == 0: self.frame.m_textCtrl_mesh_limit.SetLabel(self.default_mesh_pattern) self.frame.m_textCtrl_tex_limit.SetLabel(self.default_tex_pattern) self.change_input(event) self.change_div(event=event) else: self.frame.m_staticText15.Enable(Tr...
if self.frame.m_radioBox_type_use.GetSelection() == 0: self.frame.m_textCtrl_mesh_limit.SetLabel(self.default_mesh_pattern) self.frame.m_textCtrl_tex_limit.SetLabel(self.default_tex_pattern) self.change_input(event) self.change_div(event=event) else: self.frame.m_staticText15.Enable(True) self.f...
''' Test File ''' no_of_students = int(input('Enter the number of students')) for i in range(no_of_students): names = input('What is your name') file = open('names.txt','a') file.write(names) file.write('\n') file.close()
""" Test File """ no_of_students = int(input('Enter the number of students')) for i in range(no_of_students): names = input('What is your name') file = open('names.txt', 'a') file.write(names) file.write('\n') file.close()
ACCOUNT_NAME = 'tsoblob1' CONTAINER_NAME = 'famos' DEFAULT_FOLDER_NAME = 'hawkei001' SAVE_FILES = 'true' SOCKET_TIMEOUT = 100000 DEBUG_FILE = 'debug.log' STAGING_DIR = 'C:\\Temp' ZIP_FILE_NAME = 'famos-logs.zip' THRESHOLD = 10000
account_name = 'tsoblob1' container_name = 'famos' default_folder_name = 'hawkei001' save_files = 'true' socket_timeout = 100000 debug_file = 'debug.log' staging_dir = 'C:\\Temp' zip_file_name = 'famos-logs.zip' threshold = 10000
""" 1. Clarification 2. Possible solutions - Going Forwards - Going Backwards 3. Coding 4. Tests """ # T=O(n), S=O(1) class Solution: def canJump(self, nums: List[int]) -> bool: if not nums: return False maxIndex = 0 for i, num in enumerate(nums): if i > maxIndex: ...
""" 1. Clarification 2. Possible solutions - Going Forwards - Going Backwards 3. Coding 4. Tests """ class Solution: def can_jump(self, nums: List[int]) -> bool: if not nums: return False max_index = 0 for (i, num) in enumerate(nums): if i > maxIndex: ...
# Vulcan credentials. credentials = ["TOKEN", "SYMBOL", "PIN"] # Discord webhook URL. webhook_url = "https://discordapp.com/api/webhooks/EXAMPLE_URL" # Check time. check_time = 600000
credentials = ['TOKEN', 'SYMBOL', 'PIN'] webhook_url = 'https://discordapp.com/api/webhooks/EXAMPLE_URL' check_time = 600000
print("first number: ") first = int(input()) print("second number") second = int(input()) sum = first + second print(sum)
print('first number: ') first = int(input()) print('second number') second = int(input()) sum = first + second print(sum)
"""Fast Close by One. cf. J. Outrata, and V. Vychodil. Fast algorithm for computing fixpoints of Galois connections induced by object-attribute relational data. Information Sciences 185.1 (2012): 114-127. https://doi.org/10.1016/j.ins.2011.09.023 """ __all__ = ['fast_generate_from', 'fcbo_dual'] def fast_generate_f...
"""Fast Close by One. cf. J. Outrata, and V. Vychodil. Fast algorithm for computing fixpoints of Galois connections induced by object-attribute relational data. Information Sciences 185.1 (2012): 114-127. https://doi.org/10.1016/j.ins.2011.09.023 """ __all__ = ['fast_generate_from', 'fcbo_dual'] def fast_generate_fro...
""" Given a sorted list of intervals, insert a given interval to it's rightful place, merge overlapping intervals caused by the insertion of new interval eg [[1,2], [3,5], [7,9]], [4, 6] [[1,2], [3,6], [7,9]] """ class Interval: def __init__(self, start, end): self.start = start self.end = end ...
""" Given a sorted list of intervals, insert a given interval to it's rightful place, merge overlapping intervals caused by the insertion of new interval eg [[1,2], [3,5], [7,9]], [4, 6] [[1,2], [3,6], [7,9]] """ class Interval: def __init__(self, start, end): self.start = start self.end = end ...
#belajar python #saya ingin menampilkan angka kelipatan 3 antara 1-100 x=3 for i in range(100): print(' '.format(x)) x=x+3 #saya ingin menampilkan angka kuadrat 1 sampai 10 for i in range(10): x=i**2 print(x)
x = 3 for i in range(100): print(' '.format(x)) x = x + 3 for i in range(10): x = i ** 2 print(x)
set_name(0x800A03CC, "VID_OpenModule__Fv", SN_NOWARN) set_name(0x800A048C, "InitScreens__Fv", SN_NOWARN) set_name(0x800A057C, "MEM_SetupMem__Fv", SN_NOWARN) set_name(0x800A05A8, "SetupWorkRam__Fv", SN_NOWARN) set_name(0x800A0638, "SYSI_Init__Fv", SN_NOWARN) set_name(0x800A073C, "GM_Open__Fv", SN_NOWARN) set_name(0x800A...
set_name(2148139980, 'VID_OpenModule__Fv', SN_NOWARN) set_name(2148140172, 'InitScreens__Fv', SN_NOWARN) set_name(2148140412, 'MEM_SetupMem__Fv', SN_NOWARN) set_name(2148140456, 'SetupWorkRam__Fv', SN_NOWARN) set_name(2148140600, 'SYSI_Init__Fv', SN_NOWARN) set_name(2148140860, 'GM_Open__Fv', SN_NOWARN) set_name(214814...
tab=list(set([' 1',' 2',' 3',' 4',' 5',' 6',' 7',' 8',' 9','10','11','12','13','14','15',' '])) while tab!=[' ', '15', '14', '13', '12', '11', '10', ' 9', ' 8', ' 7', ' 6', ' 5', ' 4', ' 3', ' 2', ' 1',]: print(tab[:4]) or print(tab[4:8]) print(tab[8:12]) or print(tab[12:]) com=input('Enter a comand: ')...
tab = list(set([' 1', ' 2', ' 3', ' 4', ' 5', ' 6', ' 7', ' 8', ' 9', '10', '11', '12', '13', '14', '15', ' '])) while tab != [' ', '15', '14', '13', '12', '11', '10', ' 9', ' 8', ' 7', ' 6', ' 5', ' 4', ' 3', ' 2', ' 1']: print(tab[:4]) or print(tab[4:8]) print(tab[8:12]) or print(tab[12:]) com = input('...
DISCOUNT = 15 def apply_discount(price, discount): return price * (100 - discount) / 100 basket = [5464.7, 2342.8, 45784.5, 3457.3] basket_sum = sum(basket) print(basket_sum) basket_sum_discounted = 0 discount_1 = 7 for product in basket: basket_sum_discounted += apply_discount(product, discount_1) print(bask...
discount = 15 def apply_discount(price, discount): return price * (100 - discount) / 100 basket = [5464.7, 2342.8, 45784.5, 3457.3] basket_sum = sum(basket) print(basket_sum) basket_sum_discounted = 0 discount_1 = 7 for product in basket: basket_sum_discounted += apply_discount(product, discount_1) print(baske...
RECAPTCHA_ENABLED = False UPLOAD_FOLDER = "tmp" MAX_CONTENT_LENGTH = 7 * 1024 * 1024 LOG = False VERIFY_URL = "https://hcaptcha.com/siteverify" PROPAGATE_EXCEPTIONS = True
recaptcha_enabled = False upload_folder = 'tmp' max_content_length = 7 * 1024 * 1024 log = False verify_url = 'https://hcaptcha.com/siteverify' propagate_exceptions = True
def magic_trick(filename): file = open(filename) out = open("output.txt", "w+") testcases = int(file.readline()) for test in range(0, testcases): ##building the game ans = 0 ans1 = 0 ans2 = 0 count = 0 array1 = [] array2 = [] ans1 = i...
def magic_trick(filename): file = open(filename) out = open('output.txt', 'w+') testcases = int(file.readline()) for test in range(0, testcases): ans = 0 ans1 = 0 ans2 = 0 count = 0 array1 = [] array2 = [] ans1 = int(file.readline()) for i ...
def get_labels(file): labels=set() with open(file,'r',encoding='utf-8') as f: for line in f: try: labels.add(line.split()[1]) except: pass return list(labels) if __name__ == '__main__': labels=get_labels('../../datasets/train.txt') pr...
def get_labels(file): labels = set() with open(file, 'r', encoding='utf-8') as f: for line in f: try: labels.add(line.split()[1]) except: pass return list(labels) if __name__ == '__main__': labels = get_labels('../../datasets/train.txt') ...
model_config = ['create_model_vanilla', 'create_model_vanilla_dropout_batchnormalization', 'create_model_stacked', 'create_model_stacked_dropout_batchnormalization', 'create_model_1d_cnn'] data_config = ['load_data_beijing_multi', 'load_da...
model_config = ['create_model_vanilla', 'create_model_vanilla_dropout_batchnormalization', 'create_model_stacked', 'create_model_stacked_dropout_batchnormalization', 'create_model_1d_cnn'] data_config = ['load_data_beijing_multi', 'load_data_appliances_multi', 'load_data_solar_multi', 'load_data_load_consumption_multi'...
'''def func_retval(): some_int = 5 return some_int def test_func_retval(): assert func_retval() == 4''' def test_sets_compare(): set1 = set("abcd") set2 = set("aced") assert set1 == set2
"""def func_retval(): some_int = 5 return some_int def test_func_retval(): assert func_retval() == 4""" def test_sets_compare(): set1 = set('abcd') set2 = set('aced') assert set1 == set2
class ArgumentsMethods(object): def parse_arguments(self, options): self.YEAR = options["year"] self.STATES = options["states"] def add_arguments(self, parser): parser.add_argument( "states", nargs="+", help="States to export by FIPS code. \ ...
class Argumentsmethods(object): def parse_arguments(self, options): self.YEAR = options['year'] self.STATES = options['states'] def add_arguments(self, parser): parser.add_argument('states', nargs='+', help='States to export by FIPS code. Use 00 to export all geographies.')...
# { 'target_defaults': { 'include_dirs': [ '.', ], 'defines': [ 'BOOST_ALL_NO_LIB=1', ], 'direct_dependent_settings': { 'defines': [ 'BOOST_ALL_NO_LIB=1', ], }, }, 'targets': [ { 'target_name': 'boost_system', 'type': 'st...
{'target_defaults': {'include_dirs': ['.'], 'defines': ['BOOST_ALL_NO_LIB=1'], 'direct_dependent_settings': {'defines': ['BOOST_ALL_NO_LIB=1']}}, 'targets': [{'target_name': 'boost_system', 'type': 'static_library', 'sources': ['libs/system/error_code.cpp', 'libs/system/local_free_on_destruction.hpp'], 'defines': ['BOO...
""" LeetCode Problem: 63. Unique Paths II Link: https://leetcode.com/problems/unique-paths-ii/ Language: Python Written by: Mostofa Adib Shakib Time Complexity: O(M*N) Space Complexity: O(1) """ class Solution: def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: if obstacleGrid[0][0]...
""" LeetCode Problem: 63. Unique Paths II Link: https://leetcode.com/problems/unique-paths-ii/ Language: Python Written by: Mostofa Adib Shakib Time Complexity: O(M*N) Space Complexity: O(1) """ class Solution: def unique_paths_with_obstacles(self, obstacleGrid: List[List[int]]) -> int: if obstacleGrid[0...
class Evaluator(): def evaluate(self): raise NotImplementedError() def clear(self): raise NotImplementedError() class ObjectDetectionEvaluator(Evaluator): __labels = None def add_batch(self, image_shape, pred_boxes, pred_classes, pred_scores, gt_boxes, gt_labels, gt...
class Evaluator: def evaluate(self): raise not_implemented_error() def clear(self): raise not_implemented_error() class Objectdetectionevaluator(Evaluator): __labels = None def add_batch(self, image_shape, pred_boxes, pred_classes, pred_scores, gt_boxes, gt_labels, gt_ids, gt_areas=N...
COMPOUND_TOKEN_ADDRESS = "0xc00e94cb662c3520282e6f5717214004a7f26888" COMPOUND_COMPTROLLER_ADDRESS = "0x3d9819210a31b4961b30ef54be2aed79b9c9cd3b" COMPOUND_RESERVOIR_ADDRESS = "0x2775b1c75658be0f640272ccb8c72ac986009e38" # https://github.com/MyEtherWallet/ethereum-lists DARKLIST = f"https://raw.githubusercontent.com/M...
compound_token_address = '0xc00e94cb662c3520282e6f5717214004a7f26888' compound_comptroller_address = '0x3d9819210a31b4961b30ef54be2aed79b9c9cd3b' compound_reservoir_address = '0x2775b1c75658be0f640272ccb8c72ac986009e38' darklist = f'https://raw.githubusercontent.com/MyEtherWallet/ethereum-lists/master/src/addresses/add...
platforms = [ {'collection': 'tweet', 'id': 'twitter', 'sourcePath': ["author", "username"]}, {'collection': 'news', 'id': 'news', 'sourcePath': ["publisher", "name"]}, {'collection': 'facebook_posts', 'id': 'facebook', 'sourcePath': []}, {'collection': 'reddit_posts', 'id': 'reddit', 'sourcePath': ["au...
platforms = [{'collection': 'tweet', 'id': 'twitter', 'sourcePath': ['author', 'username']}, {'collection': 'news', 'id': 'news', 'sourcePath': ['publisher', 'name']}, {'collection': 'facebook_posts', 'id': 'facebook', 'sourcePath': []}, {'collection': 'reddit_posts', 'id': 'reddit', 'sourcePath': ['author']}] class C...
t = int(input()) for _ in range(t): n, k = map(int, input().split()) s = input() u = s.upper() l = s.lower() chef = 0 bro = 0 for i in range(len(s)): if s[i] != l[i]: chef += 1 if s[i] != u[i]: bro += 1 if chef <= k and bro <= k: print("both") elif chef <= k: print("chef") ...
t = int(input()) for _ in range(t): (n, k) = map(int, input().split()) s = input() u = s.upper() l = s.lower() chef = 0 bro = 0 for i in range(len(s)): if s[i] != l[i]: chef += 1 if s[i] != u[i]: bro += 1 if chef <= k and bro <= k: print('b...
"""Base pagination iterator for traversing API respones.""" class BasePaginationIterator: def __init__( self, client, path, params=None, limit=None, per_page=None, cursor=None ): self._client = client self.path = path # Custom params that along every requests self.para...
"""Base pagination iterator for traversing API respones.""" class Basepaginationiterator: def __init__(self, client, path, params=None, limit=None, per_page=None, cursor=None): self._client = client self.path = path self.params = params or {} self.cursor = cursor self.per_p...
length = int(input('Length: ')) width = int(input('Width: ')) area_of_rectangle = length * width perimeter_of_rectangle = 2 * (length + width) print(f'Area: {area_of_rectangle}\nPerimeter: {perimeter_of_rectangle}') # 6
length = int(input('Length: ')) width = int(input('Width: ')) area_of_rectangle = length * width perimeter_of_rectangle = 2 * (length + width) print(f'Area: {area_of_rectangle}\nPerimeter: {perimeter_of_rectangle}')
class RapicException(Exception): """There was an exception that occurred while handling your rapic request. """ def __init__(self, *args, **kwargs): """ Initialize RapicException with `request_data` """ self.request_data = kwargs.pop('request_data', None) ...
class Rapicexception(Exception): """There was an exception that occurred while handling your rapic request. """ def __init__(self, *args, **kwargs): """ Initialize RapicException with `request_data` """ self.request_data = kwargs.pop('request_data', None) ...
""" A package dealing with many-body impurity models using exact diagonalization. Examples of functionalities: - Calculate spectra, e.g. XAS, XPS, PS. - Calculate static expectation values """
""" A package dealing with many-body impurity models using exact diagonalization. Examples of functionalities: - Calculate spectra, e.g. XAS, XPS, PS. - Calculate static expectation values """
class Color: PURPLE = '\033[1m\033[95m' CYAN = '\033[1m\033[96m' DARKCYAN = '\033[1m\033[36m' BLUE = '\033[1m\033[94m' GREEN = '\033[1m\033[92m' YELLOW = '\033[1m\033[93m' RED = '\033[1m\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m'
class Color: purple = '\x1b[1m\x1b[95m' cyan = '\x1b[1m\x1b[96m' darkcyan = '\x1b[1m\x1b[36m' blue = '\x1b[1m\x1b[94m' green = '\x1b[1m\x1b[92m' yellow = '\x1b[1m\x1b[93m' red = '\x1b[1m\x1b[91m' bold = '\x1b[1m' underline = '\x1b[4m' end = '\x1b[0m'
def isWordGuessed(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: boolean, True if all the letters of secretWord are in lettersGuessed; False otherwise ''' # FILL IN YOUR CODE HERE... ...
def is_word_guessed(secretWord, lettersGuessed): """ secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: boolean, True if all the letters of secretWord are in lettersGuessed; False otherwise """ for c in secretWord: ...
class Solution: def reorganizeString(self, S: str) -> str: dic = {} for s in S: dic[s] = dic.get(s,0)+1 h = [] for k,v in dic.items(): if v>(len(S)+1)//2: return '' heapq.heappush(h, (-v, k)) res = "" while ...
class Solution: def reorganize_string(self, S: str) -> str: dic = {} for s in S: dic[s] = dic.get(s, 0) + 1 h = [] for (k, v) in dic.items(): if v > (len(S) + 1) // 2: return '' heapq.heappush(h, (-v, k)) res = '' w...
class LoginCompleter: """ A loop-based completion system for logins """ def __init__(self, menu): self.s = "" self.logins = None self.completions = [] # completion_id has a value of -1 for the base user input # and between 0 and len(completions)-1 for completions ...
class Logincompleter: """ A loop-based completion system for logins """ def __init__(self, menu): self.s = '' self.logins = None self.completions = [] self.completion_id = -1 self.completion_base = '' self.menu = menu def initialize(self): """ Initia...
def flatten(iterable): l = [] for iterator in iterable: if hasattr(iterator, '__iter__'): # Checking if `iterator` is iterable. if any([hasattr(element, '__iter__') for element in iterator]): # Checking if there are any sublists; *flattening* if there are. ...
def flatten(iterable): l = [] for iterator in iterable: if hasattr(iterator, '__iter__'): if any([hasattr(element, '__iter__') for element in iterator]): iterator = flatten(iterator) l.extend([i for i in iterator if i]) elif iterator != None: l...
CONTENT = ''' uwu 0 uwu 1 uwu 2 owo 0 owo 1 owo 2 owo-owo0 owo-owo1 owo-owo2 ''' GREP_RESULT = ''' owo 0 owo-owo0 ''' def test_pipelines(interpreter, capfd, tmp_path): assert interpreter.feed(f'cd {tmp_path}') == False f = tmp_path / 'file.txt' f.write_text(CONTENT) assert interpreter.feed(f'cat {f} | grep "0" |...
content = '\nuwu 0\nuwu 1\nuwu 2\nowo 0\nowo 1\nowo 2\nowo-owo0\nowo-owo1\nowo-owo2\n' grep_result = '\nowo 0\nowo-owo0\n' def test_pipelines(interpreter, capfd, tmp_path): assert interpreter.feed(f'cd {tmp_path}') == False f = tmp_path / 'file.txt' f.write_text(CONTENT) assert interpreter.feed(f'cat {...
class Solution: def isMonotonic(self, A: List[int]) -> bool: isIncreasing = None for idx in range(1, len(A)): diff = A[idx] - A[idx - 1] if diff == 0: continue elif isIncreasing is None: isIncreasing = True if...
class Solution: def is_monotonic(self, A: List[int]) -> bool: is_increasing = None for idx in range(1, len(A)): diff = A[idx] - A[idx - 1] if diff == 0: continue elif isIncreasing is None: is_increasing = True if diff > 0 else Fals...
x=100 if x==100: y = "Full" else: y="Nop" #these two codes are the same y= "Full Marks" if x ==100 else "Not Yet" print(y)
x = 100 if x == 100: y = 'Full' else: y = 'Nop' y = 'Full Marks' if x == 100 else 'Not Yet' print(y)
class Coordinate: def __init__(self, x, y): self.x = x self.y = y def distancia(self, other_coord): x_diff = (self.x - other_coord.x)**2 y_diff = (self.y - other_coord.y)**2 return (x_diff + y_diff)**0.5 if __name__ == '__main__': coord_1 = Coordinate(3, 30)...
class Coordinate: def __init__(self, x, y): self.x = x self.y = y def distancia(self, other_coord): x_diff = (self.x - other_coord.x) ** 2 y_diff = (self.y - other_coord.y) ** 2 return (x_diff + y_diff) ** 0.5 if __name__ == '__main__': coord_1 = coordinate(3, 30) ...