content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
algorithm = "fourier" potential = {} potential["potential"] = "x/4" T = 8.5 dt = 0.01 eps = 0.1 f = 2.0 ngn = 4096 basis_size = 4 P = 1.0j Q = 1.0 S = 0.0 parameters = [ (P, Q, S, 1.0, -2.0) ] coefficients = [[(0, 1.0)]] write_nth = 2
algorithm = 'fourier' potential = {} potential['potential'] = 'x/4' t = 8.5 dt = 0.01 eps = 0.1 f = 2.0 ngn = 4096 basis_size = 4 p = 1j q = 1.0 s = 0.0 parameters = [(P, Q, S, 1.0, -2.0)] coefficients = [[(0, 1.0)]] write_nth = 2
class MessageKeyAttributes(object): def __init__(self, remote_jid, from_me, id, participant): self._remote_jid = remote_jid self._from_me = from_me self._id = id self._participant = participant def __str__(self): attrs = [] if self.remote_jid is not None: ...
class Messagekeyattributes(object): def __init__(self, remote_jid, from_me, id, participant): self._remote_jid = remote_jid self._from_me = from_me self._id = id self._participant = participant def __str__(self): attrs = [] if self.remote_jid is not None: ...
amt_torch, ifo_light, amt_max, ifo_count, ifo_dgree = int(input()), [False for a in range(360)], 0, 0, 0 def fill_light(ifo_start, ifo_stop): for each_spot in range(ifo_start, ifo_stop): ifo_light[each_spot] = True for each_torch in range(amt_torch): [ifo_start, ifo_stop] = [int(b) for b in input().split()...
(amt_torch, ifo_light, amt_max, ifo_count, ifo_dgree) = (int(input()), [False for a in range(360)], 0, 0, 0) def fill_light(ifo_start, ifo_stop): for each_spot in range(ifo_start, ifo_stop): ifo_light[each_spot] = True for each_torch in range(amt_torch): [ifo_start, ifo_stop] = [int(b) for b in input()...
# # PySNMP MIB module PHIHONG-PoE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PHIHONG-PoE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:31:30 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, value_size_constraint, single_value_constraint, constraints_intersection, value_range_constraint) ...
class InvalidRating(ValueError): pass class AuthRequired(TypeError): pass class CannotChangeVote(Exception): pass class CannotDeleteVote(Exception): pass class IPLimitReached(Exception): pass
class Invalidrating(ValueError): pass class Authrequired(TypeError): pass class Cannotchangevote(Exception): pass class Cannotdeletevote(Exception): pass class Iplimitreached(Exception): pass
''' oneflux.util For license information: see LICENSE file or headers in oneflux.__init__.py General utilities for oneflux @author: Gilberto Pastorello @contact: gzpastorello@lbl.gov @date: 2017-01-31 '''
""" oneflux.util For license information: see LICENSE file or headers in oneflux.__init__.py General utilities for oneflux @author: Gilberto Pastorello @contact: gzpastorello@lbl.gov @date: 2017-01-31 """
class ParserException(Exception): def __init__(self, message, filename=None, xml_exception=None, xml_element=None): Exception.__init__(self, message) self._message = message self._filename = filename self._xml_exception = xml_exception self._xml_element = xml_element @pr...
class Parserexception(Exception): def __init__(self, message, filename=None, xml_exception=None, xml_element=None): Exception.__init__(self, message) self._message = message self._filename = filename self._xml_exception = xml_exception self._xml_element = xml_element @p...
def main(filepath): ranges = [(int(x),int(y)-1) for x,y in [tuple(x.split(':')) for x in open(filepath,'r').read().replace(' ','').split('\n')]] delay = 0; caught = True severity = sum(depth*(scan_range+1) for depth, scan_range in ranges if depth%(2*scan_range) == 0) while caught: delay += 1...
def main(filepath): ranges = [(int(x), int(y) - 1) for (x, y) in [tuple(x.split(':')) for x in open(filepath, 'r').read().replace(' ', '').split('\n')]] delay = 0 caught = True severity = sum((depth * (scan_range + 1) for (depth, scan_range) in ranges if depth % (2 * scan_range) == 0)) while caught:...
# https://www.coursera.org/learn/competitive-programming-core-skills/lecture/wSCUn/defining-solution-set #input: n items with given weights w, w2, w3 and costs c1, c2 etc # largest total cost of thetems whose total weights doesnt exceed W. store= [] #defaultdict(int) def nested_fors(n,firstfor,x): global store...
store = [] def nested_fors(n, firstfor, x): global store w_total = 0 c_total = 0 n = 3 w = 5 w = [3, 2, 5] c = [2, 3, 6] if firstfor < n: for x[firstfor] in ['0', '1']: nested_fors(n, firstfor + 1, x) else: m = '' if x[0] == '1': w_tot...
def ScaleGlyph(glyph, scale, r): glyph['advanceWidth'] = r(glyph['advanceWidth'] * scale) if 'advanceHeight' in glyph: glyph['advanceHeight'] = r(glyph['advanceHeight'] * scale) glyph['verticalOrigin'] = r(glyph['verticalOrigin'] * scale) rm = [ 'stemH', 'stemV', 'hintMasks', 'contourMasks', 'instructions' ...
def scale_glyph(glyph, scale, r): glyph['advanceWidth'] = r(glyph['advanceWidth'] * scale) if 'advanceHeight' in glyph: glyph['advanceHeight'] = r(glyph['advanceHeight'] * scale) glyph['verticalOrigin'] = r(glyph['verticalOrigin'] * scale) rm = ['stemH', 'stemV', 'hintMasks', 'contourMasks',...
class Side: BUY = 'BUY' SELL = 'SELL' class TimeInForce: GTC = 'GTC' # Good Til Cancel (default value on BTSE) IOC = 'IOC' # Immediate or Cancel FIVEMIN = 'FIVEMIN' # 5 mins HOUR = 'HOUR' # 1 hour TWELVEHOUR = 'TWELVEHOUR' # 12 hours DAY = 'DAY' # 1 day WEEK = 'WEEK' # 1 wee...
class Side: buy = 'BUY' sell = 'SELL' class Timeinforce: gtc = 'GTC' ioc = 'IOC' fivemin = 'FIVEMIN' hour = 'HOUR' twelvehour = 'TWELVEHOUR' day = 'DAY' week = 'WEEK' month = 'MONTH' class Ordertype: limit = 'LIMIT' market = 'MARKET' oco = 'OCO' class Txtype: l...
dadosPessoas = [] dadoTemporario = [] c = maiorPeso = menorPeso = 0 while True: dadoTemporario.append(str(input('Nome: '))) dadoTemporario.append(float(input('Peso(KG): '))) dadosPessoas.append(dadoTemporario[:]) if c == 0: # Posso usar len(dadoTemporario) para fazer o contador maiorPeso = dado...
dados_pessoas = [] dado_temporario = [] c = maior_peso = menor_peso = 0 while True: dadoTemporario.append(str(input('Nome: '))) dadoTemporario.append(float(input('Peso(KG): '))) dadosPessoas.append(dadoTemporario[:]) if c == 0: maior_peso = dadoTemporario[1] menor_peso = dadoTemporario[1...
string = input() results = [] for i, char in enumerate(string): if i != 0 and char.isupper(): results.append('_') results.append(char.lower()) print("".join(results))
string = input() results = [] for (i, char) in enumerate(string): if i != 0 and char.isupper(): results.append('_') results.append(char.lower()) print(''.join(results))
#!/usr/bin/env python # Copyright Contributors to the Open Shading Language project. # SPDX-License-Identifier: BSD-3-Clause # https://github.com/imageworks/OpenShadingLanguage command = testshade("--groupoutputs -od half -o a a.exr -o b b.exr -o c c.exr -g 64 64 test") outputs = [ "a.exr", "b.exr", "c.exr", "out.txt...
command = testshade('--groupoutputs -od half -o a a.exr -o b b.exr -o c c.exr -g 64 64 test') outputs = ['a.exr', 'b.exr', 'c.exr', 'out.txt']
def AssignFare(c,a,d): if d<500: t_fare=(a*200)+(c*(200/2)) elif (d<1000) and (d>=500): t_fare=(a*300)+(c*(300/2)) else: t_fare=(a*500)+(c*(500/2)) return t_fare child=int(input("enter the number of children: ")) adult=int(input("enter the number of adults: ")) distan...
def assign_fare(c, a, d): if d < 500: t_fare = a * 200 + c * (200 / 2) elif d < 1000 and d >= 500: t_fare = a * 300 + c * (300 / 2) else: t_fare = a * 500 + c * (500 / 2) return t_fare child = int(input('enter the number of children: ')) adult = int(input('enter the number of adu...
def insertion_sort(array): #function to sort array using insertion sort comparison=0 shift=0 for i in range(1,len(array)): j=i-1 val=array[i] while(j>=0 and val<array[j]): shift+=1 comparison+=1 array[j+1]=array[j] array[j]=val ...
def insertion_sort(array): comparison = 0 shift = 0 for i in range(1, len(array)): j = i - 1 val = array[i] while j >= 0 and val < array[j]: shift += 1 comparison += 1 array[j + 1] = array[j] array[j] = val j -= 1 co...
# Some more if statements banned_users = ['andrew','carolina','david'] user = 'marie' if user not in banned_users: print(user.title()+", you can post a response if you wish.") car = 'subaru' print("Is car == 'subaru'? I predict True") print(car == 'subaru') print("Is car == 'audi'? I predict false") print(car == '...
banned_users = ['andrew', 'carolina', 'david'] user = 'marie' if user not in banned_users: print(user.title() + ', you can post a response if you wish.') car = 'subaru' print("Is car == 'subaru'? I predict True") print(car == 'subaru') print("Is car == 'audi'? I predict false") print(car == 'audi') age = 20 if age ...
def extract_pos(doc, pos, return_list = True, lower_case = True): tokens = [t.text for t in doc if t.pos_ == pos] if lower_case == True: tokens = [t.lower() for t in tokens] if return_list == False: tokens = ', '.join(tokens) return tokens
def extract_pos(doc, pos, return_list=True, lower_case=True): tokens = [t.text for t in doc if t.pos_ == pos] if lower_case == True: tokens = [t.lower() for t in tokens] if return_list == False: tokens = ', '.join(tokens) return tokens
class Queue: def __init__(self): self.items=[] def enqueue(self,item): self.items.append(item) def dequeue(self): return self.items.pop(0) def is_empty(self): if self.items==[]: return True return False if __name__=="__main__": q=Queue() q.en...
class Queue: def __init__(self): self.items = [] def enqueue(self, item): self.items.append(item) def dequeue(self): return self.items.pop(0) def is_empty(self): if self.items == []: return True return False if __name__ == '__main__': q = queue...
async def execute(client, **kwargs): print("Please wait...") await client.logout() print("Client sucsessfully logged out") return 1 if __name__ == "__main__": pass
async def execute(client, **kwargs): print('Please wait...') await client.logout() print('Client sucsessfully logged out') return 1 if __name__ == '__main__': pass
suffix = "ack" praefixe = "JKLMNOPQ" for praefix in praefixe: if praefix == "O" or praefix == "Q": print(praefix + "u" + suffix) else: print(praefix + suffix)
suffix = 'ack' praefixe = 'JKLMNOPQ' for praefix in praefixe: if praefix == 'O' or praefix == 'Q': print(praefix + 'u' + suffix) else: print(praefix + suffix)
def fatorial(p1): f = 1 indice = p1 while indice >= 1: f *= indice indice -= 1 return f def dobro(p1): return p1 * 2 def triplo(p1): return p1 * 3
def fatorial(p1): f = 1 indice = p1 while indice >= 1: f *= indice indice -= 1 return f def dobro(p1): return p1 * 2 def triplo(p1): return p1 * 3
# This program says hello world and asks for my name. print('Hello, world!') print('what is your name?') # ask for the name my_Name = input() print('It is nice to meet you, '+ my_Name) print('The length of your name is:') print(len(my_Name)) print(len(' ')) print('What is your age?') # ask for the age my_Age = inpu...
print('Hello, world!') print('what is your name?') my__name = input() print('It is nice to meet you, ' + my_Name) print('The length of your name is:') print(len(my_Name)) print(len(' ')) print('What is your age?') my__age = input() print('You will be ' + str(int(my_Age) + 1) + ' in a year')
class Failsafe: ''' Catches I/O errors. ''' def __init__(self, func): self.function = func def __call__(self, *args): try: self.function(*args) except IOError: print('An I/O error was caught when opening file "{}"'.format(args[0])) ...
class Failsafe: """ Catches I/O errors. """ def __init__(self, func): self.function = func def __call__(self, *args): try: self.function(*args) except IOError: print('An I/O error was caught when opening file "{}"'.format(args[0])) @Failsafe def ris...
# TIMEBOMB: report me a = 1 # TIMEBOMB (jsmith): report me # TIMEBOMB: do not report me (pragma). # no-check-fixmes # TIMEBOMB(jsmith - 2020-04-25): report me a = "TIMEBOMB" # do not report me (within a string) a = "TIMEBOMB" # do not report me (within a string) # TIMEBOMB - FEWTURE-BOOM: report me
a = 1 a = 'TIMEBOMB' a = 'TIMEBOMB'
class Node: def __init__(self, x: int, next: "Node" = None, random: "Node" = None): self.val = int(x) self.next = next self.random = random class Solution: def copyRandomList(self, head: "Node") -> "Node": if not head: return None node = head new_nod...
class Node: def __init__(self, x: int, next: 'Node'=None, random: 'Node'=None): self.val = int(x) self.next = next self.random = random class Solution: def copy_random_list(self, head: 'Node') -> 'Node': if not head: return None node = head new_node...
SELECT_NOTICES_FOR_RE_PACKAGE_AND_RESET_STATUS_TASK_ID = "select_notices_for_re_package_and_reset_status" TRIGGER_WORKER_FOR_PACKAGE_BRANCH_TASK_ID = "trigger_worker_for_package_branch" def test_selector_repackage_process_orchestrator(dag_bag): assert dag_bag.import_errors == {} dag = dag_bag.get_dag(dag_id="...
select_notices_for_re_package_and_reset_status_task_id = 'select_notices_for_re_package_and_reset_status' trigger_worker_for_package_branch_task_id = 'trigger_worker_for_package_branch' def test_selector_repackage_process_orchestrator(dag_bag): assert dag_bag.import_errors == {} dag = dag_bag.get_dag(dag_id='s...
def taylor(val,precision): next = 1 total = 0 for i in range(0,precision): posorneg = (-1) ** i top = val ** (2 * i + 1 ) * posorneg final = 1 for i in range(next): final = final * (next -i) next +=2 total += top/final print(top,final) ...
def taylor(val, precision): next = 1 total = 0 for i in range(0, precision): posorneg = (-1) ** i top = val ** (2 * i + 1) * posorneg final = 1 for i in range(next): final = final * (next - i) next += 2 total += top / final print(top, final...
class MathUtils: @staticmethod def average(a, b): return (a + b)/2 if __name__ == '__main__': print(MathUtils.average(1, 2))
class Mathutils: @staticmethod def average(a, b): return (a + b) / 2 if __name__ == '__main__': print(MathUtils.average(1, 2))
# Copyright (c) 2018, Xilinx, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of con...
__author__ = 'Peter Ogden' __copyright__ = 'Copyright 2018, Xilinx' __email__ = 'pynq_support@xilinx.com' _dac_adp = [('BlockAvailable', 'C_DAC_Slice{}{}_Enable', 'int'), ('InvSyncEnable', 'C_DAC_Invsinc_Ctrl{}{}', 'int'), ('MixMode', 'C_DAC_Mixer_Mode{}{}', 'int'), ('DecoderMode', 'C_DAC_Decoder_Mode{}{}', 'int')] _da...
# SD-WAN vManager username and password vManager_USERNAME = "devnetuser" vManager_PASSWORD = "Cisco123!" # DNA Center username and password DNAC_USER = "devnetuser" DNAC_PASSWORD = "Cisco123!" # Meraki API key MERAKI_API_KEY = "6bec40cf957de430a6f1f2baa056b99a4fac9ea0" # E-mail username and password EMAIL_USERNAME =...
v_manager_username = 'devnetuser' v_manager_password = 'Cisco123!' dnac_user = 'devnetuser' dnac_password = 'Cisco123!' meraki_api_key = '6bec40cf957de430a6f1f2baa056b99a4fac9ea0' email_username = 'email_username' email_password = 'email_password' webex_teams_space = 'webex_team_space_more_than_70_characters' webex_tea...
class Solution: def searchInsert(self, nums: List[int], target: int) -> int: def divide_conquer(low, high, nums, target): mid = int(low+high)/2 if nums[mid] == target: return mid elif nums[mid] < target: divide_conquer(mid+1, high, nums, ta...
class Solution: def search_insert(self, nums: List[int], target: int) -> int: def divide_conquer(low, high, nums, target): mid = int(low + high) / 2 if nums[mid] == target: return mid elif nums[mid] < target: divide_conquer(mid + 1, high,...
class TestLogicReset: def __init__(self,ctx): self.ctx_=ctx def advance(self, tms, tdi): if ( tms ): return self else: return self.ctx_.RunTestIdle class RunTestIdle: def __init__(self,ctx): self.ctx_=ctx def advance(self, tms, tdi): if ( tms ): return self.ctx_.SelectDR...
class Testlogicreset: def __init__(self, ctx): self.ctx_ = ctx def advance(self, tms, tdi): if tms: return self else: return self.ctx_.RunTestIdle class Runtestidle: def __init__(self, ctx): self.ctx_ = ctx def advance(self, tms, tdi): ...
class Node: def __init__(self, doc): self.doc = doc
class Node: def __init__(self, doc): self.doc = doc
class Images: @staticmethod def save(data,filename): result="" for i in data: result+=chr(i); saveBytes(filename,result) @staticmethod def visualize(data,height,width,offsetH=0,offsetW=0,scale=1): x=0 y=0 for elem in data: pixel=ord...
class Images: @staticmethod def save(data, filename): result = '' for i in data: result += chr(i) save_bytes(filename, result) @staticmethod def visualize(data, height, width, offsetH=0, offsetW=0, scale=1): x = 0 y = 0 for elem in data: ...
class printerClass(): def print_table(self, data, header): data = list(data) MaxLength = 0 data.insert(0, header) for i in range(0, len(data)): for x in data[i]: MaxLength = len(str(x)) if MaxLength < len(str(x)) else MaxLength print("-" * MaxL...
class Printerclass: def print_table(self, data, header): data = list(data) max_length = 0 data.insert(0, header) for i in range(0, len(data)): for x in data[i]: max_length = len(str(x)) if MaxLength < len(str(x)) else MaxLength print('-' * MaxLeng...
class Solution: def kthSmallestPrimeFraction(self, A: List[int], K: int) -> List[int]: lo, hi = 0, 1 n = len(A) while True: mid = (lo + hi) / 2 idxes = [bisect.bisect(A, num / mid) for num in A] cnt = sum(n - idx for idx in idxes) if cnt < K: ...
class Solution: def kth_smallest_prime_fraction(self, A: List[int], K: int) -> List[int]: (lo, hi) = (0, 1) n = len(A) while True: mid = (lo + hi) / 2 idxes = [bisect.bisect(A, num / mid) for num in A] cnt = sum((n - idx for idx in idxes)) if ...
# Search directories (list is searched downward until file is found) # cwd is searched first by default # Set to get resolver messages through stderr # (helpful for observing and debugging path resolution) # setting _more lists every path resolution attempt resolver_debug = False resolver_debug_more = False fhs_dirs ...
resolver_debug = False resolver_debug_more = False fhs_dirs = {'dld': ['./dld/', '~/dml/dld/', '/usr/local/share/dml/dld/', '/usr/share/dml/dld/', '/etc/dml/dld/'], 'dss': ['./dss/', '~/dml/dss/', '/usr/local/share/dml/dss/', '/usr/share/dml/dss/', '/etc/dml/dss/']} windows_dirs = {'dld': [], 'dss': []}
class Graph: def __init__(self, vertexes: int) -> None: self.vertexes = vertexes self.graph = [[float("inf") for _ in range(self.vertexes)] for _ in range(self.vertexes)] def connect(self, u: int, v: int, w: int) -> None: self.graph[u][v] = w def show(self, matrix: list) -> None: ...
class Graph: def __init__(self, vertexes: int) -> None: self.vertexes = vertexes self.graph = [[float('inf') for _ in range(self.vertexes)] for _ in range(self.vertexes)] def connect(self, u: int, v: int, w: int) -> None: self.graph[u][v] = w def show(self, matrix: list) -> None: ...
# Runtime: 40 ms, faster than 91.18% of Python3 online submissions for Find Peak Element. # Memory Usage: 13.9 MB, less than 5.88% of Python3 online submissions for Find Peak Element. class Solution: def findPeakElement(self, nums: List[int]) -> int: left, right = 0, len(nums) - 1 while left < righ...
class Solution: def find_peak_element(self, nums: List[int]) -> int: (left, right) = (0, len(nums) - 1) while left < right: mid = (left + right) // 2 if nums[mid] > nums[mid - 1] and nums[mid] > nums[mid + 1]: return mid if nums[mid] < nums[mid + ...
rows, cols = [int(x) for x in input().split()] matrix = [[x for x in input().split()] for _ in range(rows)] squares_found = 0 for row in range(rows - 1): for col in range(cols - 1): if matrix[row][col] == \ matrix[row][col + 1] == \ matrix[row + 1][col] == \ ...
(rows, cols) = [int(x) for x in input().split()] matrix = [[x for x in input().split()] for _ in range(rows)] squares_found = 0 for row in range(rows - 1): for col in range(cols - 1): if matrix[row][col] == matrix[row][col + 1] == matrix[row + 1][col] == matrix[row + 1][col + 1]: squares_found +...
str_year = input("what is your birth year:") year = int(str_year) age = 2020-year-1 print(f"hello, your age is {age}")
str_year = input('what is your birth year:') year = int(str_year) age = 2020 - year - 1 print(f'hello, your age is {age}')
# -*- coding: utf-8 -*- description = 'Detector data acquisition setup' group = 'lowlevel' display_order = 25 includes = ['counter'] excludes = ['virtual_daq'] sysconfig = dict( datasinks = ['kwsformat', 'yamlformat', 'binaryformat', 'livesink'], ) tango_base = 'tango://phys.kws2.frm2:10000/kws2/' devices = di...
description = 'Detector data acquisition setup' group = 'lowlevel' display_order = 25 includes = ['counter'] excludes = ['virtual_daq'] sysconfig = dict(datasinks=['kwsformat', 'yamlformat', 'binaryformat', 'livesink']) tango_base = 'tango://phys.kws2.frm2:10000/kws2/' devices = dict(kwsformat=device('nicos_mlz.kws2.de...
#!/usr/bin/env python3 with open('27985_B.txt') as f: nums = list([int(x) for x in f.readlines()][1:]) r2, r7, r14 = 0, 0, 0 for num in nums: if num % 14 == 0: r14 = max(r14, num) if num % 2 == 0: r2 = max(r2, num) if num % 7 == 0: r7 = max(r7, num) print(max(r2 * r7, r14 * max(nums)))
with open('27985_B.txt') as f: nums = list([int(x) for x in f.readlines()][1:]) (r2, r7, r14) = (0, 0, 0) for num in nums: if num % 14 == 0: r14 = max(r14, num) if num % 2 == 0: r2 = max(r2, num) if num % 7 == 0: r7 = max(r7, num) print(max(r2 * r7, r14 * max(nums)))
# Tai Sakuma <tai.sakuma@gmail.com> ##__________________________________________________________________|| def create_files_start_length_list( files, func_get_nevents_in_file=None, max_events=-1, max_events_per_run=-1, max_files=-1, max_files_per_run=1): files = _apply_max_files(files, max...
def create_files_start_length_list(files, func_get_nevents_in_file=None, max_events=-1, max_events_per_run=-1, max_files=-1, max_files_per_run=1): files = _apply_max_files(files, max_files) if max_events == 0 or max_events_per_run == 0: return [] if max_events < 0 and max_events_per_run < 0: ...
# time complexity O(n^2) def find3Numbers(A, arr_size, sum): A.sort() # Now fix the first element # one by one and find the # other two elements for i in range(0, arr_size-2): # To find the other two elements, # start two index variables from # two corners of the a...
def find3_numbers(A, arr_size, sum): A.sort() for i in range(0, arr_size - 2): l = i + 1 r = arr_size - 1 while l < r: if A[i] + A[l] + A[r] == sum: print('Triplet is', A[i], ', ', A[l], ', ', A[r]) return True elif A[i] + A[l] + A[...
r = input() s = input() a = r.split(",") b = s.split(",") count = 0 k = 0 for i in range(len(b)): count = count + int(b[k]) k += 1 for j in a: n = j.split(":") if count == int(n[0]): count = int(n[1]) if count>= 100: print("Yes"...
r = input() s = input() a = r.split(',') b = s.split(',') count = 0 k = 0 for i in range(len(b)): count = count + int(b[k]) k += 1 for j in a: n = j.split(':') if count == int(n[0]): count = int(n[1]) if count >= 100: print('Yes', end='') else: print('No', end='')
# Get a list of space-separated input ints. Multiply a new input nums = input().split() multiplier = int(input()) result = [int(item) * multiplier for item in nums] for item in result: print(item, end = ' ') print()
nums = input().split() multiplier = int(input()) result = [int(item) * multiplier for item in nums] for item in result: print(item, end=' ') print()
class Solution: def validTicTacToe(self, board: List[str]) -> bool: def win( c ): col = [0]*3 row = [0]*3 right = 0 left = 0 total = 0 for i in range(3): for j in range(3): ...
class Solution: def valid_tic_tac_toe(self, board: List[str]) -> bool: def win(c): col = [0] * 3 row = [0] * 3 right = 0 left = 0 total = 0 for i in range(3): for j in range(3): if board[i][j] == c:...
def square(number): answer = number * number return answer # note: this is not an eror, return an answer # main code starts here : useNumber = input("Enter a number: ") useNumber = float(useNumber) # convert to float numberSquarred = square(useNumber) # call the function and save the result print("The sequ...
def square(number): answer = number * number return answer use_number = input('Enter a number: ') use_number = float(useNumber) number_squarred = square(useNumber) print('The sequare of your number is', numberSquarred)
class Constants: def __init__(self): self.D20 = 20 self.D4 = 4 self.D6 = 6 self.D8 = 8 self.D10 = 10 self.D12 = 12 self.D100 = 100 self.CRITICALROLL = 20 self.CRITICAL = 100 self.FAILROLL = 1 self.FAIL = -100 self.ITEMAT...
class Constants: def __init__(self): self.D20 = 20 self.D4 = 4 self.D6 = 6 self.D8 = 8 self.D10 = 10 self.D12 = 12 self.D100 = 100 self.CRITICALROLL = 20 self.CRITICAL = 100 self.FAILROLL = 1 self.FAIL = -100 self.ITEMA...
'''This is a custom layout for the WordClock widget. Custom layouts can be created for the widget by creating a new file in the "qtile_extras.resources.wordclock" folder. Each layout must have the following variables: LAYOUT: The grid layout. Must be a single string. MAP: The mappin...
"""This is a custom layout for the WordClock widget. Custom layouts can be created for the widget by creating a new file in the "qtile_extras.resources.wordclock" folder. Each layout must have the following variables: LAYOUT: The grid layout. Must be a single string. MAP: The mappin...
dummy_dict = {"Yes": 1, "No": 0} internet_dict = {"No": 0, "No internet service": 1, "Yes": 2} train_yesno_cols = [ "Partner", "Dependents", "PhoneService", "PaperlessBilling", "Churn", ] inference_yesno_cols = ["Partner", "Dependents", "PhoneService", "PaperlessBilling"] internet_cols = [ "Onli...
dummy_dict = {'Yes': 1, 'No': 0} internet_dict = {'No': 0, 'No internet service': 1, 'Yes': 2} train_yesno_cols = ['Partner', 'Dependents', 'PhoneService', 'PaperlessBilling', 'Churn'] inference_yesno_cols = ['Partner', 'Dependents', 'PhoneService', 'PaperlessBilling'] internet_cols = ['OnlineSecurity', 'OnlineBackup',...
expected_output = { "instance": { "65109": { "areas": { "0.0.0.8": { "interfaces": { "Loopback0": { "ip_address": "10.169.197.254/32", "cost": 1, "state...
expected_output = {'instance': {'65109': {'areas': {'0.0.0.8': {'interfaces': {'Loopback0': {'ip_address': '10.169.197.254/32', 'cost': 1, 'state': 'LOOP', 'nbrs_full': 0, 'nbrs_count': 0}, 'GigabitEthernet4': {'ip_address': '10.169.197.98/30', 'cost': 1000, 'state': 'P2P', 'nbrs_full': 1, 'nbrs_count': 1}, 'GigabitEth...
datasetFile = open("datasets/rosalind_ba1d.txt", "r") pattern = datasetFile.readline().strip() genome = datasetFile.readline().strip() def findInText(pattern, genome): indices = [] for i in range(len(genome) - len(pattern) + 1): if genome[i:i+len(pattern)] == pattern: indices.append(i) ...
dataset_file = open('datasets/rosalind_ba1d.txt', 'r') pattern = datasetFile.readline().strip() genome = datasetFile.readline().strip() def find_in_text(pattern, genome): indices = [] for i in range(len(genome) - len(pattern) + 1): if genome[i:i + len(pattern)] == pattern: indices.append(i)...
#f row=0 while row<9: col =0 while col<10: if (col==4 and row!=0)or (row==0 and col==5)or (row==0 and col==6)or (row==0 and col==7)or (row==4): print("*",end=" ") else: print(" ",end=" ") col +=1 row +=1 print()
row = 0 while row < 9: col = 0 while col < 10: if col == 4 and row != 0 or (row == 0 and col == 5) or (row == 0 and col == 6) or (row == 0 and col == 7) or (row == 4): print('*', end=' ') else: print(' ', end=' ') col += 1 row += 1 print()
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. default_sim_settings = { # settings shared by example.py and benchmark.py "max_frames": 1000, "width": 640, "height": 480, ...
default_sim_settings = {'max_frames': 1000, 'width': 640, 'height': 480, 'scene': 'test.glb', 'default_agent': 0, 'sensor_height': 1.5, 'color_sensor': True, 'semantic_sensor': False, 'depth_sensor': False, 'seed': 1, 'silent': False, 'save_png': False, 'print_semantic_scene': False, 'print_semantic_mask_stats': False,...
class AssertRaises(object): def __init__(self, expected): self.expected = expected def __enter__(self): return self def __exit__(self, exc_type, exc_value, tb): if exc_type is None: try: exc_name = self.expected.__name__ except AttributeErro...
class Assertraises(object): def __init__(self, expected): self.expected = expected def __enter__(self): return self def __exit__(self, exc_type, exc_value, tb): if exc_type is None: try: exc_name = self.expected.__name__ except AttributeErro...
# Demo Python Dictionaries - Dictionary ''' Dictionary A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values. Loop Through a Dictionary You can loop through a dictionary by using a for loop. When looping through a ...
""" Dictionary A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values. Loop Through a Dictionary You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the key...
#!/usr/bin/env python3.10 #FILE = 'test_0.txt' # sol: 1384 #FILE = 'test.txt' # sol: 4140 FILE='input.txt' # sol: 3647 def parse_input(file): lines = [] with open(file, 'r') as f: for line in f: lines.append(line.rstrip()) #print(f'lines: {lines}') return lines def to_string(n)...
file = 'input.txt' def parse_input(file): lines = [] with open(file, 'r') as f: for line in f: lines.append(line.rstrip()) return lines def to_string(n): if isinstance(n, int): return str(n) string = '[' for i in range(len(n)): string += to_string(n[i]) ...
__author__ = 'rolandh' INFORMATION = 0 OK = 1 WARNING = 2 ERROR = 3 CRITICAL = 4 INTERACTION = 5 STATUSCODE = ["INFORMATION", "OK", "WARNING", "ERROR", "CRITICAL", "INTERACTION"]
__author__ = 'rolandh' information = 0 ok = 1 warning = 2 error = 3 critical = 4 interaction = 5 statuscode = ['INFORMATION', 'OK', 'WARNING', 'ERROR', 'CRITICAL', 'INTERACTION']
INF = 10**9 class Edge: def __init__(self, _source, _target, _weight): self.source = _source self.target = _target self.weight = _weight def BellmanFord(s): dist = [INF] * n dist[s] = 0 for i in range(n - 1): for edge in graph: u, v, w = edge.source, edge.target, edge.weight if dist[u] != INF and d...
inf = 10 ** 9 class Edge: def __init__(self, _source, _target, _weight): self.source = _source self.target = _target self.weight = _weight def bellman_ford(s): dist = [INF] * n dist[s] = 0 for i in range(n - 1): for edge in graph: (u, v, w) = (edge.source, ...
def generate_rule_nums(): base1 = 3 base2 = 5 my_sum = 0 my_max = 10000 for i in range(1, 10000): if i%base1 == 0 or i%base2 == 0: my_sum += i print(my_sum) generate_rule_nums()
def generate_rule_nums(): base1 = 3 base2 = 5 my_sum = 0 my_max = 10000 for i in range(1, 10000): if i % base1 == 0 or i % base2 == 0: my_sum += i print(my_sum) generate_rule_nums()
class Solution: def isAlienSorted(self, words, order): for i in range(20): tmp = [-1 if len(word) <= i else order.index(word[i]) for word in words] if tmp != sorted(tmp): return False if tmp == sorted(tmp) and len(tmp) == len(set(tmp)): return True return True
class Solution: def is_alien_sorted(self, words, order): for i in range(20): tmp = [-1 if len(word) <= i else order.index(word[i]) for word in words] if tmp != sorted(tmp): return False if tmp == sorted(tmp) and len(tmp) == len(set(tmp)): ...
#!/usr/bin/python #coding:utf8 def GC_content(s): ''' Calculate GC content of DNA. ''' s = s.upper() G_content = s.count('G') C_content = s.count('C') ratio = (G_content + C_content) / float(len(s)) return format(ratio, '.2%') def r_complement(s): s = s.upper() d...
def gc_content(s): """ Calculate GC content of DNA. """ s = s.upper() g_content = s.count('G') c_content = s.count('C') ratio = (G_content + C_content) / float(len(s)) return format(ratio, '.2%') def r_complement(s): s = s.upper() dict = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G'} ...
# Insertion sorting Algorithm # @python def insertion_sort(list_): for x in range(1, len(list_)): cursor = list_[x] pos = x while pos > 0 and list_[pos - 1] > cursor: list_[pos] = list_[pos - 1] pos = pos - 1 list_[pos] = cursor return list_ array = [1...
def insertion_sort(list_): for x in range(1, len(list_)): cursor = list_[x] pos = x while pos > 0 and list_[pos - 1] > cursor: list_[pos] = list_[pos - 1] pos = pos - 1 list_[pos] = cursor return list_ array = [15, 2, 4, 50, 30, 2, 0, 1, 4] sorted = insert...
s={'A',"A",99,96.5} print(s) #{96.5, 99, 'A'} print(type(s)) #<class 'set'> #print(s[2]) #'set' object does not support indexing #s[0]="ASIT" #'set' object does not support item assignment print(id(s)) s.add("ASIT") print(s) print(id(s))
s = {'A', 'A', 99, 96.5} print(s) print(type(s)) print(id(s)) s.add('ASIT') print(s) print(id(s))
class Solution: def rotate(self, nums, k): k %= len(nums) self.reverseArray(nums, 0, len(nums)-1) self.reverseArray(nums, 0, k-1) self.reverseArray(nums, k, len(nums)-1) def reverseArray(self, nums, start, end): while start < end: nums[start], nums[end] = num...
class Solution: def rotate(self, nums, k): k %= len(nums) self.reverseArray(nums, 0, len(nums) - 1) self.reverseArray(nums, 0, k - 1) self.reverseArray(nums, k, len(nums) - 1) def reverse_array(self, nums, start, end): while start < end: (nums[start], nums[e...
def add_native_methods(clazz): def nOpen__int__(a0, a1): raise NotImplementedError() def nClose__long__(a0, a1): raise NotImplementedError() def nGetPortCount__long__(a0, a1): raise NotImplementedError() def nGetPortType__long__int__(a0, a1, a2): raise NotImplementedEr...
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_get_port_count__long__(a0, a1): raise not_implemented_error() def n_get_port_type__long__int__(a0, a1, a2): raise n...
class NetworkSegmentInterface: def build_network_segment(self, input_nodes): raise Exception("Not implemented error")
class Networksegmentinterface: def build_network_segment(self, input_nodes): raise exception('Not implemented error')
# https://stackoverflow.com/questions/3192095/where-exactly-the-singleton-pattern-is-used-in-real-application # https://dzone.com/articles/design-patterns-singleton # https://www.tutorialspoint.com/python_design_patterns/python_design_patterns_singleton.htm # https://code.google.com/archive/p/google-singleton-detector/...
class Singleton: __instance = None def __init__(self): if Singleton.__instance != None: raise exception('This class is a singleton!') else: Singleton.__instance = self def get_instance(self): if Singleton.__instance == None: Singleton.__instance ...
def rek(n): if n == 1: return 1 if n == 0: return 1 return 4*rek(n-1)+5 print(rek(2)) print(rek(23))
def rek(n): if n == 1: return 1 if n == 0: return 1 return 4 * rek(n - 1) + 5 print(rek(2)) print(rek(23))
dnas = [ ['pX3Eo\\]', 38, 146, 1069.71, 38, 26, -27.55, {'qty_to_risk': 7, 'target_pnl': 253, 'stop': 35, 'donchlen': 78, 'treshold': 92, 'ema_fast': 14, 'ema_slow': 40}], ['k[3Eo\\]', 38, 146, 1030.13, 38, 26, -27.55, {'qty_to_risk': 7, 'target_pnl': 267, 'stop': 35, 'donchlen': 78, 'treshold': 92, 'ema_fast': 14, 'em...
dnas = [['pX3Eo\\]', 38, 146, 1069.71, 38, 26, -27.55, {'qty_to_risk': 7, 'target_pnl': 253, 'stop': 35, 'donchlen': 78, 'treshold': 92, 'ema_fast': 14, 'ema_slow': 40}], ['k[3Eo\\]', 38, 146, 1030.13, 38, 26, -27.55, {'qty_to_risk': 7, 'target_pnl': 267, 'stop': 35, 'donchlen': 78, 'treshold': 92, 'ema_fast': 14, 'ema...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2018 Yeolar # class DAGNode(object): def __init__(self, name): self.name = name self.nexts = set() self.prevs = set() self.self_dep = False self.done = False class DAG(object): def __init__(self): sel...
class Dagnode(object): def __init__(self, name): self.name = name self.nexts = set() self.prevs = set() self.self_dep = False self.done = False class Dag(object): def __init__(self): self.nodes = [] self.index = {} self.cycle_dep = False de...
# -*- coding: utf-8 -*- description = 'TOFTOF radial collimator' group = 'optional' tango_base = 'tango://tofhw.toftof.frm2:10000/toftof/' devices = dict( rc_onoff = device('nicos.devices.tango.NamedDigitalOutput', description = 'Activates radial collimator', tangodevice = tango_base + 'rc/_rc_o...
description = 'TOFTOF radial collimator' group = 'optional' tango_base = 'tango://tofhw.toftof.frm2:10000/toftof/' devices = dict(rc_onoff=device('nicos.devices.tango.NamedDigitalOutput', description='Activates radial collimator', tangodevice=tango_base + 'rc/_rc_onoff', mapping={'on': 1, 'off': 0}), rc_motor=device('n...
def series_ele(n): pattern = [] for i in range(1,n): next_element = (i**3) + i*2 pattern.append(next_element) return pattern if __name__ == "__main__": input_number = int(input("Enter a number upto which you want to print the patter: ")) print(series_ele(input_number))
def series_ele(n): pattern = [] for i in range(1, n): next_element = i ** 3 + i * 2 pattern.append(next_element) return pattern if __name__ == '__main__': input_number = int(input('Enter a number upto which you want to print the patter: ')) print(series_ele(input_number))
{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Dependencies and Setup\n", "from bs4 import BeautifulSoup\n", "from splinter import Browser\n", "import pandas as pd\n", "import datetime as dt\n", "\n", "\n", "# ...
{'cells': [{'cell_type': 'code', 'execution_count': null, 'metadata': {}, 'outputs': [], 'source': ['# Dependencies and Setup\n', 'from bs4 import BeautifulSoup\n', 'from splinter import Browser\n', 'import pandas as pd\n', 'import datetime as dt\n', '\n', '\n', '# Set Executable Path & Initialize Chrome Browser\n', 'e...
CORS_ALLOW_ORIGINS = '*' # fixme! CORS_ALLOW_METHODS = ['GET', 'POST', 'PATH', 'DELETE'] CORS_ALLOW_HEADERS = ['*'] # fixme! DATABASE = { 'uri': 'mongodb://localhost:27017', 'max_pool_size': 10, 'db_name': 'uaberdb', }
cors_allow_origins = '*' cors_allow_methods = ['GET', 'POST', 'PATH', 'DELETE'] cors_allow_headers = ['*'] database = {'uri': 'mongodb://localhost:27017', 'max_pool_size': 10, 'db_name': 'uaberdb'}
lar = 0 sm = 0.0 while True : st = input ('Enter a number: ') if st == 'done': break try: ft = int(st) except: print("Invalid input") continue print(ft) num = num + 1 tot = tot + ft print('All Done') print(tot,num,tot/num)
lar = 0 sm = 0.0 while True: st = input('Enter a number: ') if st == 'done': break try: ft = int(st) except: print('Invalid input') continue print(ft) num = num + 1 tot = tot + ft print('All Done') print(tot, num, tot / num)
class StateChange: VFX = 'vfx_state' VFX_STATE = 'vfx_state_state' AUDIO_STATE = 'audio_state' AUDIO_EFFECT_STATE = 'audio_effect_state' AUTONOMY_MODIFIERS = 'autonomy_modifiers' AWARENESS = 'awareness' BROADCASTER = 'broadcaster' ENVIRONMENT_SCORE = 'environment_score' PAINTING_REV...
class Statechange: vfx = 'vfx_state' vfx_state = 'vfx_state_state' audio_state = 'audio_state' audio_effect_state = 'audio_effect_state' autonomy_modifiers = 'autonomy_modifiers' awareness = 'awareness' broadcaster = 'broadcaster' environment_score = 'environment_score' painting_reve...
n = int(input()) a = list(map(int, input().split())) histogram = {} res = 0 for i in range(n-1): for j in range(i+1, n): s = a[i] + a[j] if s not in histogram: histogram[s] = 0 histogram[s] += 1 res = max(res, histogram[s]) print(res)
n = int(input()) a = list(map(int, input().split())) histogram = {} res = 0 for i in range(n - 1): for j in range(i + 1, n): s = a[i] + a[j] if s not in histogram: histogram[s] = 0 histogram[s] += 1 res = max(res, histogram[s]) print(res)
class Solution: def restoreString(self, s: str, indices: List[int]) -> str: result = [None] * len(s) for i, j in enumerate(indices): result[j] = s[i] return "".join(result)
class Solution: def restore_string(self, s: str, indices: List[int]) -> str: result = [None] * len(s) for (i, j) in enumerate(indices): result[j] = s[i] return ''.join(result)
class Dog: name=None legs=None age=None gender=None isCute=None
class Dog: name = None legs = None age = None gender = None is_cute = None
''' Have the function SimpleSymbols(str) take the str parameter being passed and determine if it is an acceptable sequence by either returning the string true or false. The str parameter will be composed of + and = symbols with several letters between them (ie. ++d+===+c++==a) and for the string to be true each let...
""" Have the function SimpleSymbols(str) take the str parameter being passed and determine if it is an acceptable sequence by either returning the string true or false. The str parameter will be composed of + and = symbols with several letters between them (ie. ++d+===+c++==a) and for the string to be true each letter...
# from linked_list import LinkedList def ll_merge(arg2, arg1): if arg2._len <= 0 and arg1._len <= 0: return False if arg2.head is None: return arg1 if arg1.head is None: return arg2 if True: ptr_left, ptr_right = arg1.head, arg2.head while ptr_right is not Non...
def ll_merge(arg2, arg1): if arg2._len <= 0 and arg1._len <= 0: return False if arg2.head is None: return arg1 if arg1.head is None: return arg2 if True: (ptr_left, ptr_right) = (arg1.head, arg2.head) while ptr_right is not None: arg1.insert_before(ptr...
upload_folder = './static/images/' static_folder = '/static/' testing_folder = './unit_tests/' test_data_folder = '/tests/test_data' class Config(object): DEBUG = False TESTING = False class ProductionConfig(Config): SECRET_KEY = 'Y\xbf\xb9\xb6\x9e\xca\xf0\tM\x08\x96\x17\xa1t\x90h\xaf\x92\xca1\xde\xcff...
upload_folder = './static/images/' static_folder = '/static/' testing_folder = './unit_tests/' test_data_folder = '/tests/test_data' class Config(object): debug = False testing = False class Productionconfig(Config): secret_key = 'Y¿¹¶\x9eÊð\tM\x08\x96\x17¡t\x90h¯\x92Ê1ÞÏfð' encryption_rounds = 12 ...
__author__ = 'Christie' # Write a function in any language that takes as input a list of lists of integers. # The function should return void, and print to standard output the number of times each integer appeared at each index # in an inner list. So for instance: # countem ([ [ 1,2,3], [1,3,4], [1,3] ]) would outpu...
__author__ = 'Christie' def countem(listOfListOfIntegers): listof_lists = [[] for x in range(listOfListOfIntegers.__len__())] for l in listOfListOfIntegers: for (i, v) in enumerate(l): listofLists[i].append(v) for (i, v) in enumerate(listofLists): a = set(v) [print(j, '@...
while True: username = input("Type your username: ") if (username != "Diego"): continue password = input("Type your password: ") if (password == "pass21"): break print("Welcome! Access Allowed!")
while True: username = input('Type your username: ') if username != 'Diego': continue password = input('Type your password: ') if password == 'pass21': break print('Welcome! Access Allowed!')
def square(number: int) -> int: if 1 < number > 64: raise ValueError(f"number should be between 1 and 64, was {number}") return 1 << (number - 1) # 1 * 2^(number-1) def total() -> int: return (1 << 64) - 1 # 2^64 -1 = 1.844674407371e+19
def square(number: int) -> int: if 1 < number > 64: raise value_error(f'number should be between 1 and 64, was {number}') return 1 << number - 1 def total() -> int: return (1 << 64) - 1
############################################## # This for AVX2 REGISTER_TYPE="__m256d" DATA_TYPE="double" REGISTER_WIDTH = 4 NUMBER_OF_REGISTERS = 16 MASK_IN_REGISTER = 0 # should be 1 ?? #TARGET_ITILE = 4 #TARGET_JTILE = 12 TARGET_ITILE = 3 TARGET_JTILE = 16 TARGET_KTILE = 48 CACHE_SIZE = 8192 MAX_JTILE = 20 MAX_I...
register_type = '__m256d' data_type = 'double' register_width = 4 number_of_registers = 16 mask_in_register = 0 target_itile = 3 target_jtile = 16 target_ktile = 48 cache_size = 8192 max_jtile = 20 max_itile = 14 + 2 def zero(register): print('%s=_mm256_setzero_pd(); ' % register, end='') def load(register, ptr, ...
# @author Huaze Shen # @date 2020-01-29 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def flatten(root): if root is None: return flatten(root.left) flatten(root.right) temp = root.right root.right = root.left root.l...
class Treenode: def __init__(self, x): self.val = x self.left = None self.right = None def flatten(root): if root is None: return flatten(root.left) flatten(root.right) temp = root.right root.right = root.left root.left = None while root.right is not Non...
# Author - @Nathaniel Walker # Date - 9/23/20 # Description - This method will get the area of a square given one side length. # define method def area_of_square(side): return side * side
def area_of_square(side): return side * side
# There are few cases when recursion is useful # 1.When we need quick solution over efficient one # 2.While traversing trees # In this program we'll find factorial of a number # O(n!) def factorial(num): if num == 0: return 1 else: return num * factorial(num - 1) print(factorial(5))
def factorial(num): if num == 0: return 1 else: return num * factorial(num - 1) print(factorial(5))
''' Purpose : In a trading system a product is bought in the morning and sold out on the same day. If a person can make only 2 transactions a day with a condition that second transaction is followed only after first then find the maximum profit the person could get. Input formate : Line1 : Number of test cases Line...
""" Purpose : In a trading system a product is bought in the morning and sold out on the same day. If a person can make only 2 transactions a day with a condition that second transaction is followed only after first then find the maximum profit the person could get. Input formate : Line1 : Number of test cases Line...
class Graph: def __init__(self, edges): self.edges = edges self.graph_dict = {} for start, end in edges: if start in self.graph_dict: self.graph_dict[start].append(end) else: self.graph_dict[start] = [end] print("Graph Dict:", s...
class Graph: def __init__(self, edges): self.edges = edges self.graph_dict = {} for (start, end) in edges: if start in self.graph_dict: self.graph_dict[start].append(end) else: self.graph_dict[start] = [end] print('Graph Dict:'...
# the operator looks the same but behaves differently depending on the input. # Example: Addition (+ operator) # number + number = sum # string + string = concatenation # Overriding class Employee: def setNumberOfWorkingHours(self): self.numberOfWorkingHours = 40 def displayNumberOfWorkingHours(self)...
class Employee: def set_number_of_working_hours(self): self.numberOfWorkingHours = 40 def display_number_of_working_hours(self): print(self.numberOfWorkingHours) class Trainee(Employee): def set_number_of_working_hours(self): self.numberOfWorkingHours = 45 def reset_number_o...
def get_nested(o, default, *args): if o is None: return default current = o for arg in args: if current is None or arg is None or current.get(arg, None) is None: return default current = current.get(arg, default) return current
def get_nested(o, default, *args): if o is None: return default current = o for arg in args: if current is None or arg is None or current.get(arg, None) is None: return default current = current.get(arg, default) return current
class Solution: def newInteger(self, n): base9 = "" while n: base9 += str(n % 9) n //= 9 return int(base9[::-1])
class Solution: def new_integer(self, n): base9 = '' while n: base9 += str(n % 9) n //= 9 return int(base9[::-1])
#!/usr/bin/env python class Dog: def identify(self): return "jims dog"
class Dog: def identify(self): return 'jims dog'
# # https://rosettacode.org/wiki/Topological_sort#Python # ############### # # https://codeforces.com/blog/entry/16823 # ############### # https://www.python.org/doc/essays/graphs/ graph = {'A': ['B', 'C'], 'B': ['C', 'D'], 'C': ['D'], 'D': ['C'], 'E': ['F'], ...
graph = {'A': ['B', 'C'], 'B': ['C', 'D'], 'C': ['D'], 'D': ['C'], 'E': ['F'], 'F': ['C']} graph = {'C': ['D', 'B', 'A'], 'E': ['C'], 'D': ['B'], 'B': ['A'], 'A': []} def find_path(graph, start, end, path=None): if path is None: path = [] path += [start] if start == end: return path if ...