content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
'''Common constants.''' NUCLIOTIDES = ('A', 'C', 'G', 'T') # vcf data columns CHROM = 'CHROM' POS = 'POS' ID = 'ID' REF = 'REF' ALT = 'ALT' QUAL = 'QUAL' FILTER = 'FILTER' INFO = 'INFO' FORMAT = 'FORMAT' MANDATORY_FIELDS = (CHROM, POS, ID, REF, ALT, QUAL, FILTER) # Info-section keys NUMBER = 'Number' TYPE = 'Type' ...
"""Common constants.""" nucliotides = ('A', 'C', 'G', 'T') chrom = 'CHROM' pos = 'POS' id = 'ID' ref = 'REF' alt = 'ALT' qual = 'QUAL' filter = 'FILTER' info = 'INFO' format = 'FORMAT' mandatory_fields = (CHROM, POS, ID, REF, ALT, QUAL, FILTER) number = 'Number' type = 'Type' description = 'Description' mandatory_field...
# Link: https://leetcode.com/problems/clone-graph/ # Definition for a undirected graph node # class UndirectedGraphNode: # def __init__(self, x): # self.label = x # self.neighbors = [] class Solution: # @param node, a undirected graph node # @return a undirected graph node def cloneGrap...
class Solution: def clone_graph(self, node): if not node: return None q = [] m = {} head = undirected_graph_node(node.label) q.append(node) m[node] = head while len(q): curr = q.pop() for neighbor in curr.neighbors: ...
load("@bazel_skylib//lib:unittest.bzl", "asserts", "unittest") load(":dot_case.bzl", "dot_case") def _dot_case_test_impl(ctx): env = unittest.begin(ctx) tt = [ ["", ""], ["test", "test"], ["test string", "test.string"], ["Test String", "test.string"], ["dot.case", "dot.c...
load('@bazel_skylib//lib:unittest.bzl', 'asserts', 'unittest') load(':dot_case.bzl', 'dot_case') def _dot_case_test_impl(ctx): env = unittest.begin(ctx) tt = [['', ''], ['test', 'test'], ['test string', 'test.string'], ['Test String', 'test.string'], ['dot.case', 'dot.case'], ['path/case', 'path.case'], ['Test...
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Gender, obj[4]: Age, obj[5]: Education, obj[6]: Occupation, obj[7]: Bar, obj[8]: Coffeehouse, obj[9]: Restaurant20to50, obj[10]: Direction_same, obj[11]: Distance # {"feature": "Bar", "instances": 34, "metric_value": 0.9975, "depth": 1} ...
def find_decision(obj): if obj[7] <= 2.0: if obj[2] > 1: if obj[11] <= 2: if obj[5] <= 3: if obj[4] > 0: if obj[10] <= 0: if obj[8] <= 2.0: if obj[9] <= 1.0: ...
def bin_to_oct(binary): decimal = int(binary, 2) return oct(decimal) def oct_to_bin(octal): decimal = int(octal, 8) return bin(decimal) if __name__ == "__main__": print(bin_to_oct("111")) print(oct_to_bin("7"))
def bin_to_oct(binary): decimal = int(binary, 2) return oct(decimal) def oct_to_bin(octal): decimal = int(octal, 8) return bin(decimal) if __name__ == '__main__': print(bin_to_oct('111')) print(oct_to_bin('7'))
''' Function for insertion sort Time Complexity : O(N) Space Complexity : O(N) Auxilary Space : O(1) ''' def insertionSort(ar): for i in range(1,len(ar)): j = i - 1 elem = ar[i] while(j >= 0 and ar[j] > elem): ar[j + 1] = ar[j] j -= 1 a...
""" Function for insertion sort Time Complexity : O(N) Space Complexity : O(N) Auxilary Space : O(1) """ def insertion_sort(ar): for i in range(1, len(ar)): j = i - 1 elem = ar[i] while j >= 0 and ar[j] > elem: ar[j + 1] = ar[j] j -= 1 ar[j + ...
assert 1 < 2 assert 1 < 2 < 3 assert 5 == 5 == 5 assert (5 == 5) == True assert 5 == 5 != 4 == 4 > 3 > 2 < 3 <= 3 != 0 == 0 assert not 1 > 2 assert not 5 == 5 == True assert not 5 == 5 != 5 == 5 assert not 1 < 2 < 3 > 4 assert not 1 < 2 > 3 < 4 assert not 1 > 2 < 3 < 4
assert 1 < 2 assert 1 < 2 < 3 assert 5 == 5 == 5 assert (5 == 5) == True assert 5 == 5 != 4 == 4 > 3 > 2 < 3 <= 3 != 0 == 0 assert not 1 > 2 assert not 5 == 5 == True assert not 5 == 5 != 5 == 5 assert not 1 < 2 < 3 > 4 assert not 1 < 2 > 3 < 4 assert not 1 > 2 < 3 < 4
def find_salary_threshold(target_payroll, current_salaries): # custom algorithm, not from the book # first i take avg salary based on payroll and total number of current_salaries in current_salaries list # residue is the remainder left after comparing salary with avg_target for any salary that's more than avg_tar...
def find_salary_threshold(target_payroll, current_salaries): avg_target = target_payroll // len(current_salaries) residue = 0 i = 0 while i < len(current_salaries): if current_salaries[i] < avg_target: residue += avg_target - current_salaries[i] i += 1 else: ...
class OrderedMap(dict): def __init__(self,*args,**kwargs): super().__init__(*args, **kwargs) def __iter__(self): return iter(sorted(super().__iter__())) class OrderedSet(set): def __init__(self,lst=[]): super().__init__(lst) def __iter__(self): ...
class Orderedmap(dict): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def __iter__(self): return iter(sorted(super().__iter__())) class Orderedset(set): def __init__(self, lst=[]): super().__init__(lst) def __iter__(self): return iter(sorted(...
class Solution: def luckyNumbers(self, mat): def solve(i, m): for row in mat: if row[i] > m: return False return True ans = [] for row in mat: idx, mn = [], 10 ** 6 for i, ele in enumerate(row): if ele < mn: ...
class Solution: def lucky_numbers(self, mat): def solve(i, m): for row in mat: if row[i] > m: return False return True ans = [] for row in mat: (idx, mn) = ([], 10 ** 6) for (i, ele) in enumerate(row): ...
__author__ = 'marble_xu' DEBUG = False DEBUG_START_X = 110 DEBUG_START_Y = 534 SCREEN_HEIGHT = 600 SCREEN_WIDTH = 800 SCREEN_SIZE = (SCREEN_WIDTH, SCREEN_HEIGHT) ORIGINAL_CAPTION = 'Super Mario Bros.' # COLORS # R G B GRAY = (100, 100, 100) NAVYBLUE = ( 60, 60, 100) WHITE = ...
__author__ = 'marble_xu' debug = False debug_start_x = 110 debug_start_y = 534 screen_height = 600 screen_width = 800 screen_size = (SCREEN_WIDTH, SCREEN_HEIGHT) original_caption = 'Super Mario Bros.' gray = (100, 100, 100) navyblue = (60, 60, 100) white = (255, 255, 255) red = (255, 0, 0) green = (0, 255, 0) forest_gr...
# Find the set of all integers a, b, c, d that satisfy the following conditions: # 0 <= a^3 + b^3 + c^3 + d^3 <= N # a^3 + b^3 = c^ + d3 # 0 <= a, b, c, d <= N def find_satisfy_sets(N): a = 0 d = dict() m = N // 2 while pow(a, 3) <= m: for b in range(a): t = pow(a, 3) + pow(b, 3) ...
def find_satisfy_sets(N): a = 0 d = dict() m = N // 2 while pow(a, 3) <= m: for b in range(a): t = pow(a, 3) + pow(b, 3) if t > m: break if t in d: for cd in d[t]: print(a, b, cd[0], cd[1]) d[...
expected_output = { "slot": { "P6": { "sensor": { "Temp: FC PWM1": {"state": "Fan Speed 45%", "reading": "25 Celsius"} } }, "P7": { "sensor": { "Temp: FC PWM1": {"state": "Fan Speed 45%", "reading": "25 Celsius"} ...
expected_output = {'slot': {'P6': {'sensor': {'Temp: FC PWM1': {'state': 'Fan Speed 45%', 'reading': '25 Celsius'}}}, 'P7': {'sensor': {'Temp: FC PWM1': {'state': 'Fan Speed 45%', 'reading': '25 Celsius'}}}}}
def square_dict(num): return {n: n * n for n in range(1, int(num) + 1)} # py.test exercise_10_27_16.py --cov=exercise_10_27_16.py --cov-report=html def test_square_dict(): assert square_dict(3) == {1: 1, 2: 4, 3: 9} assert square_dict(0) == {} assert square_dict(-1) == {} if __name__ == '__main__': ...
def square_dict(num): return {n: n * n for n in range(1, int(num) + 1)} def test_square_dict(): assert square_dict(3) == {1: 1, 2: 4, 3: 9} assert square_dict(0) == {} assert square_dict(-1) == {} if __name__ == '__main__': print(square_dict(input('Number: ')))
n: int; i: int; somaPares: int; contPares: int mediaPares: float n = int(input("Quantos elementos vai ter o vetor? ")) vet: [int] = [0 for x in range(n)] for i in range(0, n): vet[i] = int(input("Digite um numero: ")) somaPares = 0 contPares = 0 for i in range(0, n): if vet[i] % 2 == 0: somaPares =...
n: int i: int soma_pares: int cont_pares: int media_pares: float n = int(input('Quantos elementos vai ter o vetor? ')) vet: [int] = [0 for x in range(n)] for i in range(0, n): vet[i] = int(input('Digite um numero: ')) soma_pares = 0 cont_pares = 0 for i in range(0, n): if vet[i] % 2 == 0: soma_pares = s...
# create simple dictionary person_one = { 'name': 'tazri', 'age' : 17 } # direct method person_two = person_one; print("person_one : ",person_one); print("person_two : ",person_two); # changing value in person two and see what happen person_two['name'] = 'focasa'; print("\n\nAfter change name in person two ...
person_one = {'name': 'tazri', 'age': 17} person_two = person_one print('person_one : ', person_one) print('person_two : ', person_two) person_two['name'] = 'focasa' print('\n\nAfter change name in person two : ') print('person_one : ', person_one) person_one['name'] = 'tazri' copy_person = person_one.copy() copy_perso...
vHora = float(input("informe o valor da sua hora")) qtdHoras = int(input("informe a quantidade de horas trabalhadas por sua pessoa")) salario = vHora*qtdHoras print(salario) ir = salario*0.11 print(ir) inss = salario*0.08 print(inss) sindicato = salario*0.05 print(sindicato) sLiquido = salario-ir-inss-sindicato print(s...
v_hora = float(input('informe o valor da sua hora')) qtd_horas = int(input('informe a quantidade de horas trabalhadas por sua pessoa')) salario = vHora * qtdHoras print(salario) ir = salario * 0.11 print(ir) inss = salario * 0.08 print(inss) sindicato = salario * 0.05 print(sindicato) s_liquido = salario - ir - inss - ...
BASE_ATTR_TMPL = '_attr_{name}' BASE_ATTR_GET_TMPL = '_attr__get_{name}' BASE_ATTR_SET_TMPL = '_attr__set_{name}' def mixin(cls): return cls
base_attr_tmpl = '_attr_{name}' base_attr_get_tmpl = '_attr__get_{name}' base_attr_set_tmpl = '_attr__set_{name}' def mixin(cls): return cls
def findDecision(obj): #obj[0]: Driving_to, obj[1]: Passanger, obj[2]: Weather, obj[3]: Temperature, obj[4]: Time, obj[5]: Coupon, obj[6]: Coupon_validity, obj[7]: Gender, obj[8]: Age, obj[9]: Maritalstatus, obj[10]: Children, obj[11]: Education, obj[12]: Occupation, obj[13]: Income, obj[14]: Bar, obj[15]: Coffeehouse,...
def find_decision(obj): if obj[5] > 1: if obj[15] > 0.0: if obj[18] > 0.0: if obj[12] <= 7: if obj[8] <= 6: if obj[14] > 0.0: if obj[19] <= 0: if obj[17] > 2.0: ...
def support_map_vectorized1(linked,num_indirect_equal_direct=3): # columns # 'team_j', 'team_i_name', 'team_i_score', 'team_i_H_A_N', # 'team_j_i_score', 'team_j_i_H_A_N', 'game_i_j', 'team_k_name', # 'team_k_score', 'team_k_H_A_N', 'team_j_k_score', 'team_j_k_H_A_N', # 'game_k_j' linked["direc...
def support_map_vectorized1(linked, num_indirect_equal_direct=3): linked['direct'] = linked['team_i_name'] == linked['team_k_name'] for_index1 = linked[['team_i_name', 'team_k_name']].copy() for_index1.loc[linked['direct']] = linked.loc[linked['direct'], ['team_i_name', 'team_j_name']] for_index1.column...
# Algorith of Attraction # @author unobatbayar # Basic information used: Physical, Status, Character, Chemistry # Let's just give points for each trait, however, minus points if not her preference points = 0 # will give points depending on traits below questions = ["He has a symmetrical face:", "He has ...
points = 0 questions = ['He has a symmetrical face:', 'He has a good smell:', 'He is handsome:', 'He is well dressed or looking good:', 'He has clear skin, bright eyes, fit body:', 'He is powerful (financial, physical, Informational or etc):', 'He is ambitious, motivated:', 'He has a great job or holds a reputable posi...
class Solution: def maxDiff(self, num: int) -> int: num = str(num) d = [int(c) for c in num] d = list(set(d)) res = [] for x in d: for y in range(0, 10): p = str(num) p = p.replace(str(x), str(y)) if p[0] != '0' and ...
class Solution: def max_diff(self, num: int) -> int: num = str(num) d = [int(c) for c in num] d = list(set(d)) res = [] for x in d: for y in range(0, 10): p = str(num) p = p.replace(str(x), str(y)) if p[0] != '0' an...
phonebook = {} phonebook["John"] = 938477566 phonebook["Jack"] = 938377264 phonebook["Jill"] = 947662781 print(phonebook) phonebook = { "John" : 938477566, "Jack" : 938377264, "Jill" : 947662781 } print(phonebook) phonebook = {"John" : 938477566,"Jack" : 938377264,"Jill" : 947662781} for name, number in p...
phonebook = {} phonebook['John'] = 938477566 phonebook['Jack'] = 938377264 phonebook['Jill'] = 947662781 print(phonebook) phonebook = {'John': 938477566, 'Jack': 938377264, 'Jill': 947662781} print(phonebook) phonebook = {'John': 938477566, 'Jack': 938377264, 'Jill': 947662781} for (name, number) in phonebook.items(): ...
INTRAHEALTH_DOMAINS = ('ipm-senegal', 'testing-ipm-senegal', 'ct-apr') OPERATEUR_XMLNSES = ( 'http://openrosa.org/formdesigner/7330597b92db84b1a33c7596bb7b1813502879be', 'http://openrosa.org/formdesigner/EF8B5DB8-4FB2-4CFB-B0A2-CDD26ADDAE3D' ) COMMANDE_XMLNSES = ( 'http://openrosa.org/formdesigner/9ED6673...
intrahealth_domains = ('ipm-senegal', 'testing-ipm-senegal', 'ct-apr') operateur_xmlnses = ('http://openrosa.org/formdesigner/7330597b92db84b1a33c7596bb7b1813502879be', 'http://openrosa.org/formdesigner/EF8B5DB8-4FB2-4CFB-B0A2-CDD26ADDAE3D') commande_xmlnses = ('http://openrosa.org/formdesigner/9ED66735-752D-4C69-B9C8-...
# This method computes the name (and IDs) of the features by recursion def addNames(curName, curd, targetd, lasti, curID,options,names,ids,N): if curd<targetd: for i in range(lasti,N): addNames(curName + (' * ' if len(curName)>0 else '') + options[i], curd + 1, targetd, i + 1, curID + [i], optio...
def add_names(curName, curd, targetd, lasti, curID, options, names, ids, N): if curd < targetd: for i in range(lasti, N): add_names(curName + (' * ' if len(curName) > 0 else '') + options[i], curd + 1, targetd, i + 1, curID + [i], options, names, ids, N) elif curd == targetd: names.a...
class Full(Exception): pass class Empty(Exception): pass class Queue(object): def __init__(self, maxSize = 0): self._list = [] self._maxQueued = maxSize def push(self, i): if self._maxQueued and len(self._list) >= self._maxQueued: raise Full else: ...
class Full(Exception): pass class Empty(Exception): pass class Queue(object): def __init__(self, maxSize=0): self._list = [] self._maxQueued = maxSize def push(self, i): if self._maxQueued and len(self._list) >= self._maxQueued: raise Full else: ...
def validate_coordinates(row, col): return 0 <= row < matrix_size and 0 <= col < matrix_size matrix_size = int(input()) matrix = [[int(num) for num in input().split()] for _ in range(matrix_size)] line = input() while not line == "END": command, row, col, value = line.split() row = int(row) col = int...
def validate_coordinates(row, col): return 0 <= row < matrix_size and 0 <= col < matrix_size matrix_size = int(input()) matrix = [[int(num) for num in input().split()] for _ in range(matrix_size)] line = input() while not line == 'END': (command, row, col, value) = line.split() row = int(row) col = int(...
def animated_player_mgt(game_mgr): def fn_get_action(board): # fn_display(board_pieces) valid_moves = game_mgr.fn_get_valid_moves(board, 1) if valid_moves is None: return None for i in range(len(valid_moves)): if valid_moves[i]: print("[", int...
def animated_player_mgt(game_mgr): def fn_get_action(board): valid_moves = game_mgr.fn_get_valid_moves(board, 1) if valid_moves is None: return None for i in range(len(valid_moves)): if valid_moves[i]: print('[', int(i / game_mgr.fn_get_board_size()),...
class Solution: def titleToNumber(self, columnTitle: str) -> int: ans = 0 for i in range(len(columnTitle)): temp = pow(26,len(columnTitle)-1-i)*(ord(columnTitle[i])-ord('A')+1) ans+=temp return ans
class Solution: def title_to_number(self, columnTitle: str) -> int: ans = 0 for i in range(len(columnTitle)): temp = pow(26, len(columnTitle) - 1 - i) * (ord(columnTitle[i]) - ord('A') + 1) ans += temp return ans
def add_matrix(): if r1==r2 and c1==c2: print("Addition Matrix of Given matrices is:") for i in range(r1): for j in range(c1): print(m1[i][j]+m2[i][j], end=" ") print() else: print("Error! Can't Add them!!") r1=int(input("Enter no of rows in the m...
def add_matrix(): if r1 == r2 and c1 == c2: print('Addition Matrix of Given matrices is:') for i in range(r1): for j in range(c1): print(m1[i][j] + m2[i][j], end=' ') print() else: print("Error! Can't Add them!!") r1 = int(input('Enter no of rows i...
''' Created on Nov 7, 2016 @author: matth ''' class init(object): ''' This will set up all of the initial systems that need to be started when a new flight is requested. ''' def __init__(self): ''' Constructor ''' def start(self): ''' This is what...
""" Created on Nov 7, 2016 @author: matth """ class Init(object): """ This will set up all of the initial systems that need to be started when a new flight is requested. """ def __init__(self): """ Constructor """ def start(self): """ This is what will be ...
pkgname = "ncurses" pkgver = "6.3" pkgrel = 0 build_style = "gnu_configure" configure_args = [ "--enable-widec", "--enable-big-core", "--enable-ext-colors", "--enable-pc-files", "--without-debug", "--without-ada", "--with-shared", "--with-manpage-symlinks", "--with-manpage-format=normal", "--with-pk...
pkgname = 'ncurses' pkgver = '6.3' pkgrel = 0 build_style = 'gnu_configure' configure_args = ['--enable-widec', '--enable-big-core', '--enable-ext-colors', '--enable-pc-files', '--without-debug', '--without-ada', '--with-shared', '--with-manpage-symlinks', '--with-manpage-format=normal', '--with-pkg-config-libdir=/usr/...
def flatten(dd, prefix=''): def flatten_impl(dd): if (type(dd) == dict): nextKey = [*dd][0] return '[' + nextKey + ']' + flatten(dd[nextKey]) else: return '=' + str(dd) return prefix + flatten_impl(dd)
def flatten(dd, prefix=''): def flatten_impl(dd): if type(dd) == dict: next_key = [*dd][0] return '[' + nextKey + ']' + flatten(dd[nextKey]) else: return '=' + str(dd) return prefix + flatten_impl(dd)
def is_palindrom(permutation: str) -> bool: if not permutation: return False permutation = permutation.replace(' ', '').lower() store = {} odd = 0 for letter in permutation: if letter not in store: store[letter] = 0 store[letter] += 1 if store[letter] %...
def is_palindrom(permutation: str) -> bool: if not permutation: return False permutation = permutation.replace(' ', '').lower() store = {} odd = 0 for letter in permutation: if letter not in store: store[letter] = 0 store[letter] += 1 if store[letter] % 2 ...
# Suppose a sorted array is rotated at some pivot unknown to you beforehand. # (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). # Find the minimum element. # The array may contain duplicates. def find_min(numbers): size = len(numbers) if size == 0: return 0 elif size == 1: return numbers[...
def find_min(numbers): size = len(numbers) if size == 0: return 0 elif size == 1: return numbers[0] elif size == 2: return min(numbers[0], numbers[1]) start = 0 stop = size - 1 while start < stop - 1: if numbers[start] < numbers[stop]: return numbe...
''' gsconfig is a python library for manipulating a GeoServer instance via the GeoServer RESTConfig API. The project is distributed under a MIT License . ''' __author__ = "David Winslow" __copyright__ = "Copyright 2012-2015 Boundless, Copyright 2010-2012 OpenPlans" __license__ = "MIT" # shapefile_and_friends = None ...
""" gsconfig is a python library for manipulating a GeoServer instance via the GeoServer RESTConfig API. The project is distributed under a MIT License . """ __author__ = 'David Winslow' __copyright__ = 'Copyright 2012-2015 Boundless, Copyright 2010-2012 OpenPlans' __license__ = 'MIT' def shapefile_and_friends(path):...
class LoginFlags: CONSOLE = 1 GUI = 2
class Loginflags: console = 1 gui = 2
def tree(p, n): return [1 if i==0 or i==n-1 else p[i-1]+p[i] for i in range(n)] #weird stuff List=[] n=1 arr=[1] while n!=30: #change this for your own length arr=euclidtree(arr,n) List.append(arr) n += 1 s_len = len(" ".join(map(str,List[-1]))) for el in List: s = " ".join(map(str,el...
def tree(p, n): return [1 if i == 0 or i == n - 1 else p[i - 1] + p[i] for i in range(n)] list = [] n = 1 arr = [1] while n != 30: arr = euclidtree(arr, n) List.append(arr) n += 1 s_len = len(' '.join(map(str, List[-1]))) for el in List: s = ' '.join(map(str, el)) print(str.center(s, s_len)) inp...
# # @lc app=leetcode id=102 lang=python3 # # [102] Binary Tree Level Order Traversal # # @lc code=start # 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...
class Solution: def level_order(self, root: TreeNode) -> List[List[int]]: if root is None: return [] result = [] trees = [root] while trees: result.append([t.val for t in trees]) new_trees = [] for t in trees: if t.left...
while(True): try: a,b=list(map(int,input().split())) if(a==b): break else: if(a<b): print("Crescente") else: print("Decrescente") except EOFError: break
while True: try: (a, b) = list(map(int, input().split())) if a == b: break elif a < b: print('Crescente') else: print('Decrescente') except EOFError: break
microcode = ''' def macroop VADDSS_XMM_XMM { maddf xmm0, xmm0v, xmm0m, size=4, ext=Scalar movfph2h dest=xmm0, src1=xmm0v, dataSize=4 movfp dest=xmm1, src1=xmm1v, dataSize=8 vclear dest=xmm2, destVL=16 }; def macroop VADDSS_XMM_M { movfp dest=xmm0, src1=xmm0v, dataSize=8 movfp dest=xmm1, src1=x...
microcode = '\ndef macroop VADDSS_XMM_XMM {\n maddf xmm0, xmm0v, xmm0m, size=4, ext=Scalar\n movfph2h dest=xmm0, src1=xmm0v, dataSize=4\n movfp dest=xmm1, src1=xmm1v, dataSize=8\n vclear dest=xmm2, destVL=16\n};\n\ndef macroop VADDSS_XMM_M {\n movfp dest=xmm0, src1=xmm0v, dataSize=8\n movfp dest=xmm1,...
def our_decorator(func): def function_wrapper(x): print("Before calling " + func.__name__) func(x) print("After calling " + func.__name__) return function_wrapper @our_decorator def foo(x): print("Hi, foo has been called with " + str(x)) foo("Hi")
def our_decorator(func): def function_wrapper(x): print('Before calling ' + func.__name__) func(x) print('After calling ' + func.__name__) return function_wrapper @our_decorator def foo(x): print('Hi, foo has been called with ' + str(x)) foo('Hi')
class Solution: def wiggleMaxLength(self, nums): if len(nums) <= 2: return 0 if not nums else 1 if nums[0] == nums[-1] else 2 inc = nums[0] < nums[1] if nums[0] != nums[1] else None cnt = 2 if inc != None else 1 for i in range(2, len(nums)): if nums[i - 1] != nums[i] and ...
class Solution: def wiggle_max_length(self, nums): if len(nums) <= 2: return 0 if not nums else 1 if nums[0] == nums[-1] else 2 inc = nums[0] < nums[1] if nums[0] != nums[1] else None cnt = 2 if inc != None else 1 for i in range(2, len(nums)): if nums[i - 1] ...
# Python - 3.6.0 test.assert_equals(is_palindrome('anna'), True) test.assert_equals(is_palindrome('walter'), False) test.assert_equals(is_palindrome(12321), True) test.assert_equals(is_palindrome(123456), False)
test.assert_equals(is_palindrome('anna'), True) test.assert_equals(is_palindrome('walter'), False) test.assert_equals(is_palindrome(12321), True) test.assert_equals(is_palindrome(123456), False)
# # PySNMP MIB module MYLEXRAID-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MYLEXRAID-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:16:50 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_union, constraints_intersection, single_value_constraint, value_size_constraint) ...
n, x = map(int, input().split()) students = [] for _ in range(x): students.append(map(float, input().split())) for i in zip(*students): print(sum(i) / len(i))
(n, x) = map(int, input().split()) students = [] for _ in range(x): students.append(map(float, input().split())) for i in zip(*students): print(sum(i) / len(i))
#A while statement will repeatedly execute a single statement or group of statements as long as the condition is true. # The reason it is called a 'loop' is because the code statements are looped through over and over again until the condition is no longer met. # Example x = 0 while x < 10: print('x is currently...
x = 0 while x < 10: print('x is currently: ', x) print(' x is still less than 10, adding 1 to x') x += 1 else: print('All Done!') '\nbreak: Breaks out of the current closest enclosing loop.\ncontinue: Goes to the top of the closest enclosing loop.\npass: Does nothing at all.' x = 0 while x < 10: pri...
''' Module for pretrained models to be used for transfer learning Import modules to register class names in global registry ''' __author__ = 'Elisha Yadgaran'
""" Module for pretrained models to be used for transfer learning Import modules to register class names in global registry """ __author__ = 'Elisha Yadgaran'
class Action: def __init__(self, head, arg_types, goal, precond): self.head = head self.arg_types = arg_types self.goal = goal self.precond = precond
class Action: def __init__(self, head, arg_types, goal, precond): self.head = head self.arg_types = arg_types self.goal = goal self.precond = precond
class LuxDevice: def __init__(self, serial_number, is_connected=True, temperature=None): self.serial_number = serial_number self.__temperature = temperature self.is_connected = is_connected @property def temperature(self): return self.__temperature @temperature.setter ...
class Luxdevice: def __init__(self, serial_number, is_connected=True, temperature=None): self.serial_number = serial_number self.__temperature = temperature self.is_connected = is_connected @property def temperature(self): return self.__temperature @temperature.setter ...
''' Bing.com page objects as CSS selectors ''' class Page(object): search_box = 'input.b_searchbox' search_button = 'input[name="go"]' search_results = '#b_results'
""" Bing.com page objects as CSS selectors """ class Page(object): search_box = 'input.b_searchbox' search_button = 'input[name="go"]' search_results = '#b_results'
class PossibilitySet: def __init__(self, dependencies, possibilities): self.dependencies = dependencies self.possibilities = possibilities @property def latest_version(self): if self.possibilities: return self.possibilities[-1] def __str__(self): return '[{...
class Possibilityset: def __init__(self, dependencies, possibilities): self.dependencies = dependencies self.possibilities = possibilities @property def latest_version(self): if self.possibilities: return self.possibilities[-1] def __str__(self): return '[{...
#!/usr/bin/env python # Copyright 2018 National Technology & Engineering Solutions of Sandia, LLC # (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. # Government retains certain rights in this software. allowable_variable_chars = set( 'abcdefghijklmnopqrstuvwxyz' ...
allowable_variable_chars = set('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_') allowable_word_chars = allowable_variable_chars.union('.-=+#@^%:~') allowable_param_value_chars = allowable_word_chars.union('<>!') allowable_wildcard_expression_chars = allowable_word_chars.union('*?[]!') def allowable_w...
s = input() if len(s) > 0: s = s.strip()[:-1] print(' '.join(map(str, map(len, s.split()))))
s = input() if len(s) > 0: s = s.strip()[:-1] print(' '.join(map(str, map(len, s.split()))))
a=int(input('Digite a altura: ')) b=int(input('Digite a largura: ')) area= a*b tinta= area/2 print('Vai precisar de {}L de tinta'.format(tinta))
a = int(input('Digite a altura: ')) b = int(input('Digite a largura: ')) area = a * b tinta = area / 2 print('Vai precisar de {}L de tinta'.format(tinta))
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. class BaseReporter(object): def __init__(self, metric_provider): self.metrics = [] self.metric_provider...
class Basereporter(object): def __init__(self, metric_provider): self.metrics = [] self.metric_provider = metric_provider def track_metric(self, metric): self.metrics.append(metric) def get_metric_values(self): metric_values = {} for metric in self.metrics: ...
infile = open("hotels.txt", "r") hotels = [] for line in infile: [hotel, stars, review] = line.split(";") hotels.append([hotel, int(stars), float(review)]) infile.close() # print(hotels) star = int(input()) found_hotels = [] for h in hotels: if h[1] >= star: found_hotels.append([h[2], h[1], h[0]]) f...
infile = open('hotels.txt', 'r') hotels = [] for line in infile: [hotel, stars, review] = line.split(';') hotels.append([hotel, int(stars), float(review)]) infile.close() star = int(input()) found_hotels = [] for h in hotels: if h[1] >= star: found_hotels.append([h[2], h[1], h[0]]) found_hotels.sort...
class App(object): name = 'AppName' def __init__(self, tManager): self.textManager = tManager self.playerList = [] self.__running = False def help(self): ''' Print the help message ''' return '' def start(self): ''' Wrapper for __start ''...
class App(object): name = 'AppName' def __init__(self, tManager): self.textManager = tManager self.playerList = [] self.__running = False def help(self): """ Print the help message """ return '' def start(self): """ Wrapper for __start """ self....
class Solution: def XXX(self, l1: ListNode, l2: ListNode) -> ListNode: p1 = l1 p2 = l2 res = ListNode() res_head = res carry = 0 while p1 and p2: res.next = ListNode() res = res.next res.val = p1.val + p2.val + carry car...
class Solution: def xxx(self, l1: ListNode, l2: ListNode) -> ListNode: p1 = l1 p2 = l2 res = list_node() res_head = res carry = 0 while p1 and p2: res.next = list_node() res = res.next res.val = p1.val + p2.val + carry ...
INITIATED = 'INIT' PAID = 'PAID' FAILED = 'FAIL' PAYMENT_STATUS_CHOICES = ( (INITIATED, 'Initiated'), (PAID, 'Paid'), (FAILED, 'Failed'), )
initiated = 'INIT' paid = 'PAID' failed = 'FAIL' payment_status_choices = ((INITIATED, 'Initiated'), (PAID, 'Paid'), (FAILED, 'Failed'))
# python program Swap # two nibbles in a byte def swapNibbles(x): return ( (x & 0x0F)<<4 | (x & 0xF0)>>4 ) # Driver code x = 100 print(swapNibbles(x))
def swap_nibbles(x): return (x & 15) << 4 | (x & 240) >> 4 x = 100 print(swap_nibbles(x))
class Node: def __init__(self, data=None): self.data = data self.out_edges = [] self.in_edges = [] def outgoing_edges(self): return self.out_edges def incoming_edges(self): return self.in_edges def edges(self): return self.out_edges + self.in_edges ...
class Node: def __init__(self, data=None): self.data = data self.out_edges = [] self.in_edges = [] def outgoing_edges(self): return self.out_edges def incoming_edges(self): return self.in_edges def edges(self): return self.out_edges + self.in_edges ...
with open("input.txt") as x: lines = x.read().splitlines() rules = lines[:20] ticket = lines[22] nearby = lines[25:] rularr = {} for r in rules: f, rules = r.split(": ") rules = rules.split(" or ") rules = [rule.split("-") for rule in rules] ruld[f] = [[int(n) for n in r] for r in rule...
with open('input.txt') as x: lines = x.read().splitlines() rules = lines[:20] ticket = lines[22] nearby = lines[25:] rularr = {} for r in rules: (f, rules) = r.split(': ') rules = rules.split(' or ') rules = [rule.split('-') for rule in rules] ruld[f] = [[int(n) for n in r] for r in rule...
#encoding:utf-8 subreddit = 'quotes' t_channel = '@lyricalquotes' def send_post(submission, r2t): return r2t.send_simple(submission, disable_web_page_preview=True)
subreddit = 'quotes' t_channel = '@lyricalquotes' def send_post(submission, r2t): return r2t.send_simple(submission, disable_web_page_preview=True)
my_dictionary={ "nama": "Elyas", "tinggal": "Probolinggo", "year": 2000 } print(my_dictionary) my_dictionary= {'warna': 'merah', 1: [2,3,5]} print(my_dictionary[1][-1])
my_dictionary = {'nama': 'Elyas', 'tinggal': 'Probolinggo', 'year': 2000} print(my_dictionary) my_dictionary = {'warna': 'merah', 1: [2, 3, 5]} print(my_dictionary[1][-1])
# Defines number of epochs n_epochs = 1000 for epoch in range(n_epochs): # Sets model to TRAIN mode model.train() # Step 1 - Computes model's predicted output - forward pass yhat = model(x_train_tensor) # Step 2 - Computes the loss loss = loss_fn(yhat, y_train_tensor) # Step 3 - Com...
n_epochs = 1000 for epoch in range(n_epochs): model.train() yhat = model(x_train_tensor) loss = loss_fn(yhat, y_train_tensor) loss.backward() optimizer.step() optimizer.zero_grad()
# parsetab.py # This file is automatically generated. Do not edit. # pylint: disable=W,C,R _tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'leftPLUSMINUSleftTIMESDIVIDEPERCENTrightUMINUSCIRCLE COMMA DIVIDE DO DOUBLE DOUBLE_CONST ECHO ELSE ENDIF ENDSUBROUTINE ENDWHILE EQUALITY EQUALS FOR GREATER_EQUAL GREATE...
_tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'leftPLUSMINUSleftTIMESDIVIDEPERCENTrightUMINUSCIRCLE COMMA DIVIDE DO DOUBLE DOUBLE_CONST ECHO ELSE ENDIF ENDSUBROUTINE ENDWHILE EQUALITY EQUALS FOR GREATER_EQUAL GREATER_THAN IF INPUT INT INT_CONST LBRACKET LESS_EQUAL LESS_THAN LPAREN MINUS NEWLINE NEXT NOT_EQUA...
KEY_LABEL_BOXES_3D = 'label_boxes_3d' KEY_LABEL_ANCHORS = 'label_anchors' KEY_LABEL_CLASSES = 'label_classes' KEY_LABEL_SEG = 'label_seg' KEY_IMAGE_INPUT = 'image_input' KEY_BEV_INPUT = 'bev_input' KEY_BEV_PSE_INPUT = 'bev_pse_input' KEY_SEG_INPUT = 'seg_input' KEY_SAMPLE_IDX = 'sample_idx' KEY_SAMPLE_NAME = 's...
key_label_boxes_3_d = 'label_boxes_3d' key_label_anchors = 'label_anchors' key_label_classes = 'label_classes' key_label_seg = 'label_seg' key_image_input = 'image_input' key_bev_input = 'bev_input' key_bev_pse_input = 'bev_pse_input' key_seg_input = 'seg_input' key_sample_idx = 'sample_idx' key_sample_name = 'sample_n...
print("This program returns prevalence, sensitivity, specificity, positive predictive value, and negative predictive value.") tp = "" tn = "" fp = "" fn = "" def get_diagnostic_parameter_from_user(parameter, message:str): while type(parameter) != int: parameter = input(message) try: par...
print('This program returns prevalence, sensitivity, specificity, positive predictive value, and negative predictive value.') tp = '' tn = '' fp = '' fn = '' def get_diagnostic_parameter_from_user(parameter, message: str): while type(parameter) != int: parameter = input(message) try: pa...
def reverse(nums): start = 0 end = len(nums) - 1 while end > start: nums[start], nums[end] = nums[end], nums[start] start += 1 end -= 1 if __name__ == "__main__": n = [1, 2, 3, 4] reverse(n) print(n)
def reverse(nums): start = 0 end = len(nums) - 1 while end > start: (nums[start], nums[end]) = (nums[end], nums[start]) start += 1 end -= 1 if __name__ == '__main__': n = [1, 2, 3, 4] reverse(n) print(n)
load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies") load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies") def rules_nfpm_setup(nogo = None): go_rules_dependencies() go_register_toolchains(nogo = nogo) gazelle_dependencies()
load('@io_bazel_rules_go//go:deps.bzl', 'go_register_toolchains', 'go_rules_dependencies') load('@bazel_gazelle//:deps.bzl', 'gazelle_dependencies') def rules_nfpm_setup(nogo=None): go_rules_dependencies() go_register_toolchains(nogo=nogo) gazelle_dependencies()
# Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. DEPS = [ 'codesearch', ] def RunSteps(api): api.codesearch.set_config('base') api.codesearch.run_clang_tool() def GenTests(api): yield ( ap...
deps = ['codesearch'] def run_steps(api): api.codesearch.set_config('base') api.codesearch.run_clang_tool() def gen_tests(api): yield api.test('basic') yield (api.test('run_translation_unit_clang_tool_failed') + api.step_data('run translation_unit clang tool', retcode=1))
# # @lc app=leetcode id=326 lang=python3 # # [326] Power of Three # # @lc code=start class Solution: def isPowerOfThree(self, n: int) -> bool: if n <= 0: return False if n == 1: return True if n % 3 != 0: return False return self.isPowerOfThree...
class Solution: def is_power_of_three(self, n: int) -> bool: if n <= 0: return False if n == 1: return True if n % 3 != 0: return False return self.isPowerOfThree(n // 3)
# # @lc app=leetcode.cn id=337 lang=python3 # # [337] house-robber-iii # None # @lc code=end
None
#!/usr/bin/python class Game: def __init__(self, team1, team1players, team2, team2players, date): self.team1 = team1 self.team1players = team1players self.team2 = team2 self.team2players = team2players self.date = date self.team1Score = 0 self.team2Score = 0...
class Game: def __init__(self, team1, team1players, team2, team2players, date): self.team1 = team1 self.team1players = team1players self.team2 = team2 self.team2players = team2players self.date = date self.team1Score = 0 self.team2Score = 0 def get_score...
def make_form(args, action, method='post', cls='payment-form'): html = "<meta http-equiv='content-type' content='text/html; charset=utf-8'>" html += '<form class="{}" action="{}" method="{}">'.format(cls, action, method) for k, v in args.items(): html += '<div>{}<input name="{}" value="{}" /></div>'...
def make_form(args, action, method='post', cls='payment-form'): html = "<meta http-equiv='content-type' content='text/html; charset=utf-8'>" html += '<form class="{}" action="{}" method="{}">'.format(cls, action, method) for (k, v) in args.items(): html += '<div>{}<input name="{}" value="{}" /></div...
if __name__ == '__main__': k1, k2 = map(int, input().split()) n = int(input()) row_sum = [0] * k1 col_sum = [0] * k2 all_sum = 0 real = {} for _ in range(n): x, y = map(int, input().split()) x -= 1 y -= 1 real[(x, y)] = real.get((x, y), 0) + 1 row_su...
if __name__ == '__main__': (k1, k2) = map(int, input().split()) n = int(input()) row_sum = [0] * k1 col_sum = [0] * k2 all_sum = 0 real = {} for _ in range(n): (x, y) = map(int, input().split()) x -= 1 y -= 1 real[x, y] = real.get((x, y), 0) + 1 row_su...
# Substring with Concatenation of All Words # You are given a string s and an array of strings words of the same length. # Return all starting indices of substring(s) in s that is a concatenation of each word # in words exactly once, in any order, and without any intervening characters. # You can return the answer in ...
def find_substring(s, words): window = 0 res = [] for ele in words: window += len(ele) if len(s) < window: return [] (start, end) = (0, window) while end <= len(s): substring = True redundant_words = {} for ele in words: if words.count(ele) != ...
def testmethod(f): f.__testmethod__=True return f
def testmethod(f): f.__testmethod__ = True return f
# Bootstrap class for flash alerts class Flash_Alerts(): SUCCESS = 'success' ERROR = 'danger' INFO = 'info' WARNING = 'warning' ALERT = Flash_Alerts()
class Flash_Alerts: success = 'success' error = 'danger' info = 'info' warning = 'warning' alert = flash__alerts()
a=4 b=2 c=a-b print(c)
a = 4 b = 2 c = a - b print(c)
def diap_to_prefix(a, b): def inner(aa, bb, p): if p == 1: if a <= aa <= b: yield aa return for d in range(aa, bb + 1, p): if a <= d and d + p - 1 <= b: yield d // p elif not (bb < a or aa > b): for i in...
def diap_to_prefix(a, b): def inner(aa, bb, p): if p == 1: if a <= aa <= b: yield aa return for d in range(aa, bb + 1, p): if a <= d and d + p - 1 <= b: yield (d // p) elif not (bb < a or aa > b): for i ...
IMAGE_BLACK = [ # 0X00,0X01,0XC8,0X00,0XC8,0X00, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF, 0XFF,0XFF,0XFF,0XFF,0XF...
image_black = [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, ...
# grid illusion # settings pw = ph = 600 grid_lines = 9 bar_s = 11 cell_s = pw/grid_lines dot_f = 1.25 # drawings newPage(pw, ph) rect(0, 0, pw, ph) fill(.5) # the grid for i in range(grid_lines): rect(cell_s*i + cell_s/2 -bar_s/2, 0, bar_s, ph) rect(0, cell_s*i + cell_s/2 -bar_s/2, pw, bar_s) # the do...
pw = ph = 600 grid_lines = 9 bar_s = 11 cell_s = pw / grid_lines dot_f = 1.25 new_page(pw, ph) rect(0, 0, pw, ph) fill(0.5) for i in range(grid_lines): rect(cell_s * i + cell_s / 2 - bar_s / 2, 0, bar_s, ph) rect(0, cell_s * i + cell_s / 2 - bar_s / 2, pw, bar_s) fill(1) for i in range(grid_lines): for j in...
class SubPackage: def keyword_in_mylibdir_subpackage_class(self): pass
class Subpackage: def keyword_in_mylibdir_subpackage_class(self): pass
n=int(input()) s=[int(i) for i in input().split()] cnt=0 for i in range(n): if i+1!=s[i]: cnt+=1 print(cnt)
n = int(input()) s = [int(i) for i in input().split()] cnt = 0 for i in range(n): if i + 1 != s[i]: cnt += 1 print(cnt)
#!/usr/bin/python # -*- coding: utf-8 -*- # Helper script to determine voltage levels based on the resistor values in the windvane # and the used resistor for the voltage divider on the boad. resistances = [33000, 6570, 8200, 891, 1000, 688, 2200, 1410, 3900, 3140, 16000, 14120, 120000, 42120, 64900, 21880] def volt...
resistances = [33000, 6570, 8200, 891, 1000, 688, 2200, 1410, 3900, 3140, 16000, 14120, 120000, 42120, 64900, 21880] def voltage_divider(r1, r2, vin): vout = vin * r1 / (r1 + r2) return round(vout, 3) for x in range(len(resistances)): print(resistances[x], voltage_divider(4700, resistances[x], 3.3))
# Project Euler #4: Largest palindrome product def palindrome(n): p = 0 while n > 0: r = n % 10 n = n // 10 p = p * 10 + r return p def find_largest(): max = 850000 # make a guess to save time m = 999 while m >= 100: n = m while n >= 100: pri...
def palindrome(n): p = 0 while n > 0: r = n % 10 n = n // 10 p = p * 10 + r return p def find_largest(): max = 850000 m = 999 while m >= 100: n = m while n >= 100: print(m) print(n) p = m * n if p < max: ...
# -*- coding: utf-8 -*- # @Author: Cody Kochmann # @Date: 2018-03-10 09:10:41 # @Last Modified by: Cody Kochmann # @Last Modified time: 2018-03-10 09:14:03 def reverse(pipe): ''' this has the same funcitonality as builtins.reversed(), except this doesnt complain about non-reversable things. If you didn...
def reverse(pipe): """ this has the same funcitonality as builtins.reversed(), except this doesnt complain about non-reversable things. If you didnt know already, a generator needs to fully run in order to be reversed. """ for i in reversed(list(pipe)): yield i if __name__ == '__main...
i = 1 def index(): return 'hello' b =10
i = 1 def index(): return 'hello' b = 10
# 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 invertTree(self, root: TreeNode) -> TreeNode: def invert(node): if node.left: ...
class Solution: def invert_tree(self, root: TreeNode) -> TreeNode: def invert(node): if node.left: invert(node.left) if node.right: invert(node.right) temp = node.left node.left = node.right node.right = temp ...
def stones(n, a, b): guesses = [] for i in range(n): if a < b: small, large = a, b else: small, large = b, a add = (n-1-i)*small + i*large if add not in guesses: guesses.append(add) return guesses
def stones(n, a, b): guesses = [] for i in range(n): if a < b: (small, large) = (a, b) else: (small, large) = (b, a) add = (n - 1 - i) * small + i * large if add not in guesses: guesses.append(add) return guesses
#!/usr/bin/env python3 def w_len(e): return len(e) words = ['forest', 'wood', 'tool', 'sky', 'poor', 'cloud', 'rock', 'if'] words.sort(reverse=True, key=w_len) print(words)
def w_len(e): return len(e) words = ['forest', 'wood', 'tool', 'sky', 'poor', 'cloud', 'rock', 'if'] words.sort(reverse=True, key=w_len) print(words)
def string_numbers_till_n(n): string_var = "0" for i in range(n): string_var = string_var + " " + str(i+1) return string_var print(string_numbers_till_n(5))
def string_numbers_till_n(n): string_var = '0' for i in range(n): string_var = string_var + ' ' + str(i + 1) return string_var print(string_numbers_till_n(5))
# # PySNMP MIB module EQUIPMENT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EQUIPMENT-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:51:34 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, constraints_intersection, value_range_constraint, value_size_constraint, constraints_union) ...
class _stream_iter: def __init__(self, s): self.stream = s self.i = 0 def next(self): try: val = self.stream[self.i] except IndexError: raise StopIteration self.i += 1 return val class stream(list): def __init__(self, iterator): list.__ini...
class _Stream_Iter: def __init__(self, s): self.stream = s self.i = 0 def next(self): try: val = self.stream[self.i] except IndexError: raise StopIteration self.i += 1 return val class Stream(list): def __init__(self, iterator): ...
def sale(securities, M, K): sorted_sec = sorted(securities, key=lambda x: x[0] * x[1], reverse=True) res = 0 for i in range(M): if K > 0: x, _ = sorted_sec[i] y = 1 else: x, y = sorted_sec[i] K -= 1 res += x * y print(res) # N, M...
def sale(securities, M, K): sorted_sec = sorted(securities, key=lambda x: x[0] * x[1], reverse=True) res = 0 for i in range(M): if K > 0: (x, _) = sorted_sec[i] y = 1 else: (x, y) = sorted_sec[i] k -= 1 res += x * y print(res) def test...
a = input() if a.isupper(): print(a.lower()) elif a[0].islower() and a[1:].isupper(): print(a[0].upper() + a[1:].lower()) elif len(a) == 1: print(a.upper()) else: print(a)
a = input() if a.isupper(): print(a.lower()) elif a[0].islower() and a[1:].isupper(): print(a[0].upper() + a[1:].lower()) elif len(a) == 1: print(a.upper()) else: print(a)
##https://www.hackerrank.com/challenges/max-array-sum/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dynamic-programming # Complete the maxSubsetSum function below. def maxSubsetSum(arr): incl = 0 excl = 0 for i in arr: # Current max excl...
def max_subset_sum(arr): incl = 0 excl = 0 for i in arr: new_excl = excl if excl > incl else incl incl = excl + i excl = new_excl return excl if excl > incl else incl
# OpenWeatherMap API Key weather_api_key = "6956968996d9e0c5c5a9bac119faa2e7" # Google API Key g_key = "AIzaSyDvdrUOBRkNKwWnuOOQR6wEJER3I25tAUA"
weather_api_key = '6956968996d9e0c5c5a9bac119faa2e7' g_key = 'AIzaSyDvdrUOBRkNKwWnuOOQR6wEJER3I25tAUA'