content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
#default parameters #you can make default parameter(last_name= 'unknown') in last like after age #if we make all parameters defalut than ouput is unknowndef user_info(first_name='unknown', last_name= 'unknown',age = None) # None is used for numbers #'unknown' is used for string def user_info(first_name, last_name,age)...
def user_info(first_name, last_name, age): print(f'Your First name is: {first_name} ') print(f'Your last name is: {last_name} ') print(f'Your age is: {age} ') user_info('Beenash', 'Pervaiz', 20)
def total(lists): array = [] sum = 0 for i in lists: sum += i array.append(sum) return array listss = [1,2,3,5,5,4] print(total(listss))
def total(lists): array = [] sum = 0 for i in lists: sum += i array.append(sum) return array listss = [1, 2, 3, 5, 5, 4] print(total(listss))
description = 'Setup for the ma11 dom motor' devices = dict( dom = device('nicos_ess.devices.epics.motor.EpicsMotor', description = 'Sample stick rotation', motorpv = 'SQ:SANS:ma11:dom', errormsgpv = 'SQ:SANS:ma11:dom-MsgTxt', precision = 0.1, ), )
description = 'Setup for the ma11 dom motor' devices = dict(dom=device('nicos_ess.devices.epics.motor.EpicsMotor', description='Sample stick rotation', motorpv='SQ:SANS:ma11:dom', errormsgpv='SQ:SANS:ma11:dom-MsgTxt', precision=0.1))
with open("input.txt", "r") as f: values = [int(e) for e in f.readlines()] windowsSum = list() index = 0 for value in values: if(index+2 < len(values)): sum = value sum += values[index+1] sum += values[index+2] windowsSum.append(sum) index...
with open('input.txt', 'r') as f: values = [int(e) for e in f.readlines()] windows_sum = list() index = 0 for value in values: if index + 2 < len(values): sum = value sum += values[index + 1] sum += values[index + 2] windowsSum.append(sum) ...
TOKEN = "<Your Bot Token Here>" LOG_LEVEL_STDOUT = "DEBUG" # Console log level LOG_LEVEL_FILE = "INFO" # File log level
token = '<Your Bot Token Here>' log_level_stdout = 'DEBUG' log_level_file = 'INFO'
_base_ = './retinanet_r50_fpn_1x_cityscapes.py' model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint='checkpoints/resnet101-63fe2227.pth'))) # load_from="checkpoints/retinanet_r101_fpn_mstrain_3x_coco_20210720_214650-7ee888e0.pth"
_base_ = './retinanet_r50_fpn_1x_cityscapes.py' model = dict(backbone=dict(depth=101, init_cfg=dict(type='Pretrained', checkpoint='checkpoints/resnet101-63fe2227.pth')))
class Player: def __init__(self, name, life_value, attack_value): self.name = name self.life_value = life_value self.attack_value = attack_value def attack(self, enemy_player: 'Player'): enemy_player.life_value = enemy_player.life_value - self.attack_value def is_alive(self...
class Player: def __init__(self, name, life_value, attack_value): self.name = name self.life_value = life_value self.attack_value = attack_value def attack(self, enemy_player: 'Player'): enemy_player.life_value = enemy_player.life_value - self.attack_value def is_alive(sel...
# Define physical constants P0 = 1000. # Ground pressure level. Unit: hPa SCALE_HEIGHT = 7000. # Unit: m CP = 1004. # specific heat at constant pressure for air (cp) = 1004 J/kg-K DRY_GAS_CONSTANT = 287. EARTH_RADIUS = 6.378e+6 # Unit: m EARTH_OMEGA = 7.29e-5
p0 = 1000.0 scale_height = 7000.0 cp = 1004.0 dry_gas_constant = 287.0 earth_radius = 6378000.0 earth_omega = 7.29e-05
with open('./input.txt') as input: lines = [int(s.strip()) for s in input.readlines()] last = 999999999999 counter = 0 for (a, b, c) in zip(lines[0:-2], lines[1:-1], lines[2:]): current = a + b + c if (current > last): counter += 1 last = current print(counter) # ...
with open('./input.txt') as input: lines = [int(s.strip()) for s in input.readlines()] last = 999999999999 counter = 0 for (a, b, c) in zip(lines[0:-2], lines[1:-1], lines[2:]): current = a + b + c if current > last: counter += 1 last = current print(counter)
# This program saves a list of numbers to a file. def main(): # Create a list of numbers. numbers = [1, 2, 3, 4, 5, 6, 7] # Open a file for writing. outfile = open('numberlist.txt', 'w') # Write the list to the file. for item in numbers: outfile.write(str(item) + '\n') ...
def main(): numbers = [1, 2, 3, 4, 5, 6, 7] outfile = open('numberlist.txt', 'w') for item in numbers: outfile.write(str(item) + '\n') outfile.close() main()
x = int(input('Enter your Age: ')) print('****************') for i in range(0, 1): if x >= 18: print('You can watch content with R-rating') elif x >= 13: print('You can watch movies under parental guidance ') else: print('Cartoons permitted') print(' Thanks! ')
x = int(input('Enter your Age: ')) print('****************') for i in range(0, 1): if x >= 18: print('You can watch content with R-rating') elif x >= 13: print('You can watch movies under parental guidance ') else: print('Cartoons permitted') print(' Thanks! ')
def internal_consistency_check(Reports_dict, reportnos=None): return_dict = {} if reportnos: search_list = reportnos else: search_list = list(Reports_dict.keys()) for reportno in search_list: rdf = pd.DataFrame() rdf = Reports_dict[reportno].copy() print('REPORT',...
def internal_consistency_check(Reports_dict, reportnos=None): return_dict = {} if reportnos: search_list = reportnos else: search_list = list(Reports_dict.keys()) for reportno in search_list: rdf = pd.DataFrame() rdf = Reports_dict[reportno].copy() print('REPORT',...
N = int(input()) X = 1 K = 0 while X <= N: X *= 2 K += 1 print(max(0, K - 1))
n = int(input()) x = 1 k = 0 while X <= N: x *= 2 k += 1 print(max(0, K - 1))
data_in = [3.0, 1.0, 0.0, 0.0, 1.0, 6.0, 1.0, 0.0, 1.0, 0.0, 3280.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ...
data_in = [3.0, 1.0, 0.0, 0.0, 1.0, 6.0, 1.0, 0.0, 1.0, 0.0, 3280.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0...
# Parsers # Parse initial fields name to normalized form. parse_name = lambda name: str(name).replace(' ', '_').lower()
parse_name = lambda name: str(name).replace(' ', '_').lower()
# Oct 2021 # Class for extraction.py class FoundExpression: def __init__(self, expression: str, file: str, language: str, line_no: int): self.expression = expression self.language = language self.file = file self.line_no = line_no
class Foundexpression: def __init__(self, expression: str, file: str, language: str, line_no: int): self.expression = expression self.language = language self.file = file self.line_no = line_no
class Solution: def minOperations(self, nums: List[int]) -> int: n = len(nums) ans = n nums = sorted(set(nums)) for i, start in enumerate(nums): end = start + n - 1 index = bisect_right(nums, end) uniqueLength = index - i ans = min(ans, n - uniqueLength) return ans
class Solution: def min_operations(self, nums: List[int]) -> int: n = len(nums) ans = n nums = sorted(set(nums)) for (i, start) in enumerate(nums): end = start + n - 1 index = bisect_right(nums, end) unique_length = index - i ans = min...
data = ( 'jun', # 0x00 'junj', # 0x01 'junh', # 0x02 'jud', # 0x03 'jul', # 0x04 'julg', # 0x05 'julm', # 0x06 'julb', # 0x07 'juls', # 0x08 'jult', # 0x09 'julp', # 0x0a 'julh', # 0x0b 'jum', # 0x0c 'jub', # 0x0d 'jubs', # 0x0e 'jus', # 0x0f 'juss', #...
data = ('jun', 'junj', 'junh', 'jud', 'jul', 'julg', 'julm', 'julb', 'juls', 'jult', 'julp', 'julh', 'jum', 'jub', 'jubs', 'jus', 'juss', 'jung', 'juj', 'juc', 'juk', 'jut', 'jup', 'juh', 'jweo', 'jweog', 'jweogg', 'jweogs', 'jweon', 'jweonj', 'jweonh', 'jweod', 'jweol', 'jweolg', 'jweolm', 'jweolb', 'jweols', 'jweolt'...
def calculate_area(side_length=10): print(f"The area of a square with sides of length {side_length} is {side_length**2}.") length=int(input("Enter side length: ")) if length<=0: calculate_area(10) else: calculate_area(length)
def calculate_area(side_length=10): print(f'The area of a square with sides of length {side_length} is {side_length ** 2}.') length = int(input('Enter side length: ')) if length <= 0: calculate_area(10) else: calculate_area(length)
def find_max(num1, num2): max_num=-1 if num2> num1: data = range(num1,num2+1) main_list = [] for x in data: b = str(x) if x < 0: b = str(x*-1) sx = list(map(int,list(b))) if len(sx)==2 and sum(sx)%3==0 and x%5==0: ...
def find_max(num1, num2): max_num = -1 if num2 > num1: data = range(num1, num2 + 1) main_list = [] for x in data: b = str(x) if x < 0: b = str(x * -1) sx = list(map(int, list(b))) if len(sx) == 2 and sum(sx) % 3 == 0 and (x ...
def calc(): numOne = int(input("What is the first number of your problem?")) numTwo = int(input("What is the second number of your problem?")) numThree = input("What type of Math Problem is it, Addition, Subtraction, Multiplication, Division, Remainder, or Exponents? Type exactly.") if numThree == 'Addition': ...
def calc(): num_one = int(input('What is the first number of your problem?')) num_two = int(input('What is the second number of your problem?')) num_three = input('What type of Math Problem is it, Addition, Subtraction, Multiplication, Division, Remainder, or Exponents? Type exactly.') if numThree == 'A...
x_min = -2 y_min = (-(modelparams['weights'][0] * x_min) / modelparams['weights'][1] - (modelparams['bias'][0] / model_params['weights'][1])) x_max = 2 y_max = (-(modelparams['weights'][0] * x_max) / modelparams['weights'][1] - (modelparams['bias'][0] / modelparams['weights'][1])) fig, ax = plt.sub...
x_min = -2 y_min = -(modelparams['weights'][0] * x_min) / modelparams['weights'][1] - modelparams['bias'][0] / model_params['weights'][1] x_max = 2 y_max = -(modelparams['weights'][0] * x_max) / modelparams['weights'][1] - modelparams['bias'][0] / modelparams['weights'][1] (fig, ax) = plt.subplots(1, 2, sharex=True, fi...
for i in range(0, 201, 2): print(i) for i in range(0, 100, 3): print(i)
for i in range(0, 201, 2): print(i) for i in range(0, 100, 3): print(i)
# This is all about using strings stg_1 = "this is the first message without a tab" print(stg_1) stg_2 = "\t this is the second message with a tab" print(stg_2) stg_3 = "this is another message with a newline\n" print(stg_3)
stg_1 = 'this is the first message without a tab' print(stg_1) stg_2 = '\t this is the second message with a tab' print(stg_2) stg_3 = 'this is another message with a newline\n' print(stg_3)
#!/usr/bin/python # unicode.py text = u'\u041b\u0435\u0432 \u041d\u0438\u043a\u043e\u043b\u0430\ \u0435\u0432\u0438\u0447 \u0422\u043e\u043b\u0441\u0442\u043e\u0439: \n\ \u0410\u043d\u043d\u0430 \u041a\u0430\u0440\u0435\u043d\u0438\u043d\u0430' print (text)
text = u'Лев Николаевич Толстой: \nАнна Каренина' print(text)
#to have some interaction #we need an loop to look for actions def setup(): size(400, 400) #executed once println("This is the setup. Executed once. Initiate things here") #executed all the time waiting for infos def draw(): #do the bakcground color transformation noStroke() fill(map(mouseX, w...
def setup(): size(400, 400) println('This is the setup. Executed once. Initiate things here') def draw(): no_stroke() fill(map(mouseX, width, 0, 0, width), 100) rect(0, 0, width, height) fill(mouseX) ellipse(mouseX, mouseY, 10, 10) println('Frame number: ' + frameCount) print('mouse...
########################################################################## # NSAp - Copyright (C) CEA, 2013 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html # for details. ##########...
options = (('documentation_folder', {'type': 'string', 'default': None, 'help': 'the folder containing the documentation of the project.', 'group': 'piws', 'level': 1}), ('show_user_status', {'type': 'yn', 'default': True, 'help': 'Show or not the user status link on the website.', 'group': 'piws', 'level': 1}), ('ldap...
class Command: def __init__(self, name, desc="", args=[]): self.name = name self.desc = desc self.args = args
class Command: def __init__(self, name, desc='', args=[]): self.name = name self.desc = desc self.args = args
n1,n2=map(int,input().split()) a=[] for i in range(n2): a.append(list(map(float,input().split()))) for i in zip(*a): print(sum(i)/n2)
(n1, n2) = map(int, input().split()) a = [] for i in range(n2): a.append(list(map(float, input().split()))) for i in zip(*a): print(sum(i) / n2)
def read_txt_file_str(filename): f=open('text_files/'+filename, "r") contents=f.read() f.close() return contents def read_txt_file_list(filename): f=open('text_files/'+filename, "r") contents=f.readlines() f.close() return contents
def read_txt_file_str(filename): f = open('text_files/' + filename, 'r') contents = f.read() f.close() return contents def read_txt_file_list(filename): f = open('text_files/' + filename, 'r') contents = f.readlines() f.close() return contents
# Author: Jocelino F.G. n = int(input()) vetor = [n] dobro = n for i in range(0, 10): dobro = dobro * 2 vetor.append(dobro) print("N[{}] = {}".format(i, vetor[i]))
n = int(input()) vetor = [n] dobro = n for i in range(0, 10): dobro = dobro * 2 vetor.append(dobro) print('N[{}] = {}'.format(i, vetor[i]))
def is_even(number): return number % 2 == 0
def is_even(number): return number % 2 == 0
class InvalidOperationError(BaseException): pass class Node(): def __init__(self, value, next=None): self.value = value self.next = next class Stack(): def __init__(self, node=None): self.top = node def __len__(self): count = 0 curr = self.top while ...
class Invalidoperationerror(BaseException): pass class Node: def __init__(self, value, next=None): self.value = value self.next = next class Stack: def __init__(self, node=None): self.top = node def __len__(self): count = 0 curr = self.top while curr:...
# Given x = 10000.0 y = 3.0 print(x / y) print(10000 / 3) # What is happening? # Given print(x - 1 / y) print((x - 1) / y) # What is happening? # Given x = 'foo' y = 'bar' # Create 'foobar' using x and y s = x + y print(s) # Create 'foo -> bar' using x and y print(x + " -> " + y) # Given x = 'hello world' # from x ...
x = 10000.0 y = 3.0 print(x / y) print(10000 / 3) print(x - 1 / y) print((x - 1) / y) x = 'foo' y = 'bar' s = x + y print(s) print(x + ' -> ' + y) x = 'hello world' print(x.upper()) print(x.replace('o', 'X')) x = 10000.0 y = 3.0 print('{x} / {y} = {z}'.format(x=x, y=y, z=x / y)) s = ['hello', 'world'] print(s[0] + s[1]...
class Config: def __init__(self): self.data_dir = './data/' self.data_path = self.data_dir + 'peot.txt' self.pickle_path = self.data_dir + 'tang.npz' self.load_path = './checkpoints/peot9.pt' self.save_path = './checkpoints/peot9.pt' self.do_train = False sel...
class Config: def __init__(self): self.data_dir = './data/' self.data_path = self.data_dir + 'peot.txt' self.pickle_path = self.data_dir + 'tang.npz' self.load_path = './checkpoints/peot9.pt' self.save_path = './checkpoints/peot9.pt' self.do_train = False sel...
''' @Author: Ofey Chan @Date: 2020-03-03 19:23:15 @LastEditors: Ofey Chan @LastEditTime: 2020-03-03 20:07:31 @Description: General permutation group class. @Reference: '''
""" @Author: Ofey Chan @Date: 2020-03-03 19:23:15 @LastEditors: Ofey Chan @LastEditTime: 2020-03-03 20:07:31 @Description: General permutation group class. @Reference: """
# Forcing recursion for no good reason. But it passed so.... def solution_r(n): if n <= 0: return n else: if not n%3 or not n%5: return n + solution_r(n-1) else: return solution_r(n-1) def solution(number): if not number: return 0 return solutio...
def solution_r(n): if n <= 0: return n elif not n % 3 or not n % 5: return n + solution_r(n - 1) else: return solution_r(n - 1) def solution(number): if not number: return 0 return solution_r(number - 1) assert solution(10) == 23, 'Oops, recursion is the devil'
class Solution: def minJumps(self, arr: List[int]) -> int: graph = defaultdict(list) for i in range(len(arr)): graph[arr[i]].append(i) visited = set() src, dest = 0, len(arr) - 1 queue = deque() queue.append((src, 0)) visited.add(src) whil...
class Solution: def min_jumps(self, arr: List[int]) -> int: graph = defaultdict(list) for i in range(len(arr)): graph[arr[i]].append(i) visited = set() (src, dest) = (0, len(arr) - 1) queue = deque() queue.append((src, 0)) visited.add(src) ...
def transitions(y,x): yield y+1,x yield y,x+1 yield y-1,x yield y,x-1 def valid_transitions(arr): # print(arr) Y = len(arr) X = len(arr[0]) def _f(y0,x0): for y,x in transitions(y0,x0): if 0 <= y < Y and 0 <= x < X and arr[y][x] != "-": yield y,x ...
def transitions(y, x): yield (y + 1, x) yield (y, x + 1) yield (y - 1, x) yield (y, x - 1) def valid_transitions(arr): y = len(arr) x = len(arr[0]) def _f(y0, x0): for (y, x) in transitions(y0, x0): if 0 <= y < Y and 0 <= x < X and (arr[y][x] != '-'): yi...
def insertShiftArray(arr, value): mid = len(arr) // 2 new_arr = [] for i in range(0, mid): new_arr.append(arr[i]) new_arr.append(value) for i in range(mid, len(arr)): new_arr.append(arr[i]) return new_arr test = [1, 2, 3, 4, 5] print(test) print(insertSh...
def insert_shift_array(arr, value): mid = len(arr) // 2 new_arr = [] for i in range(0, mid): new_arr.append(arr[i]) new_arr.append(value) for i in range(mid, len(arr)): new_arr.append(arr[i]) return new_arr test = [1, 2, 3, 4, 5] print(test) print(insert_shift_array(test, 8)) tes...
class Hamming: def distance(self, first, second): num_of_errors = 0 if type(first) != str or type(second) != str: return "Wrong type of strands" if len(first) != len(second): return "Strands should be the same length" for i in range(len(first)): if...
class Hamming: def distance(self, first, second): num_of_errors = 0 if type(first) != str or type(second) != str: return 'Wrong type of strands' if len(first) != len(second): return 'Strands should be the same length' for i in range(len(first)): i...
conditons = True alcool = 0 gas = 0 disel = 0 while conditons : T = int(input()) if T == 4: conditons = False; else: if T == 1: alcool +=1 if T == 2: gas +=1 if T == 3: disel +=1 print("MUITO OBRIGADO") print(f"Alcool: {alcool}") print(...
conditons = True alcool = 0 gas = 0 disel = 0 while conditons: t = int(input()) if T == 4: conditons = False else: if T == 1: alcool += 1 if T == 2: gas += 1 if T == 3: disel += 1 print('MUITO OBRIGADO') print(f'Alcool: {alcool}') print(f'G...
def estimator(data): output = {'data':data, 'impact': {}, 'severeImpact': {}} output['impact']['currentlyInfected'] = data['reportedCases'] * 10 output['severeImpact']['currentlyInfected'] = data['reportedCases'] * 50 if data['periodType'] == 'weeks': data['timeToElapse'] = data['timeToElapse'] ...
def estimator(data): output = {'data': data, 'impact': {}, 'severeImpact': {}} output['impact']['currentlyInfected'] = data['reportedCases'] * 10 output['severeImpact']['currentlyInfected'] = data['reportedCases'] * 50 if data['periodType'] == 'weeks': data['timeToElapse'] = data['timeToElapse']...
# -*- python -*- load("@drake//tools/workspace:os.bzl", "determine_os") def _impl(repository_ctx): os_result = determine_os(repository_ctx) if os_result.error != None: fail(os_result.error) if os_result.is_macos: repository_ctx.symlink( "/usr/local/opt/double-conversion/inclu...
load('@drake//tools/workspace:os.bzl', 'determine_os') def _impl(repository_ctx): os_result = determine_os(repository_ctx) if os_result.error != None: fail(os_result.error) if os_result.is_macos: repository_ctx.symlink('/usr/local/opt/double-conversion/include', 'include') repositor...
def linear_search(array, y): for i in range(len(array)): if array[i] == y: return i return -1 arrSize=int(input("Enter Array Size")) array=[] print("Enter Array Elements") for i in range(arrSize): array.append(int(input())) y = int(input("Enter Number you want to find =:...
def linear_search(array, y): for i in range(len(array)): if array[i] == y: return i return -1 arr_size = int(input('Enter Array Size')) array = [] print('Enter Array Elements') for i in range(arrSize): array.append(int(input())) y = int(input('Enter Number you want to find =:-')) result ...
# https://atcoder.jp/contests/abc194/tasks/abc194_b N = int(input()) job_list = [] a_min_idx, b_min_idx = 0, 0 a_2nd, b_2nd = 0, 0 for i in range(N): a, b = list(map(int, input().split())) job_list.append([a, b]) if job_list[a_min_idx][0] > a: a_2nd = a_min_idx a_min_idx = i if job_list[...
n = int(input()) job_list = [] (a_min_idx, b_min_idx) = (0, 0) (a_2nd, b_2nd) = (0, 0) for i in range(N): (a, b) = list(map(int, input().split())) job_list.append([a, b]) if job_list[a_min_idx][0] > a: a_2nd = a_min_idx a_min_idx = i if job_list[b_min_idx][1] > b: b_2nd = b_min_i...
# https://practice.geeksforgeeks.org/problems/get-minimum-element-from-stack/1# # Approach is to store an array containing stack elements and minEle in separate variable # For push # if minEle is None add element to s and assign minEle - element # if minEle <= element add element to s # else add 2*x-minEle in s ...
class Stack: def __init__(self): self.s = [] self.minEle = None def push(self, x): if self.minEle is None: self.minEle = x self.s.append(x) elif self.minEle <= x: self.s.append(x) else: self.s.append(2 * x - self.minEle) ...
# MIT License # # Copyright (c) 2017 Matt Boyer # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, p...
valid_page_sizes = (1, 512, 1024, 2048, 4096, 8192, 16384, 32768) sqlite_table_columns = {'sqlite_master': ('type', 'name', 'tbl_name', 'rootpage', 'sql'), 'sqlite_sequence': ('name', 'seq'), 'sqlite_stat1': ('tbl', 'idx', 'stat'), 'sqlite_stat2': ('tbl', 'idx', 'sampleno', 'sample'), 'sqlite_stat3': ('tbl', 'idx', 'nE...
# #### We create a function cleanQ so we can do the cleaning and preperation of our data # #### INPUT: String # #### OUTPUT: Cleaned String def cleanQ(query): query = query.lower() tokenizer = RegexpTokenizer(r'\w+') tokens = tokenizer.tokenize(query) stemmer=[ps.stem(i) for i in tokens] filtered...
def clean_q(query): query = query.lower() tokenizer = regexp_tokenizer('\\w+') tokens = tokenizer.tokenize(query) stemmer = [ps.stem(i) for i in tokens] filtered_q = [w for w in stemmer if not w in stopwords.words('english')] return filtered_Q def compute_tf(doc_words): bow = 0 for (k, ...
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # OpneWinchPy : a library for controlling the Raspberry Pi's Winch # Copyright (c) 2020 Mickael Gaillard <mick.gaillard@gmail.com> __version__ = "0.1.0"
__version__ = '0.1.0'
lst = [] count_of_elements = int(input("How many elements want to store in list?")) for i in range(count_of_elements): element = input("Enter the element:") lst.append(element) print(lst)
lst = [] count_of_elements = int(input('How many elements want to store in list?')) for i in range(count_of_elements): element = input('Enter the element:') lst.append(element) print(lst)
class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: ans = [] one_hot = {} for word in strs: mapping = [0 for _ in range(26)] for char in word: representation = ord(char) mapping[representation % 26] += 1 ...
class Solution: def group_anagrams(self, strs: List[str]) -> List[List[str]]: ans = [] one_hot = {} for word in strs: mapping = [0 for _ in range(26)] for char in word: representation = ord(char) mapping[representation % 26] += 1 ...
# -*- coding: utf-8 -*- __author__ = 'Tommy Stallings' __email__ = 'tommy.stallings2@gmail.com' __version__ = '1.0'
__author__ = 'Tommy Stallings' __email__ = 'tommy.stallings2@gmail.com' __version__ = '1.0'
def GetChargeLevel(): return {'data': 42, 'error': 'NO_ERROR'} def GetBatteryTemperature(): return {'data': 25.4, 'error': 'NO_ERROR'} def GetBatteryVoltage(): return {'data': 3111, 'error': 'NO_ERROR'} def GetBatteryCurrent(): return {'data': 800, 'error': 'NO_ERROR'} def GetIoVoltage(): re...
def get_charge_level(): return {'data': 42, 'error': 'NO_ERROR'} def get_battery_temperature(): return {'data': 25.4, 'error': 'NO_ERROR'} def get_battery_voltage(): return {'data': 3111, 'error': 'NO_ERROR'} def get_battery_current(): return {'data': 800, 'error': 'NO_ERROR'} def get_io_voltage(): ...
def message_replier(messages): for message in messages: userid = message.from_user.id banlist = redisserver.sismember('zigzag_banlist', '{}'.format(userid)) if banlist: return if userid in messanger_list: bot.reply_to(message, MESSANGER_LEAVE_MSG, parse_mode="Markdown") messanger_lis...
def message_replier(messages): for message in messages: userid = message.from_user.id banlist = redisserver.sismember('zigzag_banlist', '{}'.format(userid)) if banlist: return if userid in messanger_list: bot.reply_to(message, MESSANGER_LEAVE_MSG, parse_mode='...
def maior_E_menor(x, y): if x > y: return x, y return y, x x = int(input()) y = int(input()) if(x == y): print("0") else: maior, menor = maior_E_menor(x, y) soma = 0 menor +=1 while(menor < maior): if menor % 2 != 0: soma += menor menor += 1 print(s...
def maior_e_menor(x, y): if x > y: return (x, y) return (y, x) x = int(input()) y = int(input()) if x == y: print('0') else: (maior, menor) = maior_e_menor(x, y) soma = 0 menor += 1 while menor < maior: if menor % 2 != 0: soma += menor menor += 1 print...
# Want to extract domain hotmail.com data = 'From ritchie_ng@hotmail.com Tues May 31' at_position = data.find('@') print(at_position) space_position = data.find(' ', at_position) # Starting from at_position, where's the next space print(space_position) host = data[at_position + 1: space_position] print(host)
data = 'From ritchie_ng@hotmail.com Tues May 31' at_position = data.find('@') print(at_position) space_position = data.find(' ', at_position) print(space_position) host = data[at_position + 1:space_position] print(host)
def stable_sorted_copy(alist, _indices=xrange(sys.maxint)): # the 'decorate' step: make a list such that each item # is the concatenation of sort-keys in order of decreasing # significance -- we'll sort this auxiliary-list decorated = zip(alist, _indices) # the 'sort' step: just builtin-sort the au...
def stable_sorted_copy(alist, _indices=xrange(sys.maxint)): decorated = zip(alist, _indices) decorated.sort() return [item for (item, index) in decorated] def stable_sort_inplace(alist): alist[:] = stable_sorted_copy(alist)
def wellbracketed(s): c=0 for i in range(0, len(s)): if s[i] == "(": c = c + 1 elif s[i] == ")": c = c - 1 if c == 0: return(True) else: return(False)
def wellbracketed(s): c = 0 for i in range(0, len(s)): if s[i] == '(': c = c + 1 elif s[i] == ')': c = c - 1 if c == 0: return True else: return False
#!/usr/bin/env python3 # Get superior triangular matrix a) n = 3 A = [[1, 1/2, 1/3], [1/2, 1/3, 1/4], [1/3, 1/4, 1/5]] b = [-1, 1, 1] for i in range(n): pivot = A[i][i] b[i] /= pivot for j in range(n): A[i][j] /= pivot for j in range(i+1, n): times = A[j][i] b[j] -= times * b[...
n = 3 a = [[1, 1 / 2, 1 / 3], [1 / 2, 1 / 3, 1 / 4], [1 / 3, 1 / 4, 1 / 5]] b = [-1, 1, 1] for i in range(n): pivot = A[i][i] b[i] /= pivot for j in range(n): A[i][j] /= pivot for j in range(i + 1, n): times = A[j][i] b[j] -= times * b[i] for k in range(n): A[...
class CustomerAddWebsitePermissionDenied(Exception): pass class ObjectDoesNotExist(Exception): pass
class Customeraddwebsitepermissiondenied(Exception): pass class Objectdoesnotexist(Exception): pass
#!/bin/python3 def main(person_list): users = [] for name, email in person_list: if email.endswith('@gmail.com'): users.append(name) print(*sorted(users), sep='\n') if __name__ == '__main__': N = int(input()) persons = [] for N_itr in range(N): firstName, emailID ...
def main(person_list): users = [] for (name, email) in person_list: if email.endswith('@gmail.com'): users.append(name) print(*sorted(users), sep='\n') if __name__ == '__main__': n = int(input()) persons = [] for n_itr in range(N): (first_name, email_id) = input().spl...
# basic example class MetaSpam(type): # notice how the __new__ method has the same arguments # as the type function we used earlier. def __new__(metaclass, name, bases, namespace): name = 'SpamCreateByMeta' bases = (int,) + bases namespace['eggs'] = 1 return type.__new...
class Metaspam(type): def __new__(metaclass, name, bases, namespace): name = 'SpamCreateByMeta' bases = (int,) + bases namespace['eggs'] = 1 return type.__new__(metaclass, name, bases, namespace) class Spam(object): pass print(Spam.__name__) print(issubclass(Spam, int)) try: ...
S = input() for i in range(len(S)): print(i + 1)
s = input() for i in range(len(S)): print(i + 1)
def c_to_f(c): Farhenheite=(c*9/5)+32 return Farhenheite n=int(input("Celcius=")) f=c_to_f(n) print(f,"'F")
def c_to_f(c): farhenheite = c * 9 / 5 + 32 return Farhenheite n = int(input('Celcius=')) f = c_to_f(n) print(f, "'F")
class QueueOverflow(BaseException): pass # Node of a doubly linkedlist class Node: # constructor def __init__(self, data=None): self.data = data self.next = None self.prev = None # method for setting the data field of the node def setData(self, data): self.data = d...
class Queueoverflow(BaseException): pass class Node: def __init__(self, data=None): self.data = data self.next = None self.prev = None def set_data(self, data): self.data = data def get_data(self): return self.data def set_next(self, nextOne): sel...
#!/usr/bin/python ''' Copyright 2016 Aaron Stephens <aaron@icebrg.io>, ICEBRG Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by app...
""" Copyright 2016 Aaron Stephens <aaron@icebrg.io>, ICEBRG Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agre...
class ProfilePage: BACK_TO_USERS = "Back to members" EDIT_USER_BUTTON = "Change role" USER_EMAIL = "Email" USER_FIRST_NAME = "First name" USER_LAST_NAME = "Last name" USER_ROLE = "Role" USER_STATUS = "Status" USER_PENDING = "Pending" USER_DEACTIVATE = "Deactivate member" USER_REA...
class Profilepage: back_to_users = 'Back to members' edit_user_button = 'Change role' user_email = 'Email' user_first_name = 'First name' user_last_name = 'Last name' user_role = 'Role' user_status = 'Status' user_pending = 'Pending' user_deactivate = 'Deactivate member' user_rea...
'''Program to find the factorial of a number using recursion''' def factorial_of_a_number(n): if n<=1: return 1 else: return n * factorial_of_a_number(n-1) #Taking number from user and passing it to the function n = int(input()) print(factorial_of_a_number(n))
"""Program to find the factorial of a number using recursion""" def factorial_of_a_number(n): if n <= 1: return 1 else: return n * factorial_of_a_number(n - 1) n = int(input()) print(factorial_of_a_number(n))
def dec_to_bin(n): if n < 0: return bin(n * -1)[2:] return bin(n)[2:] def trim_to(number, length): zeroes = '' for i in range(int(length) - len(number)): zeroes += '0' return zeroes + number def bit_not(number): negated = '' for bit in number: if bit == '1': negated += '...
def dec_to_bin(n): if n < 0: return bin(n * -1)[2:] return bin(n)[2:] def trim_to(number, length): zeroes = '' for i in range(int(length) - len(number)): zeroes += '0' return zeroes + number def bit_not(number): negated = '' for bit in number: if bit == '1': ...
def printSet(set): sorted(set) print('{', end=" ") for x in set : print(x, end=" ") print('}') def main(): a = set("Hi There, Raghuram") b = set("Hello, Nice to Meet you") x = set('hello') y = set('world') printSet(a) printSet(b) printSet(x - y ) if __name__ == "__...
def print_set(set): sorted(set) print('{', end=' ') for x in set: print(x, end=' ') print('}') def main(): a = set('Hi There, Raghuram') b = set('Hello, Nice to Meet you') x = set('hello') y = set('world') print_set(a) print_set(b) print_set(x - y) if __name__ == '__...
with open('input.txt') as f: lines = [int(i) for i in f.readlines()] depth_increased = 0 for i in range(0, len(lines) - 3): last_sum = sum(lines[i-1:i+2]) current_sum = sum(lines[i:i+3]) if (current_sum > last_sum): depth_increased = depth_increased + ...
with open('input.txt') as f: lines = [int(i) for i in f.readlines()] depth_increased = 0 for i in range(0, len(lines) - 3): last_sum = sum(lines[i - 1:i + 2]) current_sum = sum(lines[i:i + 3]) if current_sum > last_sum: depth_increased = depth_increased + 1 print(dept...
class Bye: def __init__(self): self.foo = 'bar' def is_hello(self): return type(self) == Hello class Hello: def __init__(self): self.value = 'foobar' print(Bye().is_hello())
class Bye: def __init__(self): self.foo = 'bar' def is_hello(self): return type(self) == Hello class Hello: def __init__(self): self.value = 'foobar' print(bye().is_hello())
# Leetcode 70. Climbing Stairs # # Link: https://leetcode.com/problems/climbing-stairs/ # Difficulty: Easy # Solution using DP # Complexity: # O(N) time | where N represent the number of steps of the staircase # O(1) space class Solution: def climbStairs(self, n: int) -> int: one, two = 1, 1 ...
class Solution: def climb_stairs(self, n: int) -> int: (one, two) = (1, 1) for i in range(n - 1): (one, two) = (one + two, one) return one
## Set to display confirmation dialog on exit. You can always use 'exit' or # 'quit', to force a direct exit without any confirmation. c.JupyterConsoleApp.confirm_exit = False ## Whether to display a banner upon starting the QtConsole. c.JupyterQtConsoleApp.display_banner = False ## Start the console window with the...
c.JupyterConsoleApp.confirm_exit = False c.JupyterQtConsoleApp.display_banner = False c.JupyterQtConsoleApp.hide_menubar = True
#66: Compute a Grade Point Average a={'A+':4.0,'A':4.0,'A-':3.7,'B+':3.3,'B':3.0,'B-':2.7,'C+':2.3,'C':2.0,'C-':1.7,'D+':1.3,'D':1.0,'F':0} add=lambda x,y:x+y c=0 d=0 while True: b=input("Enter the grade:") if b=="": break c=add(c,a[b]) d+=1 print("Average grade point:",c/d)
a = {'A+': 4.0, 'A': 4.0, 'A-': 3.7, 'B+': 3.3, 'B': 3.0, 'B-': 2.7, 'C+': 2.3, 'C': 2.0, 'C-': 1.7, 'D+': 1.3, 'D': 1.0, 'F': 0} add = lambda x, y: x + y c = 0 d = 0 while True: b = input('Enter the grade:') if b == '': break c = add(c, a[b]) d += 1 print('Average grade point:', c / d)
def test_mining_property_tester(web3_tester): web3 = web3_tester assert web3.eth.mining is False def test_mining_property_ipc_and_rpc(web3_empty, wait_for_miner_start, skip_if_testrpc): web3 = web3_empty skip_if_testrpc(web3) wait_for_miner_start(web3) a...
def test_mining_property_tester(web3_tester): web3 = web3_tester assert web3.eth.mining is False def test_mining_property_ipc_and_rpc(web3_empty, wait_for_miner_start, skip_if_testrpc): web3 = web3_empty skip_if_testrpc(web3) wait_for_miner_start(web3) assert web3.eth.mining is True
class Solution: def checkIfExist(self, arr): exists = {} for num in arr: if (num * 2) in exists or ((num / 2) in exists and num % 2 == 0): return True exists[num] = True return False
class Solution: def check_if_exist(self, arr): exists = {} for num in arr: if num * 2 in exists or (num / 2 in exists and num % 2 == 0): return True exists[num] = True return False
#input # 637 3371 327 67 924 968 2 6 6 77 5464 21813 70 5 67 74225 46 2 310 6156 50 4 623 87675 1702 3947 4927 9628 7 510 31 65 3321 23993 8406 88 -1 array = [int(x) for x in input().split()] array.remove(-1) swaps = 0 for i in range(0, len(array) - 1): if array[i] > array[i+1]: swaps += 1 t = array[i] ...
array = [int(x) for x in input().split()] array.remove(-1) swaps = 0 for i in range(0, len(array) - 1): if array[i] > array[i + 1]: swaps += 1 t = array[i] array[i] = array[i + 1] array[i + 1] = t checksum = 0 for num in array: checksum += num checksum *= 113 checksum %= 1000...
DEBUG = True
debug = True
# Write a program that reads a word and prints the number of syllables in the word. # For this exercise, assume that syllables are determined as follows: Each sequence of # adjacent vowels a e i o u y , except for the last e in a word, is a syllable. However, if # that algorithm yields a count of 0, change it to 1. F...
input_word = str(input('Enter a word: ')) vowels = ('a', 'e', 'i', 'o', 'u', 'y', 'A', 'E', 'I', 'O', 'U', 'Y') last_vowel = False last_cons = False curr_vowel = False curr_cons = False syllables_count = 0 for i in range(len(inputWord)): letter = inputWord[i] if letter in vowels: curr_vowel = True ...
# Maximum number of images to keep in the database MAX_FILES = 20 # Size of a JPEG minimum coded unit (MCU) BLOCK_SIZE = 16 # Images will be resized to this width IMAGE_WIDTH = 1200 # Image aspect ratio ASPECT_RATIO = 3
max_files = 20 block_size = 16 image_width = 1200 aspect_ratio = 3
# Source: https://leetcode.com/problems/contains-duplicate-iii/ # Better approach; Current time complexity: O(n * k) class Solution: def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool: if t == 0 and len(set(nums)) == len(nums): return False for i i...
class Solution: def contains_nearby_almost_duplicate(self, nums: List[int], k: int, t: int) -> bool: if t == 0 and len(set(nums)) == len(nums): return False for i in range(len(nums)): for j in range(i + 1, min(i + k + 1, len(nums))): if abs(nums[i] - nums[j])...
response = sm.sendAskYesNo("Are you sure you want to leave?") # sm.sendSay("Response was " + str(response) + "\r\rAnswer was " + str(answer)) if response: sm.clearPartyInfo(401060000) sm.dispose()
response = sm.sendAskYesNo('Are you sure you want to leave?') if response: sm.clearPartyInfo(401060000) sm.dispose()
VISIT_DETAIL_FORM_CONSTANTS = { 'visit_date':{ 'max_length': 100, "data-dojo-type": "dijit.form.DateTextBox", "data-dojo-props": r"'required' :true" }, 'op_surgeon':{ 'max_length': 100, "data-dojo-type": "dijit.form.Select", ...
visit_detail_form_constants = {'visit_date': {'max_length': 100, 'data-dojo-type': 'dijit.form.DateTextBox', 'data-dojo-props': "'required' :true"}, 'op_surgeon': {'max_length': 100, 'data-dojo-type': 'dijit.form.Select', 'data-dojo-props': "'required' : true"}, 'referring_doctor': {'max_length': 100, 'data-dojo-type':...
def _merge_mro(seqs): res = [] i = 0 while 1: nonemptyseqs = [seq for seq in seqs if seq] if not nonemptyseqs: return res i += 1 for seq in nonemptyseqs: cand = seq[0] nothead = [s for s in nonemptyseqs if cand in s[1:]] if nothead: cand = None else: break if not ca...
def _merge_mro(seqs): res = [] i = 0 while 1: nonemptyseqs = [seq for seq in seqs if seq] if not nonemptyseqs: return res i += 1 for seq in nonemptyseqs: cand = seq[0] nothead = [s for s in nonemptyseqs if cand in s[1:]] if noth...
def Skew(Genome): res = [0] for nuc in Genome: to_app = res[-1] if nuc == 'C': to_app -= 1 elif nuc == 'G': to_app += 1 res.append(to_app) return res def MinimumSkew(Genome): min_val = 0 current_val = 0 min_pos = [0] for i, nuc in enumerate(Genome): if nuc == 'C': current_val -= 1 elif nuc ...
def skew(Genome): res = [0] for nuc in Genome: to_app = res[-1] if nuc == 'C': to_app -= 1 elif nuc == 'G': to_app += 1 res.append(to_app) return res def minimum_skew(Genome): min_val = 0 current_val = 0 min_pos = [0] for (i, nuc) in e...
load("@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl", "tool_path", "action_config", "tool") load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES") def _impl(ctx): tool_paths = [ tool_path( name = "gcc", path = "wrapper_cc.sh", ), tool_path( ...
load('@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl', 'tool_path', 'action_config', 'tool') load('@bazel_tools//tools/build_defs/cc:action_names.bzl', 'ACTION_NAMES') def _impl(ctx): tool_paths = [tool_path(name='gcc', path='wrapper_cc.sh'), tool_path(name='g++', path='wrapper_cxx.sh'), tool_path(name='ld', ...
class Graph(): def __init__(self, vertices): self.V = vertices self.graph = [[0 for column in range(vertices)] for row in range(vertices)] def printSolution(self, dist): print("Vertex \t Distance from source") for node in range(self.V): print(node, "\t", dist[node]) ...
class Graph: def __init__(self, vertices): self.V = vertices self.graph = [[0 for column in range(vertices)] for row in range(vertices)] def print_solution(self, dist): print('Vertex \t Distance from source') for node in range(self.V): print(node, '\t', dist[node]) ...
def setup_animation(): init_figure() for line in lines: self.line = self.mplCanvas.canvas.ax.plot([], [], []) self.stopped = False
def setup_animation(): init_figure() for line in lines: self.line = self.mplCanvas.canvas.ax.plot([], [], []) self.stopped = False
def count_substring(string, sub_string): # Init counter counter = 0 # Find first index ind = string.find(sub_string) # Iterate over string for i in string: # If not found, return counter if ind == -1: return counter else: # Increment counter ...
def count_substring(string, sub_string): counter = 0 ind = string.find(sub_string) for i in string: if ind == -1: return counter else: counter += 1 string = string[ind + 1:] ind = string.find(sub_string) if __name__ == '__main__': string = ...
s = input() if s[0:3] == 'KIH': s = 'A'+s elif s[0:4] != 'AKIH': print('NO') exit(0) if s[4:5] == 'B': s = s[0:4]+'A'+s[4:] elif s[4:6] != 'AB': print('NO') exit(0) if s[5:7] == 'BR': s = s[0:6]+'A'+s[6:] elif s[5:7] != 'BA': print('NO') exit(0) if (s[7:9] == 'RA' and len(s) == 9...
s = input() if s[0:3] == 'KIH': s = 'A' + s elif s[0:4] != 'AKIH': print('NO') exit(0) if s[4:5] == 'B': s = s[0:4] + 'A' + s[4:] elif s[4:6] != 'AB': print('NO') exit(0) if s[5:7] == 'BR': s = s[0:6] + 'A' + s[6:] elif s[5:7] != 'BA': print('NO') exit(0) if s[7:9] == 'RA' and len(s)...
def main(): file = open('6.txt') banks = [] for line in file: cells = [int(i) for i in line.split()] banks.extend(cells) all_banks = [] while banks not in all_banks: all_banks.append(banks.copy()) i, m = max(enumerate(banks), key=lambda x: x[1]) banks[i] = 0 ...
def main(): file = open('6.txt') banks = [] for line in file: cells = [int(i) for i in line.split()] banks.extend(cells) all_banks = [] while banks not in all_banks: all_banks.append(banks.copy()) (i, m) = max(enumerate(banks), key=lambda x: x[1]) banks[i] = 0...
def get_key(x, y): return str(x)+"-"+str(y) #input_line = input("Enter input:\n") filename = "..\inputs\day_three_input.txt" f = open(filename) input_line = f.readline() x = 0 y = 0 present_locations = {} present_locations[get_key(x,y)]=1 for c in input_line: if c == ">": x += 1 elif c == "<": x -= 1 elif c ==...
def get_key(x, y): return str(x) + '-' + str(y) filename = '..\\inputs\\day_three_input.txt' f = open(filename) input_line = f.readline() x = 0 y = 0 present_locations = {} present_locations[get_key(x, y)] = 1 for c in input_line: if c == '>': x += 1 elif c == '<': x -= 1 elif c == '^': ...
class PersegiPanjang(object) : def __init__(self,p,l) : self.panjang = p self.lebar = l def hitungLuas(self) : return self.panjang * self.lebar def cetakLuas(self) : print('Panjang : ',self.panjang) print('Lebar : ',self.lebar) print('Luas : ',self.hitungLuas()) def main() : test = Per...
class Persegipanjang(object): def __init__(self, p, l): self.panjang = p self.lebar = l def hitung_luas(self): return self.panjang * self.lebar def cetak_luas(self): print('Panjang : ', self.panjang) print('Lebar : ', self.lebar) print('Luas : ', self.hitun...
#this code gives the numbers of integers, floats, and strings present in the list a= ['Hello',35,'b',45.5,'world',60] i=f=s=0 for j in a: if isinstance(j,int): i=i+1 elif isinstance(j,float): f=f+1 else: s=s+1 print('Number of integers are:',i) print('Number of Floats are:',f) prin...
a = ['Hello', 35, 'b', 45.5, 'world', 60] i = f = s = 0 for j in a: if isinstance(j, int): i = i + 1 elif isinstance(j, float): f = f + 1 else: s = s + 1 print('Number of integers are:', i) print('Number of Floats are:', f) print('numbers of strings are:', s)
while True: a, b = map(int, input().split()) if a == 0 and b == 0: break print("Yes" if (a > b) else "No")
while True: (a, b) = map(int, input().split()) if a == 0 and b == 0: break print('Yes' if a > b else 'No')
class ComplexNumber(object): def __init__(self, real, imag): self.real = real self.imag = imag def __add__(self, other): return ComplexNumber(self.real+other.real, self.imag+other.imag) def __sub__(self, other): return ComplexNumber(self.real-other.real, self.imag-other.ima...
class Complexnumber(object): def __init__(self, real, imag): self.real = real self.imag = imag def __add__(self, other): return complex_number(self.real + other.real, self.imag + other.imag) def __sub__(self, other): return complex_number(self.real - other.real, self.imag ...
rec3 = 0 rec4 = 0 def hanoi3num(n, origem, destino, trabalho): global rec3 rec3 += 1 if n == 1: return rec3 hanoi3num(n-1, origem, trabalho, destino) hanoi3num(n-1, trabalho, destino, origem) return rec3 def hanoi4num(n, origem, destino, trabalho1, trabalho2): global rec4 i...
rec3 = 0 rec4 = 0 def hanoi3num(n, origem, destino, trabalho): global rec3 rec3 += 1 if n == 1: return rec3 hanoi3num(n - 1, origem, trabalho, destino) hanoi3num(n - 1, trabalho, destino, origem) return rec3 def hanoi4num(n, origem, destino, trabalho1, trabalho2): global rec4 i...
class Solution: def strMultiply(self, s, char): bonus = 0 n = int(char) newStr = '' for i in range(len(s) - 1, -1, -1): m = int(s[i]) result = n * m + bonus newChar, bonus = str(result % 10), result // 10 newStr = newChar + newStr ...
class Solution: def str_multiply(self, s, char): bonus = 0 n = int(char) new_str = '' for i in range(len(s) - 1, -1, -1): m = int(s[i]) result = n * m + bonus (new_char, bonus) = (str(result % 10), result // 10) new_str = newChar + new...