content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def extract_coupon(description): coupon = '' for s in range(len(description)): if description[s].isnumeric() or description[s] == '.': coupon = coupon + description[s] #print(c) if description[s] == '%': break try: float(coupon) except: ...
def extract_coupon(description): coupon = '' for s in range(len(description)): if description[s].isnumeric() or description[s] == '.': coupon = coupon + description[s] if description[s] == '%': break try: float(coupon) except: coupon = coupon[1:] ...
key = [int(num) for num in input().split()] data = input() length = len(key) results_dict = {} while not data == 'find': message = "" counter = 0 for el in data: if counter == length: counter = 0 asc = ord(el) asc -= key[counter] ord_asc = chr(asc) messag...
key = [int(num) for num in input().split()] data = input() length = len(key) results_dict = {} while not data == 'find': message = '' counter = 0 for el in data: if counter == length: counter = 0 asc = ord(el) asc -= key[counter] ord_asc = chr(asc) message...
# use the with key word to open file ass mb_object with open("mbox-short.txt", "r") as mb_object: # Iterate over each line and remove leading spaces; # print contents after converting them to uppercase for line in mb_object: line = line.strip() print(line.upper())
with open('mbox-short.txt', 'r') as mb_object: for line in mb_object: line = line.strip() print(line.upper())
################ # First class functions allow us to treat functions as any other variables or objects # Closures are functions that are local inner functions within outer functions that remember the arguments passed to the outer functions ################# def square(x): return x*x def my_map_function(func , arg_l...
def square(x): return x * x def my_map_function(func, arg_list): result = [] for item in arg_list: result.append(func(item)) return result int_array = [1, 2, 3, 4, 5] f = my_map_function(square, int_array) def logger(msg): def log_message(): print('Log:', msg) return log_messa...
class AbstractPlayer: def __init__(self): raise NotImplementedError() def explain(self, word, n_words): raise NotImplementedError() def guess(self, words, n_words): raise NotImplementedError() class LocalDummyPlayer(AbstractPlayer): def __init__(self): pass def e...
class Abstractplayer: def __init__(self): raise not_implemented_error() def explain(self, word, n_words): raise not_implemented_error() def guess(self, words, n_words): raise not_implemented_error() class Localdummyplayer(AbstractPlayer): def __init__(self): pass ...
# Acesso as elementos da tupla numeros = 1,2,3,5,7,11 print(numeros[0]) print(numeros[1]) print(numeros[2]) print(numeros[3]) print(numeros[4]) print(numeros[5])
numeros = (1, 2, 3, 5, 7, 11) print(numeros[0]) print(numeros[1]) print(numeros[2]) print(numeros[3]) print(numeros[4]) print(numeros[5])
__title__ = 'contactTree-api' __package_name = 'contactTree-api' __version__ = '0.1.0' __description__ = '' __author__ = 'Dionisis Pettas' __email__ = '' __github__ = 'https://github.com/deepettas/contact-tree' __licence__ = 'MIT'
__title__ = 'contactTree-api' __package_name = 'contactTree-api' __version__ = '0.1.0' __description__ = '' __author__ = 'Dionisis Pettas' __email__ = '' __github__ = 'https://github.com/deepettas/contact-tree' __licence__ = 'MIT'
def add_native_methods(clazz): def nOpen__int__(a0, a1): raise NotImplementedError() def nClose__long__(a0, a1): raise NotImplementedError() def nSendShortMessage__long__int__long__(a0, a1, a2, a3): raise NotImplementedError() def nSendLongMessage__long__byte____int__long__(a0...
def add_native_methods(clazz): def n_open__int__(a0, a1): raise not_implemented_error() def n_close__long__(a0, a1): raise not_implemented_error() def n_send_short_message__long__int__long__(a0, a1, a2, a3): raise not_implemented_error() def n_send_long_message__long__byte___...
i = 4 # variation on testWhile.py while (i < 9): i = i+2 print(i)
i = 4 while i < 9: i = i + 2 print(i)
class RelayOutput: def enable_relay(self, name: str): pass def reset(self): pass
class Relayoutput: def enable_relay(self, name: str): pass def reset(self): pass
''' Create a tuple with some words. Show for each word its vowels. ''' vowels = ('a', 'e', 'i', 'o', 'u') words = ( 'Learn', 'Programming', 'Language', 'Python', 'Course', 'Free', 'Study', 'Practice', 'Work', 'Market', 'Programmer', 'Future' ) for word in words: print(f'\nThe word \033[34m{word}\033[...
""" Create a tuple with some words. Show for each word its vowels. """ vowels = ('a', 'e', 'i', 'o', 'u') words = ('Learn', 'Programming', 'Language', 'Python', 'Course', 'Free', 'Study', 'Practice', 'Work', 'Market', 'Programmer', 'Future') for word in words: print(f'\nThe word \x1b[34m{word}\x1b[m contains', ...
f = open('surf.txt') maior = 0 for linha in f: nome, pontos = linha.split() if float(pontos) > maior: maior = float(pontos) f.close() print (maior)
f = open('surf.txt') maior = 0 for linha in f: (nome, pontos) = linha.split() if float(pontos) > maior: maior = float(pontos) f.close() print(maior)
'''https://leetcode.com/problems/palindrome-linked-list/''' # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # Solution 1 # Time Complexity - O(n) # Space Complexity - O(n) class Solution: def isPalindrome(self, head: ListNode) -...
"""https://leetcode.com/problems/palindrome-linked-list/""" class Solution: def is_palindrome(self, head: ListNode) -> bool: s = [] while head: s += [head.val] head = head.next return s == s[::-1] class Solution: def is_palindrome(self, head: ListNode) -> bool...
def calculate(**kwargs): operation_lookup = { 'add': kwargs.get('first', 0) + kwargs.get('second', 0), 'subtract': kwargs.get('first', 0) - kwargs.get('second', 0), 'divide': kwargs.get('first', 0) / kwargs.get('second', 1), 'multiply': kwargs.get('first', 0) * kwargs.get('second', ...
def calculate(**kwargs): operation_lookup = {'add': kwargs.get('first', 0) + kwargs.get('second', 0), 'subtract': kwargs.get('first', 0) - kwargs.get('second', 0), 'divide': kwargs.get('first', 0) / kwargs.get('second', 1), 'multiply': kwargs.get('first', 0) * kwargs.get('second', 0)} is_float = kwargs.get('mak...
# --------------------------------------------------------------------------------------- # # Title: Permutations # # Link: https://leetcode.com/problems/permutations/ # # Difficulty: Medium # # Language: Python # # -----------------------------------------------------------------------------------...
class Permutations: def permute(self, nums): return self.phelper(nums, [], []) def phelper(self, nums, x, y): for i in nums: if i not in x: x.append(i) if len(x) == len(nums): y.append(x.copy()) else: ...
''' modifier: 01 eqtime: 25 ''' def main(): info('Jan Air Script x1') gosub('jan:WaitForMiniboneAccess') gosub('jan:PrepareForAirShot') gosub('jan:EvacPipette2') gosub('common:FillPipette2') gosub('jan:PrepareForAirShotExpansion') gosub('common:ExpandPipette2')
""" modifier: 01 eqtime: 25 """ def main(): info('Jan Air Script x1') gosub('jan:WaitForMiniboneAccess') gosub('jan:PrepareForAirShot') gosub('jan:EvacPipette2') gosub('common:FillPipette2') gosub('jan:PrepareForAirShotExpansion') gosub('common:ExpandPipette2')
def SaveOrder(orderDict): file = open("orderLog.txt", 'w') total = 0 for item, price in orderDict.items(): file.write(item+'-->'+str(price)+'\n') total += price file.write('Total = '+str(total)) file.close() def main(): order = { 'Pizza':100, 'Snak...
def save_order(orderDict): file = open('orderLog.txt', 'w') total = 0 for (item, price) in orderDict.items(): file.write(item + '-->' + str(price) + '\n') total += price file.write('Total = ' + str(total)) file.close() def main(): order = {'Pizza': 100, 'Snaks': 200, 'Pasta': 50...
# Generator A starts with 783 # Generator B starts with 325 REAL_START=[783, 325] SAMPLE_START=[65, 8921] FACTORS=[16807, 48271] DIVISOR=2147483647 # 0b1111111111111111111111111111111 2^31 def next_a_value(val, factor): while True: val = (val * factor) % DIVISOR if val & 3 == 0: return ...
real_start = [783, 325] sample_start = [65, 8921] factors = [16807, 48271] divisor = 2147483647 def next_a_value(val, factor): while True: val = val * factor % DIVISOR if val & 3 == 0: return val def next_b_value(val, factor): while True: val = val * factor % DIVISOR ...
# -*- coding: utf-8 -*- class ArgumentTypeError(TypeError): pass class ArgumentValueError(ValueError): pass
class Argumenttypeerror(TypeError): pass class Argumentvalueerror(ValueError): pass
# VALIDAR SE A CIDADE DIGITADA INICIA COM O NOME SANTO: cidade = str(input('Digite a cidade em que nasceu... ')).strip() print(cidade[:5].upper() == 'SANTO')
cidade = str(input('Digite a cidade em que nasceu... ')).strip() print(cidade[:5].upper() == 'SANTO')
ls = list(map(int, input().split())) count = 0 for i in ls: if ls[i] == 1: count += 1 print(count)
ls = list(map(int, input().split())) count = 0 for i in ls: if ls[i] == 1: count += 1 print(count)
def abc(a,b,c): for i in a: b(a) if c(): if b(a) > 100: b(a) elif 100 > 0: b(a) else: b(a) else: b(100) return 100 def ex(): try: fh = open("testfile", "w") fh.write("a") except IOError: print("b...
def abc(a, b, c): for i in a: b(a) if c(): if b(a) > 100: b(a) elif 100 > 0: b(a) else: b(a) else: b(100) return 100 def ex(): try: fh = open('testfile', 'w') fh.write('a') except IOError: print(...
# 4. Write a Python program to check a list is empty or not. Take few lists with one of them empty. fruits = ['apple', 'cherry', 'pear', 'lemon', 'banana'] fruits1 = [] fruits2 = ['mango', 'strawberry', 'peach'] # print (fruits[3]) # print (fruits[-2]) # print (fruits[1]) # # # print (fruits[0]) # print (fruits) # # f...
fruits = ['apple', 'cherry', 'pear', 'lemon', 'banana'] fruits1 = [] fruits2 = ['mango', 'strawberry', 'peach'] fruits.append('apple') fruits.append('banana') fruits.append('pear') fruits.append('cherry') print(fruits) fruits.append('apple') fruits.append('banana') fruits.append('pear') fruits.append('cherry') print(fr...
include("common.py") def cyanamidationGen(): r = RuleGen("Cyanamidation") r.left.extend([ '# H2NCN', 'edge [ source 0 target 1 label "#" ]', '# The other', 'edge [ source 105 target 150 label "-" ]', ]) r.context.extend([ '# H2NCN', 'node [ id 0 label "N" ]', 'node [ id 1 label "C" ]', 'node [ id 2...
include('common.py') def cyanamidation_gen(): r = rule_gen('Cyanamidation') r.left.extend(['# H2NCN', 'edge [ source 0 target 1 label "#" ]', '# The other', 'edge [ source 105 target 150 label "-" ]']) r.context.extend(['# H2NCN', 'node [ id 0 label "N" ]', 'node [ id 1 label "C" ]', 'node [ id 2 label "N"...
number = int(input()) divider = number // 2 numbers = '' while divider != 1: if 0 == number % divider: numbers += " " + str(divider) divider -= 1 if 0 == len(numbers): print('Prime Number') else: print(numbers[1:])
number = int(input()) divider = number // 2 numbers = '' while divider != 1: if 0 == number % divider: numbers += ' ' + str(divider) divider -= 1 if 0 == len(numbers): print('Prime Number') else: print(numbers[1:])
class Solution: def XXX(self, nums: List[int]) -> List[List[int]]: return reduce(lambda x, y: x + [i + [y] for i in x], nums, [[]])
class Solution: def xxx(self, nums: List[int]) -> List[List[int]]: return reduce(lambda x, y: x + [i + [y] for i in x], nums, [[]])
HEARTBEAT = "0" TESTREQUEST = "1" RESENDREQUEST = "2" REJECT = "3" SEQUENCERESET = "4" LOGOUT = "5" IOI = "6" ADVERTISEMENT = "7" EXECUTIONREPORT = "8" ORDERCANCELREJECT = "9" QUOTESTATUSREQUEST = "a" LOGON = "A" DERIVATIVESECURITYLIST = "AA" NEWORDERMULTILEG = "AB" MULTILEGORDERCANCELREPLACE = "AC" TRADECAPTUREREPORTR...
heartbeat = '0' testrequest = '1' resendrequest = '2' reject = '3' sequencereset = '4' logout = '5' ioi = '6' advertisement = '7' executionreport = '8' ordercancelreject = '9' quotestatusrequest = 'a' logon = 'A' derivativesecuritylist = 'AA' newordermultileg = 'AB' multilegordercancelreplace = 'AC' tradecapturereportr...
# Given two integers, swap them with no additional variable # 1. With temporal variable t def swap(a,b): t = b a = b b = t return a, b # 2. With no variable def swap(a,b): a = b - a b = b - a # b = b -(b-a) = a a = b + a # b = a + b - a = b...Swapped return a, b ...
def swap(a, b): t = b a = b b = t return (a, b) def swap(a, b): a = b - a b = b - a a = b + a return (a, b) def swap(a, b): a = a ^ b b = a ^ b a = b ^ a return (a, b)
# coding: utf-8 def test_default_value(printer): assert printer._inverse is False def test_changing_no_value(printer): printer.inverse() assert printer._inverse is False def test_changing_state_on(printer): printer.inverse(True) assert printer._inverse is True def test_changing_state_off(pri...
def test_default_value(printer): assert printer._inverse is False def test_changing_no_value(printer): printer.inverse() assert printer._inverse is False def test_changing_state_on(printer): printer.inverse(True) assert printer._inverse is True def test_changing_state_off(printer): printer.in...
# program to merge two linked list class Node: def __init__(self, data, next): self.data = data self.next = next def merge(L1,L2): L3 = Node(None, None) prev = L3 while L1 != None and L2 != None: if L1.data <= L2.data: prev.next = L2.data ...
class Node: def __init__(self, data, next): self.data = data self.next = next def merge(L1, L2): l3 = node(None, None) prev = L3 while L1 != None and L2 != None: if L1.data <= L2.data: prev.next = L2.data l1 = L1.next else: prev.data ...
local_webserver = '/var/www/html' ssh = dict( host = '', username = '', password = '', remote_path = '' )
local_webserver = '/var/www/html' ssh = dict(host='', username='', password='', remote_path='')
class FibIterator(object): def __init__(self, n): self.n = n self.current = 0 self.num1 = 0 self.num2 = 1 def __next__(self): if self.current < self.n: item = self.num1 self.num1, self.num2 = self.num2, self.num1+self.num2 self.current...
class Fibiterator(object): def __init__(self, n): self.n = n self.current = 0 self.num1 = 0 self.num2 = 1 def __next__(self): if self.current < self.n: item = self.num1 (self.num1, self.num2) = (self.num2, self.num1 + self.num2) self....
cpgf._import(None, "builtin.debug"); cpgf._import(None, "builtin.core"); class SAppContext: device = None, counter = 0, listbox = None Context = SAppContext(); GUI_ID_QUIT_BUTTON = 101; GUI_ID_NEW_WINDOW_BUTTON = 102; GUI_ID_FILE_OPEN_BUTTON = 103; GUI_ID_TRANSPARENCY_SCROLL_BAR = 104; def makeM...
cpgf._import(None, 'builtin.debug') cpgf._import(None, 'builtin.core') class Sappcontext: device = (None,) counter = (0,) listbox = None context = s_app_context() gui_id_quit_button = 101 gui_id_new_window_button = 102 gui_id_file_open_button = 103 gui_id_transparency_scroll_bar = 104 def make_my_event_re...
class SoftplusParams: __slots__ = ["beta"] def __init__(self, beta=100): self.beta = beta class GeometricInitParams: __slots__ = ["bias"] def __init__(self, bias=0.6): self.bias = bias class IDRHyperParams: def __init__(self, softplus=None, geometric_init=None): self.so...
class Softplusparams: __slots__ = ['beta'] def __init__(self, beta=100): self.beta = beta class Geometricinitparams: __slots__ = ['bias'] def __init__(self, bias=0.6): self.bias = bias class Idrhyperparams: def __init__(self, softplus=None, geometric_init=None): self.sof...
# Coin Change 8 class Solution: def change(self, amount, coins): # Classic DP problem? dp = [0] * (amount + 1) dp[0] = 1 for coin in coins: for am in range(1, amount + 1): if am >= coin: dp[am] += dp[am - coin] return dp[amoun...
class Solution: def change(self, amount, coins): dp = [0] * (amount + 1) dp[0] = 1 for coin in coins: for am in range(1, amount + 1): if am >= coin: dp[am] += dp[am - coin] return dp[amount] if __name__ == '__main__': sol = solutio...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def insertIntoMaxTree(self, root: TreeNode, val: int) -> TreeNode: if root is None or root.val < val: node = TreeNode(val) ...
class Treenode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def insert_into_max_tree(self, root: TreeNode, val: int) -> TreeNode: if root is None or root.val < val: node = tree_node(val) node.left = root ...
#------------------------------------------------------------- # Name: Michael Dinh # Date: 10/10/2018 # Reference: Pg. 169, Problem #6 # Title: Book Club Points # Inputs: User inputs number of books bought from a store # Processes: Determines point value based on number of books bought # Outputs: Number of points user...
def get_books(): books = int(input("Welcome to the Serendipity Booksellers Book Club Awards Points Calculator! Please enter the number of books you've purchased today: ")) return books def det_points(books): if books < 1: print("You've earned 0 points; buy at least one book to qualify!") elif b...
def arraypermute(collection, key): return [ str(i) + str(j) for i in collection for j in key ] class FilterModule(object): def filters(self): return { 'arraypermute': arraypermute }
def arraypermute(collection, key): return [str(i) + str(j) for i in collection for j in key] class Filtermodule(object): def filters(self): return {'arraypermute': arraypermute}
# # PySNMP MIB module SNIA-SML-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SNIA-SML-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:00:04 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019,...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, value_size_constraint, constraints_intersection, single_value_constraint, value_range_constraint) ...
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: dic = {} for i in range(len(nums)): if dic.get(target - nums[i]) is not None: return [dic[target - nums[i]], i] dic[nums[i]] = i
class Solution: def two_sum(self, nums: List[int], target: int) -> List[int]: dic = {} for i in range(len(nums)): if dic.get(target - nums[i]) is not None: return [dic[target - nums[i]], i] dic[nums[i]] = i
#!/usr/bin/env python3 ARP = [ {'mac_addr': '0062.ec29.70fe', 'ip_addr': '10.220.88.1', 'interface': 'gi0/0/0'}, {'mac_addr': 'c89c.1dea.0eb6', 'ip_addr': '10.220.88.20', 'interface': 'gi0/0/0'}, {'mac_addr': 'a093.5141.b780', 'ip_addr': '10.220.88.22', 'interface': 'gi0/0/0'}, {'mac_addr': '0001.00ff.0001', 'ip_addr...
arp = [{'mac_addr': '0062.ec29.70fe', 'ip_addr': '10.220.88.1', 'interface': 'gi0/0/0'}, {'mac_addr': 'c89c.1dea.0eb6', 'ip_addr': '10.220.88.20', 'interface': 'gi0/0/0'}, {'mac_addr': 'a093.5141.b780', 'ip_addr': '10.220.88.22', 'interface': 'gi0/0/0'}, {'mac_addr': '0001.00ff.0001', 'ip_addr': '10.220.88.37', 'interf...
#!/usr/bin/env python # encoding: utf-8 def run(whatweb, pluginname): whatweb.recog_from_file(pluginname, "Script/FocusSlide.js", "southidc") whatweb.recog_from_content(pluginname, "southidc") whatweb.recog_from_file(pluginname,"Script/Html.js", "southidc")
def run(whatweb, pluginname): whatweb.recog_from_file(pluginname, 'Script/FocusSlide.js', 'southidc') whatweb.recog_from_content(pluginname, 'southidc') whatweb.recog_from_file(pluginname, 'Script/Html.js', 'southidc')
''' width search Explore all of the neighbors nodes at the present depth ''' three_d_array = [[[i for k in range(4)] for j in range(4)] for i in range(4)] sum = three_d_array[1][2][3] + three_d_array[2][3][1] + three_d_array[0][0][0] print(sum)
""" width search Explore all of the neighbors nodes at the present depth """ three_d_array = [[[i for k in range(4)] for j in range(4)] for i in range(4)] sum = three_d_array[1][2][3] + three_d_array[2][3][1] + three_d_array[0][0][0] print(sum)
def f(x): print('a') y = x print('b') while y > 0: print('c') y -= 1 print('d') yield y print('e') print('f') return None for val in f(3): print(val) #gen = f(3) #print(gen) #print(gen.__next__()) #print(gen.__next__()) #print(gen.__next__()) #print(...
def f(x): print('a') y = x print('b') while y > 0: print('c') y -= 1 print('d') yield y print('e') print('f') return None for val in f(3): print(val) print(repr(f(0))[0:17]) print('PASS')
file = open("test/TopCompiler/"+input("filename: "), mode= "w") sizeOfFunc = input("size of func: ") lines = input("lines of code: ") out = [] for i in range(int(int(lines) / int(sizeOfFunc)+2)): out.append("def func"+str(i)+"() =\n") for c in range(int(sizeOfFunc)): out.append(' println "hello worl...
file = open('test/TopCompiler/' + input('filename: '), mode='w') size_of_func = input('size of func: ') lines = input('lines of code: ') out = [] for i in range(int(int(lines) / int(sizeOfFunc) + 2)): out.append('def func' + str(i) + '() =\n') for c in range(int(sizeOfFunc)): out.append(' println "he...
#! /usr/bin/env python3 ''' Disjoint Set Class that provides basic functionality. Implemented according the functionality provided here: https://en.wikipedia.org/wiki/Disjoint-set_data_structure @author: Paul Miller (github.com/138paulmiller) ''' class DisjointSet: ''' Disjoint Set : Utility class that helps implem...
""" Disjoint Set Class that provides basic functionality. Implemented according the functionality provided here: https://en.wikipedia.org/wiki/Disjoint-set_data_structure @author: Paul Miller (github.com/138paulmiller) """ class Disjointset: """ Disjoint Set : Utility class that helps implement Kruskal MST algo...
#!/usr/bin/python # https://code.google.com/codejam/contest/2933486/dashboard # application of insertion sort N = int(input().strip()) for i in range(N): M = int(input().strip()) deck = [] count = 0 for j in range(M): deck.append(input().strip()) p = 0 for k in range(len(deck)): if k > 0 and deck[k]...
n = int(input().strip()) for i in range(N): m = int(input().strip()) deck = [] count = 0 for j in range(M): deck.append(input().strip()) p = 0 for k in range(len(deck)): if k > 0 and deck[k] < deck[p]: count += 1 else: p = k print(f'Case #{i + ...
def sum(arr: list, start: int, end: int)->int: if start > end: return 0 elif start == end: return arr[start] else: midpoint: int = int(start + (end - start) / 2) return sum(arr, start, midpoint) + sum(arr, midpoint + 1, end) numbers1: list = [] numbers2: list =...
def sum(arr: list, start: int, end: int) -> int: if start > end: return 0 elif start == end: return arr[start] else: midpoint: int = int(start + (end - start) / 2) return sum(arr, start, midpoint) + sum(arr, midpoint + 1, end) numbers1: list = [] numbers2: list = [1] numbers3...
class Car: def __init__(self, pMake, pModel, pColor, pPrice): self.make = pMake self.model = pModel self.color = pColor self.price = pPrice def __str__(self): return 'Make = %s, Model = %s, Color = %s, Price = %s' %(self.make, self.model, self.color, self.price) ...
class Car: def __init__(self, pMake, pModel, pColor, pPrice): self.make = pMake self.model = pModel self.color = pColor self.price = pPrice def __str__(self): return 'Make = %s, Model = %s, Color = %s, Price = %s' % (self.make, self.model, self.color, self.price) d...
class SimpleTreeNode: def __init__(self, val, left=None, right=None) -> None: self.val = val self.left = left self.right = right class AdvanceTreeNode: def __init__(self, val, parent=None, left=None, right=None) -> None: self.val = val self.parent: AdvanceTreeNode = par...
class Simpletreenode: def __init__(self, val, left=None, right=None) -> None: self.val = val self.left = left self.right = right class Advancetreenode: def __init__(self, val, parent=None, left=None, right=None) -> None: self.val = val self.parent: AdvanceTreeNode = pa...
# # PySNMP MIB module CISCO-OPTICAL-MONITOR-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-OPTICAL-MONITOR-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:08:51 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3....
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_size_constraint, constraints_union, value_range_constraint, constraints_intersection) ...
name = 'Bob' if name == 'Alice': print('Hi Alice') print('Done')
name = 'Bob' if name == 'Alice': print('Hi Alice') print('Done')
def tup(name, len): ret = '(' for i in range(len): ret += f'{name}{i}, ' return ret + ')' for i in range(10): print( f'impl_unzip!({tup("T",i)}, {tup("A",i)}, {tup("s",i)}, {tup("t",i)});')
def tup(name, len): ret = '(' for i in range(len): ret += f'{name}{i}, ' return ret + ')' for i in range(10): print(f"impl_unzip!({tup('T', i)}, {tup('A', i)}, {tup('s', i)}, {tup('t', i)});")
class SubrectangleQueries: def __init__(self, rectangle: List[List[int]]): self.rec = rectangle self.newRec = [] def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None: self.newRec.append((row1, col1, row2, col2, newValue)) def get...
class Subrectanglequeries: def __init__(self, rectangle: List[List[int]]): self.rec = rectangle self.newRec = [] def update_subrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None: self.newRec.append((row1, col1, row2, col2, newValue)) def get_value(s...
# model model = Model() i0 = Input("op_shape", "TENSOR_INT32", "{4}") weights = Parameter("ker", "TENSOR_FLOAT32", "{1, 3, 3, 1}", [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]) i1 = Input("in", "TENSOR_FLOAT32", "{1, 4, 4, 1}" ) pad = Int32Scalar("pad_same", 1) s_x = Int32Scalar("stride_x", 1) s_y = Int32Scalar("strid...
model = model() i0 = input('op_shape', 'TENSOR_INT32', '{4}') weights = parameter('ker', 'TENSOR_FLOAT32', '{1, 3, 3, 1}', [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]) i1 = input('in', 'TENSOR_FLOAT32', '{1, 4, 4, 1}') pad = int32_scalar('pad_same', 1) s_x = int32_scalar('stride_x', 1) s_y = int32_scalar('stride_y', ...
{ "targets": [ { "target_name": "cityhash", "include_dirs": ["cityhash/"], "sources": [ "binding.cc", "cityhash/city.cc" ] } ] }
{'targets': [{'target_name': 'cityhash', 'include_dirs': ['cityhash/'], 'sources': ['binding.cc', 'cityhash/city.cc']}]}
# def positive_or_negative(value): # if value > 0: # return "Positive!" # elif value < 0: # return "Negative!" # else: # return "It's zero!" # number = int(input("Wprowadz liczbe: ")) # print(positive_or_negative(number)) def calculator(operation, a, b): if operation == "add": ...
def calculator(operation, a, b): if operation == 'add': return a + b elif operation == 'subtract': return a - b elif operation == 'multiple': return a * b elif operation == 'divide': return a / b else: print('There is no such an operation!') operacja = str(inp...
pkgname = "eventlog" pkgver = "0.2.13" pkgrel = 0 _commit = "a5c19163ba131f79452c6dfe4e31c2b4ce4be741" build_style = "gnu_configure" hostmakedepends = ["pkgconf", "automake", "libtool"] pkgdesc = "API to format and send structured log messages" maintainer = "q66 <q66@chimera-linux.org>" license = "BSD-3-Clause" url = "...
pkgname = 'eventlog' pkgver = '0.2.13' pkgrel = 0 _commit = 'a5c19163ba131f79452c6dfe4e31c2b4ce4be741' build_style = 'gnu_configure' hostmakedepends = ['pkgconf', 'automake', 'libtool'] pkgdesc = 'API to format and send structured log messages' maintainer = 'q66 <q66@chimera-linux.org>' license = 'BSD-3-Clause' url = '...
# # PySNMP MIB module CISCO-COMPRESSION-SERVICE-ADAPTER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-COMPRESSION-SERVICE-ADAPTER-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:36:21 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 #...
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, value_size_constraint, value_range_constraint, single_value_constraint, constraints_intersection) ...
user_input = '5,4,25,18,22,9' user_numbers = user_input.split(',') user_numbers_as_int = [] for number in user_numbers: user_numbers_as_int.append(int(number)) print(user_numbers_as_int) print([number for number in user_numbers]) print([number*2 for number in user_numbers]) print([int(number) for number in use...
user_input = '5,4,25,18,22,9' user_numbers = user_input.split(',') user_numbers_as_int = [] for number in user_numbers: user_numbers_as_int.append(int(number)) print(user_numbers_as_int) print([number for number in user_numbers]) print([number * 2 for number in user_numbers]) print([int(number) for number in user_n...
line = "Please have a nice day" # This takes a parameter, what prefix we're looking for. line_new = line.startswith('Please') print(line_new) #Does it start with a lowercase p? # And then we get back a False because, # no, it doesn't start with a lowercase p line_new = line.startswith('p') print(line_new)
line = 'Please have a nice day' line_new = line.startswith('Please') print(line_new) line_new = line.startswith('p') print(line_new)
a=[1,2] for i,s in enumerate(a): print(i,"index contains",s)
a = [1, 2] for (i, s) in enumerate(a): print(i, 'index contains', s)
def gen_help(bot_name): return''' Hello! I am a telegram bot that generates duckduckgo links from tg directly. I am an inline bot, you can access it via @{bot_name}. If you have any questions feel free to leave issue at http://github.com/cleac/tgsearchbot '''.format(bot_name=bot_name)
def gen_help(bot_name): return '\nHello!\n\nI am a telegram bot that generates duckduckgo links from tg directly.\nI am an inline bot, you can access it via @{bot_name}.\n\nIf you have any questions feel free to leave issue at http://github.com/cleac/tgsearchbot\n '.format(bot_name=bot_name)
#class Solution: # def checkPowersOfThree(self, n: int) -> bool: #def checkPowersOfThree(n): # def divisible_by_3(k): # return k % 3 == 0 # #if 1 <= n <= 2: # if n == 2: # return False # if divisible_by_3(n): # return checkPowersOfThree(n//3) # else: # n = n - 1 # ...
qualified = {1, 3, 4, 9} def check_powers_of_three(n): if n in qualified: return True remainder = n % 3 if remainder == 2: return False else: reduced = (n - remainder) // 3 if check_powers_of_three(reduced): qualified.add(reduced) return True ...
n = int(input('Enter A Number:')) count = 1 for i in range(count, 11, 1): print (f'{n} * {count} = {n*count}') count +=1
n = int(input('Enter A Number:')) count = 1 for i in range(count, 11, 1): print(f'{n} * {count} = {n * count}') count += 1
# Sum of the diagonals of a spiral square diagonal # OPTIMAL (<0.1s) # # APPROACH: # Generate the numbers in the spiral with a simple algorithm until # the desdired side is obtained, SQUARE_SIDE = 1001 DUMMY_SQUARE_SIDE = 5 DUMMY_RESULT = 101 def generate_numbers(limit): current = 1 internal_square = 1 steps = ...
square_side = 1001 dummy_square_side = 5 dummy_result = 101 def generate_numbers(limit): current = 1 internal_square = 1 steps = 0 while internal_square <= limit: yield current if current == internal_square ** 2: internal_square += 2 steps += 2 current +=...
PI = 3.14 SALES_TAX = 6 if __name__ == '__main__': print('Constant file directly executed') else: print('Constant file is imported')
pi = 3.14 sales_tax = 6 if __name__ == '__main__': print('Constant file directly executed') else: print('Constant file is imported')
{ 'targets': [ { 'target_name': 'electron-dragdrop-win', 'include_dirs': [ '<!(node -e "require(\'nan\')")', ], 'defines': [ 'UNICODE', '_UNICODE'], 'sources': [ ], 'conditions': [ ['OS=="win"', { 'sources': [ "src/addon.cpp", ...
{'targets': [{'target_name': 'electron-dragdrop-win', 'include_dirs': ['<!(node -e "require(\'nan\')")'], 'defines': ['UNICODE', '_UNICODE'], 'sources': [], 'conditions': [['OS=="win"', {'sources': ['src/addon.cpp', 'src/Worker.cpp', 'src/v8utils.cpp', 'src/ole/DataObject.cpp', 'src/ole/DropSource.cpp', 'src/ole/EnumFo...
def format_reader_port_message(message, reader_port, error): return f'{message} with {reader_port}. Error: {error}' def format_reader_message(message, vendor_id, product_id, serial_number): return f'{message} with ' \ f'vendor_id={vendor_id}, ' \ f'product_id={product_id} and ' \ ...
def format_reader_port_message(message, reader_port, error): return f'{message} with {reader_port}. Error: {error}' def format_reader_message(message, vendor_id, product_id, serial_number): return f'{message} with vendor_id={vendor_id}, product_id={product_id} and serial_number={serial_number}' class Readerno...
word="boy" print(word) reverse=[] l=list(word) for i in l: reverse=[i]+reverse reverse="".join(reverse) print(reverse) l=[1,2,3,4] print(l) r=[] for i in l: r=[i]+r print(r)
word = 'boy' print(word) reverse = [] l = list(word) for i in l: reverse = [i] + reverse reverse = ''.join(reverse) print(reverse) l = [1, 2, 3, 4] print(l) r = [] for i in l: r = [i] + r print(r)
path = '08-File-Handling-Lab-Resources/File Reader/numbers.txt' file = open(path, 'r') num_sum = 0 for num in file: num_sum += int(num) print(num) # read print(num_sum) print(file.read()) # .read(n) n = number
path = '08-File-Handling-Lab-Resources/File Reader/numbers.txt' file = open(path, 'r') num_sum = 0 for num in file: num_sum += int(num) print(num) print(num_sum) print(file.read())
class BindingTypes: JSFunction = 1 JSObject = 2 class Binding(object): def __init__(self, type, src, dest): self.type = type self.src = src self.dest = dest
class Bindingtypes: js_function = 1 js_object = 2 class Binding(object): def __init__(self, type, src, dest): self.type = type self.src = src self.dest = dest
def faculty_evaluation_result(nev, rar, som, oft, voft, alw): ''' Write code to calculate faculty evaluation rating according to asssignment instructions :param nev: Never :param rar: Rarely :param som: Sometimes :param oft: Often :param voft: Very Often :param alw: Always :ret...
def faculty_evaluation_result(nev, rar, som, oft, voft, alw): """ Write code to calculate faculty evaluation rating according to asssignment instructions :param nev: Never :param rar: Rarely :param som: Sometimes :param oft: Often :param voft: Very Often :param alw: Always :return: rati...
HTTP_HOST = '' HTTP_PORT = 8080 FLASKY_MAIL_SUBJECT_PREFIX = "(Info)" FLASKY_MAIL_SENDER = 'ycs_ctbu_2010@126.com' FLASKY_ADMIN = 'ycs_ctbu_2010@126.com' SECRET_KEY = "\x02|\x86.\\\xea\xba\x89\xa3\xfc\r%s\x9e\x06\x9d\x01\x9c\x84\xa1b+uC" LOG = "/var/flasky" # WSGI Settings WSGI_LOG = 'default' # Flask-...
http_host = '' http_port = 8080 flasky_mail_subject_prefix = '(Info)' flasky_mail_sender = 'ycs_ctbu_2010@126.com' flasky_admin = 'ycs_ctbu_2010@126.com' secret_key = '\x02|\x86.\\êº\x89£ü\r%s\x9e\x06\x9d\x01\x9c\x84¡b+uC' log = '/var/flasky' wsgi_log = 'default' log_level = 'debug' log_filename = 'logs/error.log' log_...
class Action: def __init__(self, fun, id=None): self._fun = fun self._id = id def fun(self): return self._fun def id(self): return self._id
class Action: def __init__(self, fun, id=None): self._fun = fun self._id = id def fun(self): return self._fun def id(self): return self._id
class dotIFC2X3_Product_t(object): # no doc Description = None IFC2X3_OwnerHistory = None Name = None ObjectType = None
class Dotifc2X3_Product_T(object): description = None ifc2_x3__owner_history = None name = None object_type = None
''' ############################################### # ####################################### # #### ######## Simple Calculator ########## #### # ####################################### # ############################################### ## ## ###########...
""" ############################################### # ####################################### # #### ######## Simple Calculator ########## #### # ####################################### # ############################################### ## ## ###########...
def handle_error_response(resp): codes = { -1: FactomAPIError, -32008: BlockNotFound, -32009: MissingChainHead, -32010: ReceiptCreationError, -32011: RepeatedCommit, -32600: InvalidRequest, -32601: MethodNotFound, -32602: InvalidParams, -32603:...
def handle_error_response(resp): codes = {-1: FactomAPIError, -32008: BlockNotFound, -32009: MissingChainHead, -32010: ReceiptCreationError, -32011: RepeatedCommit, -32600: InvalidRequest, -32601: MethodNotFound, -32602: InvalidParams, -32603: InternalError, -32700: ParseError} error = resp.json().get('error', ...
# Encapsulate the pairs of int multiples to related string monikers class MultipleMoniker: mul = 0 mon = "" def __init__(self, multiple, moniker) -> None: self.mul = multiple self.mon = moniker # Define object to contain methods class FizzBuzz: # Define the int to start counting at ...
class Multiplemoniker: mul = 0 mon = '' def __init__(self, multiple, moniker) -> None: self.mul = multiple self.mon = moniker class Fizzbuzz: start = 1 maxi = 0 mm_pair = [multiple_moniker(3, 'Fizz'), multiple_moniker(5, 'Buzz')] array = [] def __init__(self, max_int, ...
# # 1265. Print Immutable Linked List in Reverse # # Q: https://leetcode.com/problems/print-immutable-linked-list-in-reverse/ # A: https://leetcode.com/problems/print-immutable-linked-list-in-reverse/discuss/436558/Javascript-Python3-C%2B%2B-1-Liners # class Solution: def printLinkedListInReverse(self, head: 'Immu...
class Solution: def print_linked_list_in_reverse(self, head: 'ImmutableListNode') -> None: if head: self.printLinkedListInReverse(head.getNext()) head.printValue()
class Grid: def __init__(self, grid: [[int]]): self.grid = grid self.flashes = 0 self.ticks = 0 self.height = len(grid) self.width = len(grid[0]) self.flashed_cells: [str] = [] def tick(self): self.ticks += 1 i = 0 for row in self.grid:...
class Grid: def __init__(self, grid: [[int]]): self.grid = grid self.flashes = 0 self.ticks = 0 self.height = len(grid) self.width = len(grid[0]) self.flashed_cells: [str] = [] def tick(self): self.ticks += 1 i = 0 for row in self.grid: ...
#%% text=open('new.txt', 'r+') text.write('Hello file') for i in range(0, 11): text.write(str(i)) print(text.seek(2)) #%% #file operations Read & Write text=open('sampletxt.txt', 'r') text= text.read() print(text) text=text.split(' ') print(text)
text = open('new.txt', 'r+') text.write('Hello file') for i in range(0, 11): text.write(str(i)) print(text.seek(2)) text = open('sampletxt.txt', 'r') text = text.read() print(text) text = text.split(' ') print(text)
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"load_audio": "00_core.ipynb", "AudioMono": "00_core.ipynb", "duration": "00_core.ipynb", "SpecImage": "00_core.ipynb", "ArrayAudioBase": "00_core.ipynb", "ArraySp...
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'load_audio': '00_core.ipynb', 'AudioMono': '00_core.ipynb', 'duration': '00_core.ipynb', 'SpecImage': '00_core.ipynb', 'ArrayAudioBase': '00_core.ipynb', 'ArraySpecBase': '00_core.ipynb', 'ArrayMaskBase': '00_core.ipynb', 'TensorAudio': '00_core.ip...
version = "1.0" version_maj = 1 version_min = 0
version = '1.0' version_maj = 1 version_min = 0
r = range(5) # Counts from 0 to 4 for i in r: print(i) r = range(1,6) # Counts from 1 to 5 for i in r: print(i) # Step Value r = range(1,15,3) # Counts from 1 to 15 with a gap of '3', thereby, counting till '13' only as 16 is not in the...
r = range(5) for i in r: print(i) r = range(1, 6) for i in r: print(i) r = range(1, 15, 3) for i in r: print(i)
def sum(*n): total=0 for n1 in n: total=total+n1 print("the sum=",total) sum() sum(10) sum(10,20) sum(10,20,30,40)
def sum(*n): total = 0 for n1 in n: total = total + n1 print('the sum=', total) sum() sum(10) sum(10, 20) sum(10, 20, 30, 40)
name = 'late_binding' version = "1.0" @late() def tools(): return ["util"] def commands(): env.PATH.append("{root}/bin")
name = 'late_binding' version = '1.0' @late() def tools(): return ['util'] def commands(): env.PATH.append('{root}/bin')
# functions # i.e., len() where the () designate a function # functions that are related to str course = "python programming" # here we have a kind of function called a "method" which # comes after a str and designated by a "." # in Py all everything is an object # and objects have "functions" # and "functions" have ...
course = 'python programming' print(course.upper()) print(course) print(course.capitalize()) print(course.istitle()) print(course.title()) upper_course = course.upper() print(upper_course) lower_course = upper_course.lower() print(lower_course) unstriped_course = ' The unstriped Python Course' print(unstriped_course)...
#this is to make change from dollar bills change=float(input("Enter an amount to make change for :")) print("Your change is..") print(int(change//20), "twenties") change=change % 20 print(int(change//10), "tens") change=change % 10 print(int(change//5), "fives") change=change % 5 print(int(change//1), "ones") change=ch...
change = float(input('Enter an amount to make change for :')) print('Your change is..') print(int(change // 20), 'twenties') change = change % 20 print(int(change // 10), 'tens') change = change % 10 print(int(change // 5), 'fives') change = change % 5 print(int(change // 1), 'ones') change = change % 1 print(int(chang...
def calc_fuel(mass): fuel = int(mass / 3) - 2 return fuel with open("input.txt") as infile: fuel_sum = 0 for line in infile: mass = int(line.strip()) fuel = calc_fuel(mass) fuel_sum += fuel print(fuel_sum)
def calc_fuel(mass): fuel = int(mass / 3) - 2 return fuel with open('input.txt') as infile: fuel_sum = 0 for line in infile: mass = int(line.strip()) fuel = calc_fuel(mass) fuel_sum += fuel print(fuel_sum)
def main() -> None: a, b, c = map(int, input().split()) d = [a, b, c] d.sort() print("Yes" if d[1] == b else "No") if __name__ == "__main__": main()
def main() -> None: (a, b, c) = map(int, input().split()) d = [a, b, c] d.sort() print('Yes' if d[1] == b else 'No') if __name__ == '__main__': main()
def sums(target): ans = 0 sumlist=[] count = 1 for num in range(target): sumlist.append(count) count = count + 1 ans = sum(sumlist) print(ans) #print(sumlist) target = int(input("")) sums(target)
def sums(target): ans = 0 sumlist = [] count = 1 for num in range(target): sumlist.append(count) count = count + 1 ans = sum(sumlist) print(ans) target = int(input('')) sums(target)
# AUTOGENERATED! DO NOT EDIT! File to edit: 00_core.ipynb (unless otherwise specified). __all__ = ['print_hello'] # Cell def print_hello(to): "Print hello to the user" return f"Hello, {to}!"
__all__ = ['print_hello'] def print_hello(to): """Print hello to the user""" return f'Hello, {to}!'
''' Created on Aug 4, 2012 @author: vinnie ''' class Rotor(object): def __init__(self, symbols, permutation): ''' ''' self.states = [] self.inverse_states = [] self.n_symbols = len(symbols) for i in range(self.n_symbols): self.states.append({sy...
""" Created on Aug 4, 2012 @author: vinnie """ class Rotor(object): def __init__(self, symbols, permutation): """ """ self.states = [] self.inverse_states = [] self.n_symbols = len(symbols) for i in range(self.n_symbols): self.states.append({sy...
class BasePexelError(Exception): pass class EndpointNotExists(BasePexelError): def __init__(self, end_point, _enum) -> None: options = _enum.__members__.keys() self.message = f'Endpoint "{end_point}" not exists. Valid endpoints: {", ".join(options)}' super().__init__(self.message) c...
class Basepexelerror(Exception): pass class Endpointnotexists(BasePexelError): def __init__(self, end_point, _enum) -> None: options = _enum.__members__.keys() self.message = f'''Endpoint "{end_point}" not exists. Valid endpoints: {', '.join(options)}''' super().__init__(self.message) ...
#https://www.acmicpc.net/problem/1712 a, b, b2 = map(int, input().split()) if b >= b2: print(-1) else: bx = b2 - b count = a // bx + 1 print(count)
(a, b, b2) = map(int, input().split()) if b >= b2: print(-1) else: bx = b2 - b count = a // bx + 1 print(count)
grade_1 = [9.5,8.5,6.45,21] grade_1_sum = sum(grade_1) print(grade_1_sum) grade_1_len = len(grade_1) print(grade_1_len) grade_avg = grade_1_sum/grade_1_len print(grade_avg) # create Function def mean(myList): the_mean = sum(myList) / len(myList) return the_mean print(mean([10,1,1,10])) def mean_1(value)...
grade_1 = [9.5, 8.5, 6.45, 21] grade_1_sum = sum(grade_1) print(grade_1_sum) grade_1_len = len(grade_1) print(grade_1_len) grade_avg = grade_1_sum / grade_1_len print(grade_avg) def mean(myList): the_mean = sum(myList) / len(myList) return the_mean print(mean([10, 1, 1, 10])) def mean_1(value): if type(va...
if 0: pass if 1: pass else: pass if 2: pass elif 3: pass if 4: pass elif 5: pass else: 1
if 0: pass if 1: pass else: pass if 2: pass elif 3: pass if 4: pass elif 5: pass else: 1
print("Halo") print("This is my program in vscode ") name = input("what your name : ") if name == "Hero": print("Wow your name {} ? , my name is Hero too, nice to meet you ! ".format(name)) else: print("Halo {} , nice to meet you friend".format(name)) age = input("how old are you : ") if age == "21": ...
print('Halo') print('This is my program in vscode ') name = input('what your name : ') if name == 'Hero': print('Wow your name {} ? , my name is Hero too, nice to meet you ! '.format(name)) else: print('Halo {} , nice to meet you friend'.format(name)) age = input('how old are you : ') if age == '21': print(...
def foo(numbers, path, index, cur_val, target): if index == len(numbers): return cur_val, path # No point in continuation if cur_val > target: return -1, "" sol_1 = foo(numbers, path+"1", index+1, cur_val+numbers[index], target) # Found the solution. Do not continue. if sol_1[0] == target: ...
def foo(numbers, path, index, cur_val, target): if index == len(numbers): return (cur_val, path) if cur_val > target: return (-1, '') sol_1 = foo(numbers, path + '1', index + 1, cur_val + numbers[index], target) if sol_1[0] == target: return sol_1 sol_2 = foo(numbers, path + ...