content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class Solution: # @param {int[]} nums an integer array # @return nothing, do this in-place def moveZeroes(self, nums): # Write your code here i = 0 for j in xrange(len(nums)): if nums[j]: num = nums[j] nums[j] = 0 nums[i] = ...
class Solution: def move_zeroes(self, nums): i = 0 for j in xrange(len(nums)): if nums[j]: num = nums[j] nums[j] = 0 nums[i] = num i += 1
''' key-value methods in dictionary ''' # Keys key_dictionary = { 'sector': 'Keys method', 'variable': 'dictionary' } print(key_dictionary.keys()) # Values value_dictionary = { 'sector': 'Values method', 'variable': 'dictionary' } print(value_dictionary.values()) # Key-value key_value_dictionary =...
""" key-value methods in dictionary """ key_dictionary = {'sector': 'Keys method', 'variable': 'dictionary'} print(key_dictionary.keys()) value_dictionary = {'sector': 'Values method', 'variable': 'dictionary'} print(value_dictionary.values()) key_value_dictionary = {'sector': 'key-value method', 'variable': 'dictionar...
for _ in range(int(input())): tr = int(input()) ram_task = list(map(int, input().split(' '))) dr = int(input()) ram_dare = list(map(int, input().split(' '))) ts = int(input()) sham_task = list(map(int, input().split(' '))) ds = int(input()) sham_dare = list(map(int, input().split(' '))) ...
for _ in range(int(input())): tr = int(input()) ram_task = list(map(int, input().split(' '))) dr = int(input()) ram_dare = list(map(int, input().split(' '))) ts = int(input()) sham_task = list(map(int, input().split(' '))) ds = int(input()) sham_dare = list(map(int, input().split(' '))) ...
q1 = 1 q2 = -2 q3 = 4 state = (q1, q2, q3) state = (-state[0], -state[1], -state[2]) #str(state[0]) = '33' print(state)
q1 = 1 q2 = -2 q3 = 4 state = (q1, q2, q3) state = (-state[0], -state[1], -state[2]) print(state)
load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES") load( "@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl", "feature", "flag_group", "flag_set", "tool_path", ) all_link_actions = [ ACTION_NAMES.cpp_link_executable, ACTION_NAMES.cpp_link_dynamic_library, ACTIO...
load('@bazel_tools//tools/build_defs/cc:action_names.bzl', 'ACTION_NAMES') load('@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl', 'feature', 'flag_group', 'flag_set', 'tool_path') all_link_actions = [ACTION_NAMES.cpp_link_executable, ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_libra...
def predicate(h, n): ''' Returns True if we can build a triangle of height h using n coins, else returns False ''' return h*(h+1)//2 <= n t = int(input()) for __ in range(t): n = int(input()) # binary search for the greatest height which can be reached using n coins lo = 0 hi = n wh...
def predicate(h, n): """ Returns True if we can build a triangle of height h using n coins, else returns False """ return h * (h + 1) // 2 <= n t = int(input()) for __ in range(t): n = int(input()) lo = 0 hi = n while lo < hi: mid = lo + (hi - lo + 1) // 2 if predicate(mi...
class Solution: def hammingDistance(self, x: int, y: int) -> int: count = 0 for i in range(30, -1, -1): mask = 1 << i digitX = x & mask digitY = y & mask if digitX != digitY: count += 1 return count
class Solution: def hamming_distance(self, x: int, y: int) -> int: count = 0 for i in range(30, -1, -1): mask = 1 << i digit_x = x & mask digit_y = y & mask if digitX != digitY: count += 1 return count
# https://javl.github.io/image2cpp/ # 40x40 CALENDAR_40_40 = bytearray([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x00, 0x1c, 0x00, 0x00, 0x38, 0x00, 0x1c, 0x00, 0x00, 0x3c, 0x00, 0x1c, 0x00, 0x01, 0xff, 0xff, 0xff, 0x80, 0x03, 0xff, 0xff, 0xff, 0xc0, 0x07, 0xff, 0xff, 0xff,...
calendar_40_40 = bytearray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 56, 0, 28, 0, 0, 56, 0, 28, 0, 0, 60, 0, 28, 0, 1, 255, 255, 255, 128, 3, 255, 255, 255, 192, 7, 255, 255, 255, 224, 7, 255, 255, 255, 224, 7, 255, 255, 255, 224, 7, 255, 255, 255, 224, 7, 255, 255, 255, 224, 7, 255, 255, 255, 224, 7, 128, 0, 1, 224, 7, 0, 0,...
expected_output = { "interfaces": { "GigabitEthernet1/0/17": { "mac_address": { "0024.9bff.0ac8": { "acct_session_id": "0x0000008d", "common_session_id": "0A8628020000007168945FE6", "current_policy": "Test_DOT1X-DEFAULT_...
expected_output = {'interfaces': {'GigabitEthernet1/0/17': {'mac_address': {'0024.9bff.0ac8': {'acct_session_id': '0x0000008d', 'common_session_id': '0A8628020000007168945FE6', 'current_policy': 'Test_DOT1X-DEFAULT_V1', 'domain': 'DATA', 'handle': '0x86000067', 'iif_id': '0x1534B4E2', 'ipv4_address': 'Unknown', 'ipv6_a...
def my_plot(df, case_type, case_thres=50000): m = Basemap(projection='cyl') m.fillcontinents(color='peru', alpha=0.3) groupby_columns = ['Country/Region', 'Province/State', 'Lat', 'Long'] max_num_cases = df[case_type].max() for k, g in df.groupby(groupby_columns): country_region, provi...
def my_plot(df, case_type, case_thres=50000): m = basemap(projection='cyl') m.fillcontinents(color='peru', alpha=0.3) groupby_columns = ['Country/Region', 'Province/State', 'Lat', 'Long'] max_num_cases = df[case_type].max() for (k, g) in df.groupby(groupby_columns): (country_region, province...
class Review: all_reviews = [] def __init__(self,news_id,title,name,author,description,url, urlToImage,publishedAt,content): self.new_id = new_id self.title = title self.name= name self.author=author self.description=description self.url=link self. urlT...
class Review: all_reviews = [] def __init__(self, news_id, title, name, author, description, url, urlToImage, publishedAt, content): self.new_id = new_id self.title = title self.name = name self.author = author self.description = description self.url = link ...
class Solution: def countBits(self, num: int) -> List[int]: ans=[] for i in range(num+1): ans.append(bin(i).count('1')) return ans
class Solution: def count_bits(self, num: int) -> List[int]: ans = [] for i in range(num + 1): ans.append(bin(i).count('1')) return ans
def change(img2_head_mask, img2, cv2, convexhull2, result): (x, y, w, h) = cv2.boundingRect(convexhull2) center_face2 = (int((x + x + w) / 2), int((y + y + h) / 2)) #can change it to Mix_clone seamlessclone = cv2.seamlessClone(result, img2, img2_head_mask, center_face2, cv2.NORMAL_CLONE) re...
def change(img2_head_mask, img2, cv2, convexhull2, result): (x, y, w, h) = cv2.boundingRect(convexhull2) center_face2 = (int((x + x + w) / 2), int((y + y + h) / 2)) seamlessclone = cv2.seamlessClone(result, img2, img2_head_mask, center_face2, cv2.NORMAL_CLONE) return seamlessclone
# Created by MechAviv # Map ID :: 100000000 # NPC ID :: 9110000 # Perry maps = [["Showa Town", 100000000], ["Ninja Castle", 100000000], ["Six Path Crossway", 100000000]]# TODO sm.setSpeakerID(9110000) selection = sm.sendNext("Welcome! Where to?\r\n#L0# To Showa Town#l\r\n#L1# To Ninja Castle#l\r\n#L2# To Six Path Cross...
maps = [['Showa Town', 100000000], ['Ninja Castle', 100000000], ['Six Path Crossway', 100000000]] sm.setSpeakerID(9110000) selection = sm.sendNext('Welcome! Where to?\r\n#L0# To Showa Town#l\r\n#L1# To Ninja Castle#l\r\n#L2# To Six Path Crossway#l') sm.setSpeakerID(9110000) if sm.sendAskYesNo(maps[selection][0] + '? Dr...
'''input 98 56 Worse 12 34 Better ''' # -*- coding: utf-8 -*- # AtCoder Beginner Contest # Problem A if __name__ == '__main__': x, y = list(map(int, input().split())) if x < y: print('Better') else: print('Worse')
"""input 98 56 Worse 12 34 Better """ if __name__ == '__main__': (x, y) = list(map(int, input().split())) if x < y: print('Better') else: print('Worse')
INVALID_ARGUMENT = 'invalid argument' PERMISSION_DENIED = 'permission denied' UNKNOWN = 'unknown' NOT_FOUND = 'not found' INTERNAL = 'internal error' TOO_MANY_REQUESTS = 'too many requests' SERVER_UNAVAILABLE = 'service unavailable' BAD_REQUEST = 'bad request' AUTH_ERROR = 'authorization error' class TRError(Exceptio...
invalid_argument = 'invalid argument' permission_denied = 'permission denied' unknown = 'unknown' not_found = 'not found' internal = 'internal error' too_many_requests = 'too many requests' server_unavailable = 'service unavailable' bad_request = 'bad request' auth_error = 'authorization error' class Trerror(Exception...
DATA = [ {"gender":"male","name":{"title":"mr","first":"brian","last":"watts"},"location":{"street":"8966 preston rd","city":"des moines","state":"virginia","postcode":15835},"dob":"1977-03-11 11:43:34","id":{"name":"SSN","value":"003-73-8821"},"picture":{"large":"https://randomuser.me/api/portraits/men/68.jpg","medium...
data = [{'gender': 'male', 'name': {'title': 'mr', 'first': 'brian', 'last': 'watts'}, 'location': {'street': '8966 preston rd', 'city': 'des moines', 'state': 'virginia', 'postcode': 15835}, 'dob': '1977-03-11 11:43:34', 'id': {'name': 'SSN', 'value': '003-73-8821'}, 'picture': {'large': 'https://randomuser.me/api/por...
def init() -> None: pass def run(raw_data: list) -> list: return [{"result": "Hello World"}]
def init() -> None: pass def run(raw_data: list) -> list: return [{'result': 'Hello World'}]
def can_build(env, platform): return platform=="android" def configure(env): if (env['platform'] == 'android'): env.android_add_java_dir("android") env.android_add_res_dir("res") env.android_add_asset_dir("assets") env.android_add_dependency("implementation files('../../../modules/oppo/android/libs/...
def can_build(env, platform): return platform == 'android' def configure(env): if env['platform'] == 'android': env.android_add_java_dir('android') env.android_add_res_dir('res') env.android_add_asset_dir('assets') env.android_add_dependency("implementation files('../../../modul...
# -*- coding: utf-8 -*- def main(): r, c, d = map(int, input().split()) a = [list(map(int, input().split())) for _ in range(r)] ans = 0 # See: # https://www.slideshare.net/chokudai/arc023 for y in range(r): for x in range(c): if (x + y <= d) and ((x + y) % 2 ==...
def main(): (r, c, d) = map(int, input().split()) a = [list(map(int, input().split())) for _ in range(r)] ans = 0 for y in range(r): for x in range(c): if x + y <= d and (x + y) % 2 == d % 2: ans = max(ans, a[y][x]) print(ans) if __name__ == '__main__': main()
#https://leetcode.com/problems/largest-rectangle-in-histogram/ #(Asked in Amazon SDE1 interview) class Solution: def largestRectangleArea(self, heights: List[int]) -> int: sta,finalL=[],[] it=0 for i in heights: #code for next smallest left it+=1 if st...
class Solution: def largest_rectangle_area(self, heights: List[int]) -> int: (sta, final_l) = ([], []) it = 0 for i in heights: it += 1 if sta: while sta and i <= sta[-1][1]: sta.pop() if not sta: ...
class AppSettings: types = { 'url': str, 'requestIntegration': bool, 'authURL': str, 'usernameField': str, 'passwordField': str, 'buttonField': str, 'extraFieldSelector': str, 'extraFieldValue': str, 'optionalField1': str, 'optionalFie...
class Appsettings: types = {'url': str, 'requestIntegration': bool, 'authURL': str, 'usernameField': str, 'passwordField': str, 'buttonField': str, 'extraFieldSelector': str, 'extraFieldValue': str, 'optionalField1': str, 'optionalField1Value': str, 'optionalField2': str, 'optionalField2Value': str, 'optionalField3...
class WikiPage: def __init__(self, title, uri=None, text=None, tags=None): self.title = title self.text = text or "" self.tags = tags or {} self.uri = uri or title self.parents = [] self.children = [] def add_child(self, page): self.children...
class Wikipage: def __init__(self, title, uri=None, text=None, tags=None): self.title = title self.text = text or '' self.tags = tags or {} self.uri = uri or title self.parents = [] self.children = [] def add_child(self, page): self.children.append(page)...
numbers = [12, 18, 128, 48, 2348, 21, 18, 3, 2, 42, 96, 11, 42, 12, 18] print(numbers) # Insert the number 5 to the beginning of the list. numbers.insert(0, 5) print(numbers) # Remove the number 2348 based on its value (as opposed to a hard-coded index of 4) from the list. numbers.remove(2348) print(numbers) # Creat...
numbers = [12, 18, 128, 48, 2348, 21, 18, 3, 2, 42, 96, 11, 42, 12, 18] print(numbers) numbers.insert(0, 5) print(numbers) numbers.remove(2348) print(numbers) more_numbers = [1, 2, 3, 4, 5] numbers.extend(more_numbers) print(numbers) numbers.sort() print(numbers) numbers.sort(reverse=True) print(numbers) count = number...
class pbox_description: def __init__(self, pdb_id): self.pdb_id = pdb_id def get_pdb_id(self): return self.pdb_id
class Pbox_Description: def __init__(self, pdb_id): self.pdb_id = pdb_id def get_pdb_id(self): return self.pdb_id
# Getting an input from the user x = int(input("How tall do you want your pyramid to be? ")) while x < 0 or x > 23: x = int(input("Provide a number greater than 0 and smaller than 23: ")) for i in range(x): z = i+1 # counts the number of blocks in the pyramid in each iteration y = x-i # counts the num...
x = int(input('How tall do you want your pyramid to be? ')) while x < 0 or x > 23: x = int(input('Provide a number greater than 0 and smaller than 23: ')) for i in range(x): z = i + 1 y = x - i print(' ' * y + '#' * z + ' ' + '#' * z)
class Solution: def reverseOnlyLetters(self, s: str) -> str: i = 0 j = len(s)-1 m = list(range(65, 91))+list(range(97, 123)) while i < j: if ord(s[i]) not in m: i += 1 continue if ord(s[j]) not in m: j -= 1 ...
class Solution: def reverse_only_letters(self, s: str) -> str: i = 0 j = len(s) - 1 m = list(range(65, 91)) + list(range(97, 123)) while i < j: if ord(s[i]) not in m: i += 1 continue if ord(s[j]) not in m: j -= ...
'''Returns unmodifiable sets of "uninteresting" (e.g., not drug like) ligands. References ---------- - `D3R Project <https://github.com/drugdata/D3R/blob/master/d3r/filter/filtering_sets.py`_ ''' METAL_CONTAINING = set(['CP', 'NFU', 'NFR', 'NFE', 'NFV', 'FSO', 'WCC', 'TCN', 'FS2', 'PDV', 'CPT...
"""Returns unmodifiable sets of "uninteresting" (e.g., not drug like) ligands. References ---------- - `D3R Project <https://github.com/drugdata/D3R/blob/master/d3r/filter/filtering_sets.py`_ """ metal_containing = set(['CP', 'NFU', 'NFR', 'NFE', 'NFV', 'FSO', 'WCC', 'TCN', 'FS2', 'PDV', 'CPT', 'OEC', 'XCC', 'NFS', '...
#!/usr/bin/env python # Copyright 2018 National Technology & Engineering Solutions of Sandia, LLC # (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. # Government retains certain rights in this software. class ResultsWriters: def __init__(self): "" self.writers = [] def...
class Resultswriters: def __init__(self): """""" self.writers = [] def add_writer(self, writer): """""" self.writers.append(writer) def prerun(self, atestlist, rtinfo, verbosity): """""" for wr in self.writers: wr.prerun(atestlist, rtinfo, verbo...
n = int(input()) s = [] for i in range(n): s.append(input()) # [d1, d2, d3, ..., dN] m = [] a = [] r = [] c = [] h = [] for i in s: if i[0] == "M": m.append(i) elif i[0] == "A": a.append(i) elif i[0] == "R": r.append(i) elif i[0] == "C": c.append(i) elif i[0] == "...
n = int(input()) s = [] for i in range(n): s.append(input()) m = [] a = [] r = [] c = [] h = [] for i in s: if i[0] == 'M': m.append(i) elif i[0] == 'A': a.append(i) elif i[0] == 'R': r.append(i) elif i[0] == 'C': c.append(i) elif i[0] == 'H': h.append(i) ...
# Section 9.3.2 snippets with open('accounts.txt', mode='r') as accounts: print(f'{"Account":<10}{"Name":<10}{"Balance":>10}') for record in accounts: account, name, balance = record.split() print(f'{account:<10}{name:<10}{balance:>10}') #############################################...
with open('accounts.txt', mode='r') as accounts: print(f"{'Account':<10}{'Name':<10}{'Balance':>10}") for record in accounts: (account, name, balance) = record.split() print(f'{account:<10}{name:<10}{balance:>10}')
#Array of numbers numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] #Prints out every number in array for number in numbers: print(number) print('') #Adds 1 to every number in array for number in numbers: number += 20 print(number)
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for number in numbers: print(number) print('') for number in numbers: number += 20 print(number)
# Wrong answer 10% name = input() YESnames = [] NOnames = [] first = "" biggestName = 0 habay = "" while name != "FIM": name, choice = name.split() if choice == "YES": if first == "": first = name l = len(name) if biggestName < l: biggestName = l if ...
name = input() ye_snames = [] n_onames = [] first = '' biggest_name = 0 habay = '' while name != 'FIM': (name, choice) = name.split() if choice == 'YES': if first == '': first = name l = len(name) if biggestName < l: biggest_name = l if name not in YESname...
pi = { "00": { "value": "00", "description": "Base" }, "02": { "value": "02", "description": "POS" } }
pi = {'00': {'value': '00', 'description': 'Base'}, '02': {'value': '02', 'description': 'POS'}}
#decorators for functions def audio_record_thread(func): def inner(s): print("AudioCapture: Started Recording Audio") func(s) print("AudioCapture: Stopped Recording Audio") return return inner def file_saving(func, filename): def wrap(s, filename): print("Saving...
def audio_record_thread(func): def inner(s): print('AudioCapture: Started Recording Audio') func(s) print('AudioCapture: Stopped Recording Audio') return return inner def file_saving(func, filename): def wrap(s, filename): print('Saving file...') func(s, fi...
# In case of ASCII horror, # need to get rid of this in the future. def ascii_saver(s): try: s = s.encode('ascii', errors='ignore') except: print('ascii cannot save', s) return s
def ascii_saver(s): try: s = s.encode('ascii', errors='ignore') except: print('ascii cannot save', s) return s
''' Python program to round a fl oating-point number to specifi ednumber decimal places ''' #Sample Solution-1: def setListOfIntegerOptionOne (order_amt): print('\nThe total order amount comes to %f' % float(order_amt)) print('The total order amount comes to %.2f' % float(order_amt)) print() def setLis...
""" Python program to round a fl oating-point number to specifi ednumber decimal places """ def set_list_of_integer_option_one(order_amt): print('\nThe total order amount comes to %f' % float(order_amt)) print('The total order amount comes to %.2f' % float(order_amt)) print() def set_list_of_integer_optio...
class PermissionsMixin: @classmethod def get_permissions(cls, info): return [permission(info) for permission in cls._meta.permission_classes] @classmethod def check_permissions(cls, info): for permission in cls.get_permissions(info): if not permission.has_permission(): ...
class Permissionsmixin: @classmethod def get_permissions(cls, info): return [permission(info) for permission in cls._meta.permission_classes] @classmethod def check_permissions(cls, info): for permission in cls.get_permissions(info): if not permission.has_permission(): ...
def bs(arr,target,s,e): if (s>e): return -1 m= int((s+e)/2) if arr[m]==target: return m elif target>arr[m]: return bs(arr,target,m+1,e) else: return bs(arr,target,s,m-1) if __name__ == "__main__": l1=[1, 2, 3, 4, 55, 66, 78] target = 67 print(bs(l1,...
def bs(arr, target, s, e): if s > e: return -1 m = int((s + e) / 2) if arr[m] == target: return m elif target > arr[m]: return bs(arr, target, m + 1, e) else: return bs(arr, target, s, m - 1) if __name__ == '__main__': l1 = [1, 2, 3, 4, 55, 66, 78] target = 67...
#!/usr/bin/env python # Copyright Contributors to the Open Shading Language project. # SPDX-License-Identifier: BSD-3-Clause # https://github.com/AcademySoftwareFoundation/OpenShadingLanguage command += testshade("-g 16 16 -od uint8 -o Cout out0.tif wrcloud") command += testshade("-g 16 16 -od uint8 -o Cout out0_tr...
command += testshade('-g 16 16 -od uint8 -o Cout out0.tif wrcloud') command += testshade('-g 16 16 -od uint8 -o Cout out0_transpose.tif wrcloud_transpose') command += testshade('-g 16 16 -od uint8 -o Cout out0_varying_filename.tif wrcloud_varying_filename') command += testshade('-g 256 256 -param radius 0.01 -od uint8 ...
def username_generator(first,last): counter = 0 username = "" for i in first: if counter <= 2: counter += 1 username += i counter = 0 for j in last: if counter <= 3: counter += 1 username += j return username def password_generator(username="testin"): password = "" count...
def username_generator(first, last): counter = 0 username = '' for i in first: if counter <= 2: counter += 1 username += i counter = 0 for j in last: if counter <= 3: counter += 1 username += j return username def password_generato...
# -*- coding: utf-8 -*- class Controller(object): def __init__(self, router, view): self.router = router self.view = view def show(self): if self.view: self.view.show() else: raise Exception("None view") def hide(self): if self.view: ...
class Controller(object): def __init__(self, router, view): self.router = router self.view = view def show(self): if self.view: self.view.show() else: raise exception('None view') def hide(self): if self.view: self.view.hide() ...
def geometric_eq(p,k): return (1-p)**k*p class GeometricDist: def __init__(self,p): self.p = p self.mean = (1-p)/p self.var = (1-p)/p**2 def __getitem__(self,k): return geometric_eq(self.p,k)
def geometric_eq(p, k): return (1 - p) ** k * p class Geometricdist: def __init__(self, p): self.p = p self.mean = (1 - p) / p self.var = (1 - p) / p ** 2 def __getitem__(self, k): return geometric_eq(self.p, k)
class letterCombinations: def letterCombinationsFn(self, digits: str) -> List[str]: # If the input is empty, immediately return an empty answer array if len(digits) == 0: return [] # Map all the digits to their corresponding letters letters = {"2": "abc", "3": "...
class Lettercombinations: def letter_combinations_fn(self, digits: str) -> List[str]: if len(digits) == 0: return [] letters = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'} def backtrack(index, path): if len(path)...
class Solution: def uniquePaths(self, m: int, n: int) -> int: dp = [[0]*n for i in range(m)] for i in range(m): dp[i][n-1] = 1 for i in range(n): dp[m-1][i] = 1 for i in range(m-2,-1,-1): for j in range(n-2,-1,-1): ...
class Solution: def unique_paths(self, m: int, n: int) -> int: dp = [[0] * n for i in range(m)] for i in range(m): dp[i][n - 1] = 1 for i in range(n): dp[m - 1][i] = 1 for i in range(m - 2, -1, -1): for j in range(n - 2, -1, -1): d...
n,m = list(map(int,input().split(' '))) coins = list(map(int,input().split(' '))) dp =[ [-1 for x in range(m+1)] for y in range(n+1) ] def getCount(amount,index): if amount == 0: return 1 if index == 1: coin = coins[0] if amount%coin == 0: return 1 else: r...
(n, m) = list(map(int, input().split(' '))) coins = list(map(int, input().split(' '))) dp = [[-1 for x in range(m + 1)] for y in range(n + 1)] def get_count(amount, index): if amount == 0: return 1 if index == 1: coin = coins[0] if amount % coin == 0: return 1 else: ...
c.NotebookApp.ip = '*' c.NotebookApp.token = '' c.NotebookApp.password = '' c.NotebookApp.open_browser = False c.NotebookApp.port = 8081 c.NotebookApp.allow_remote_access = True c.NotebookApp.allow_origin_pat = '(^https://8081-dot-[0-9]+-dot-devshell\.appspot\.com$)|(^https://colab\.research\.google\.com$)'
c.NotebookApp.ip = '*' c.NotebookApp.token = '' c.NotebookApp.password = '' c.NotebookApp.open_browser = False c.NotebookApp.port = 8081 c.NotebookApp.allow_remote_access = True c.NotebookApp.allow_origin_pat = '(^https://8081-dot-[0-9]+-dot-devshell\\.appspot\\.com$)|(^https://colab\\.research\\.google\\.com$)'
prova1 = float ( input()) prova2 = float ( input ()) prova3 = float (input ()) media = (((prova1 * 2.0) + (prova2 * 3.0) + (prova3 * 5.0)) / 10 ) print("MEDIA = %0.1F" % media )
prova1 = float(input()) prova2 = float(input()) prova3 = float(input()) media = (prova1 * 2.0 + prova2 * 3.0 + prova3 * 5.0) / 10 print('MEDIA = %0.1F' % media)
# https://www.codechef.com/problems/DEVUGRAP for T in range(int(input())): N,K=map(int,input().split()) n,ans=list(map(int,input().split())),0 for i in range(N): if(n[i]>=K): ans+=min(n[i]%K,K-n[i]%K) else: ans+=K-n[i]%K print(ans)
for t in range(int(input())): (n, k) = map(int, input().split()) (n, ans) = (list(map(int, input().split())), 0) for i in range(N): if n[i] >= K: ans += min(n[i] % K, K - n[i] % K) else: ans += K - n[i] % K print(ans)
_first_index_in_every_row_list = list() def _build_first_index_in_every_row_list(): global _first_index_in_every_row_list _first_index_in_every_row_list.clear() _first_index_in_every_row_list.append(0) for delta in range(199, 1, -1): _first_index_in_every_row_list.append(_first_index_in_every_...
_first_index_in_every_row_list = list() def _build_first_index_in_every_row_list(): global _first_index_in_every_row_list _first_index_in_every_row_list.clear() _first_index_in_every_row_list.append(0) for delta in range(199, 1, -1): _first_index_in_every_row_list.append(_first_index_in_every_r...
# Function for finding if it possible # to obtain sorted array or not def fun(arr, n, k): v = [] # Iterate over all elements until K for i in range(k): # Store elements as multiples of K for j in range(i, n, k): v.append(arr[j]); # Sort the elements ...
def fun(arr, n, k): v = [] for i in range(k): for j in range(i, n, k): v.append(arr[j]) v.sort() x = 0 for j in range(i, n, k): arr[j] = v[x] x += 1 v = [] for i in range(n - 1): if arr[i] > arr[i + 1]: return Fa...
class Pessoa: menbros_superiores = 2 menbro_inferiores=2 def __init__(self,*familia,name=None,idade=17): self.name= name self.familia= list(familia) self.idade= idade def comprimentar(self): return 'hello my code' def despedisir(self): return 'diz tcha...
class Pessoa: menbros_superiores = 2 menbro_inferiores = 2 def __init__(self, *familia, name=None, idade=17): self.name = name self.familia = list(familia) self.idade = idade def comprimentar(self): return 'hello my code' def despedisir(self): return 'diz t...
# coding: utf-8 def is_bool(var): return isinstance(var, bool) if __name__ == '__main__': a = False b = 0 print(is_bool(a)) print(is_bool(b))
def is_bool(var): return isinstance(var, bool) if __name__ == '__main__': a = False b = 0 print(is_bool(a)) print(is_bool(b))
class Conta: def __init__(self, numero, nome, saldo=0): self._numero = numero self._nome = nome self._saldo = saldo def atualiza(self, taxa): self._saldo += self._saldo * taxa def deposita(self, valor): self._saldo += valor - 0.10 class ContaCorrente(Conta): ...
class Conta: def __init__(self, numero, nome, saldo=0): self._numero = numero self._nome = nome self._saldo = saldo def atualiza(self, taxa): self._saldo += self._saldo * taxa def deposita(self, valor): self._saldo += valor - 0.1 class Contacorrente(Conta): d...
# -*- coding: utf-8 -*- # Coded by Sungwook Kim # 2020-12-13 # IDE: Jupyter Notebook def Fact(a): res = 1 for i in range(a): res = res * (i + 1) return res T = int(input()) for i in range(T): r, n = map(int, input().split()) a = Fact(n) b = Fact(r) c = Fact(n-r) print(...
def fact(a): res = 1 for i in range(a): res = res * (i + 1) return res t = int(input()) for i in range(T): (r, n) = map(int, input().split()) a = fact(n) b = fact(r) c = fact(n - r) print(int(a / (c * b)))
# The base class for application-specific states. class SarifState(object): def __init__(self): self.parser = None self.ppass = 1 # Taking the easy way out. # We need something in case a descendent wants to trigger # on change to ppass. def set_ppass(self, ppass): self.ppas...
class Sarifstate(object): def __init__(self): self.parser = None self.ppass = 1 def set_ppass(self, ppass): self.ppass = ppass def get_ppass(self): return self.ppass def set_parser(self, parser): self.parser = parser def get_parser(self): return s...
# store the input from the user into age age = input("How old are you? ") # store the input from the user into height height = input(f"You're {age}? Nice. How tall are you? ") # store the input from the user into weight weight = input("How much do you weigh? ") # print the f-string with the age, height and weight prin...
age = input('How old are you? ') height = input(f"You're {age}? Nice. How tall are you? ") weight = input('How much do you weigh? ') print(f"So you're {age} old. {height} tall and {weight} heavy.")
def loss_layer(self, predicts, labels, scope='loss_layer'): with tf.variable_scope(scope): predict_classes = tf.reshape(predicts[:, :self.boundary1], [self.batch_size, self.cell_size, self.cell_size, self.num_class]) predict_scales = tf.reshape(predicts[:, self.b...
def loss_layer(self, predicts, labels, scope='loss_layer'): with tf.variable_scope(scope): predict_classes = tf.reshape(predicts[:, :self.boundary1], [self.batch_size, self.cell_size, self.cell_size, self.num_class]) predict_scales = tf.reshape(predicts[:, self.boundary1:self.boundary2], [self.batch...
# AKSHITH K # BUBBLE SORT IMPLEMENTED IN PYTHON RECURSIVELY. def bubblesort(arr, n): # checking if the array does not need to be sorted and has a length of 1. if n <= 1: return # creating a for-loop to iterate for the elements in the array. for i in range(0, n - 1): # c...
def bubblesort(arr, n): if n <= 1: return for i in range(0, n - 1): if arr[i] > arr[i + 1]: (arr[i], arr[i + 1]) = (arr[i + 1], arr[i]) return bubblesort(arr, n - 1) arr = [4, 9, 1, 3, 0, 2, 6, 8, 5, 7] n = len(arr) bubblesort(arr, n) print(arr)
## Problem 10.2 # write a program to read through the mbox-short.txt # and figure out the distribution by hour of the day for each of the messages. file_name = input("Enter file:") file_handle = open(file_name) hour_list = list() for line in file_handle: # pull the hour out from the 'From ' line # From stephe...
file_name = input('Enter file:') file_handle = open(file_name) hour_list = list() for line in file_handle: if line.startswith('From'): line_list = line.split() if len(line_list) > 2: hour = line_list[5][:2] hour_list.append(hour) hour_dict = dict() for key in hour_list: h...
# Copyright 2006 James Tauber and contributors # Copyright (C) 2009 Luke Kenneth Casson Leighton <lkcl@lkcl.net> # Copyright (C) 2010 Serge Tarkovski <serge.tarkovski@gmail.com> # Copyright (C) 2010 Rich Newpol (IE override) <rich.newpol@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # y...
def show(mousetarget, **kwargs): global mousecapturer target_element = mousetarget.getElement() if hasattr(target_element, 'setCapture'): mousecapturer = target_element DOM.setCapture(target_element) def hide(): global mousecapturer if hasattr(mousecapturer, 'releaseCapture'): ...
# WAP to show the use of if..elif..else season= input("Enter season : ") print(season) if season == 'spring': print('plant the garden!') elif season == 'summer': print('water the garden!') elif season == 'fall': print('harvest the garden!') elif season == 'winter': print('stay indoors!') e...
season = input('Enter season : ') print(season) if season == 'spring': print('plant the garden!') elif season == 'summer': print('water the garden!') elif season == 'fall': print('harvest the garden!') elif season == 'winter': print('stay indoors!') else: print('unrecognized season')
# # PySNMP MIB module HH3C-L2TP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-L2TP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:14:47 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_range_constraint, constraints_union, single_value_constraint, value_size_constraint) ...
kuukiondo = 70 shitsudo = 100 if kuukiondo >= 100: print("A") elif kuukiondo >= 92 and shitsudo > 75: print("B") elif kuukiondo > 88 and shitsudo >= 85: print("C") elif kuukiondo == 75 and shitsudo <= 65: print("D") else: print("E")
kuukiondo = 70 shitsudo = 100 if kuukiondo >= 100: print('A') elif kuukiondo >= 92 and shitsudo > 75: print('B') elif kuukiondo > 88 and shitsudo >= 85: print('C') elif kuukiondo == 75 and shitsudo <= 65: print('D') else: print('E')
class Solution1: def maxSubArray(self, nums: List[int]) -> int: total_max, total = -1e10, 0 for i in range( len(nums) ): if total > 0: total += nums[i] else: total = nums[i] if total > total_max: t...
class Solution1: def max_sub_array(self, nums: List[int]) -> int: (total_max, total) = (-10000000000.0, 0) for i in range(len(nums)): if total > 0: total += nums[i] else: total = nums[i] if total > total_max: total_...
################################################################################ # # # ____ _ # # | _ \ ___ __| |_ __ _ _ _ __ ___ ...
class Metadata_Dictionary_Type: key_flags: int = 0 key_health: int = 1 key_variant: int = 2 key_color: int = 3 key_nametag: int = 4 key_owner_eid: int = 5 key_target_eid: int = 6 key_air: int = 7 key_potion_color: int = 8 key_potion_ambient: int = 9 key_jump_duration: int = 1...
class Base(object): def __secret(self): print("don't tell") def public(self): self.__secret() class Derived(Base): def __secret(self): print("never ever") if __name__ == "__main__": print("Base class members:", dir(Base)) print("Derived class members:", dir(Derived)) ...
class Base(object): def __secret(self): print("don't tell") def public(self): self.__secret() class Derived(Base): def __secret(self): print('never ever') if __name__ == '__main__': print('Base class members:', dir(Base)) print('Derived class members:', dir(Derived)) ...
# Basic script to find primer candidates # Hits are 20bp in length, with 50-55% GC content, GC clamps in the 3' end, and no more than 3xGC at the clamp # Paste the target exon sequences from a FASTA sequence with no white spaces # Exon 1 is where forward primer candidates will be identified exon1 = "GCAGTGTCACTAG...
exon1 = 'GCAGTGTCACTAGGCCGGCTGGGGGCCCTGGGTACGCTGTAGACCAGACCGCGACAGGCCAGAACACGGGCGGCGGCTTCGGGCCGGGAGACCCGCGCAGCCCTCGGGGCATCTCAGTGCCTCACTCCCCACCCCCTCCCCCGGGTCGGGGGAGGCGGCGCGTCCGGCGGAGGGTTGAGGGGAGCGGGGCAGGCCTGGAGCGCCATGAGCAGCCCGGATGCGGGATACGCCAGTGACGACCAGAGCCAGACCCAGAGCGCGCTGCCCGCGGTGATGGCCGGGCTGGGCCCCTGCCCCTGGGCCGAGTCGCT...
# Objective # Today we're discussing scope. Check out the Tutorial tab for learning materials and an instructional video! # The absolute difference between two integers, # and , is written as . The maximum absolute difference between two integers in a set of positive integers, , is the largest absolute difference betw...
class Difference: def __init__(self, a): self.__elements = a def compute_difference(self): diff_array = [] for i in range(len(self.__elements) - 1): for j in range(i + 1, len(self.__elements)): diff = abs(self.__elements[j] - self.__elements[i]) ...
#another way of doing recursive palindrome def is_palindrome(s): ln = len(s) if s != '': if s[ln-1] == s[0]: return True and is_palindrome(s[1:ln-1]) return False return True assert is_palindrome('abab') == False assert is_palindrome('abba') == True assert is_palindrome('madam')...
def is_palindrome(s): ln = len(s) if s != '': if s[ln - 1] == s[0]: return True and is_palindrome(s[1:ln - 1]) return False return True assert is_palindrome('abab') == False assert is_palindrome('abba') == True assert is_palindrome('madam') == True assert is_palindrome('madame') ...
class Profile(object): @property def name(self): return self.__name @property def trustRoleArn(self): return self.__trustRoleArn @property def sourceProfile(self): return self.__sourceProfile @property def credentials(self): return self.__credentials ...
class Profile(object): @property def name(self): return self.__name @property def trust_role_arn(self): return self.__trustRoleArn @property def source_profile(self): return self.__sourceProfile @property def credentials(self): return self.__credential...
# f_name = 'ex1.txt' f_name = 'input.txt' all_ingredients = set() possible_allergens = dict() recipes = list() with open(f_name, 'r') as f: for i, line in enumerate(f.readlines()): # get a list of the ingredients and record the food recipe as a set of the # ingredients (recipes = [{'aaa', 'bbb'}, ...
f_name = 'input.txt' all_ingredients = set() possible_allergens = dict() recipes = list() with open(f_name, 'r') as f: for (i, line) in enumerate(f.readlines()): ingredients = line.split(' (')[0].strip().split() recipes.append(set(ingredients)) all_ingredients |= set(ingredients) all...
S = 0 T = 0 L = [] for i in range(11): L.append(list(map(int,input().split()))) L.sort(key = lambda t:(t[0],t[1])) for i in L: T+=i[0] S += T + i[1]*20 print(S)
s = 0 t = 0 l = [] for i in range(11): L.append(list(map(int, input().split()))) L.sort(key=lambda t: (t[0], t[1])) for i in L: t += i[0] s += T + i[1] * 20 print(S)
# Evaluacion de expresiones print(3+5) print(3+2*5) print((3+2)*5) print(2**3) print(4**0.5) print(10%3) print('abra' + 'cadabra') print('ja'*3) print(1+2) print(1.0+2.0) print(1.0+2) print(1/2) print(1//2) print(1.0//2.0) print('En el curso hay ' + str(30) + ' alumnos') print('100'+'1') print(int('100') +1) # Variabl...
print(3 + 5) print(3 + 2 * 5) print((3 + 2) * 5) print(2 ** 3) print(4 ** 0.5) print(10 % 3) print('abra' + 'cadabra') print('ja' * 3) print(1 + 2) print(1.0 + 2.0) print(1.0 + 2) print(1 / 2) print(1 // 2) print(1.0 // 2.0) print('En el curso hay ' + str(30) + ' alumnos') print('100' + '1') print(int('100') + 1) a = 8...
a, b, c, d = 1, 2, 3, 4 print(a, b, c, d) a, b, c, d = d, c, b, a print(a, b, c, d)
(a, b, c, d) = (1, 2, 3, 4) print(a, b, c, d) (a, b, c, d) = (d, c, b, a) print(a, b, c, d)
def test_metadata(system_config) -> None: assert system_config.provider_code == "system" assert system_config._prefix == "TEST" def test_prefixize(system_config) -> None: assert system_config.prefixize("key1") == "TEST_KEY1" assert system_config.unprefixize("TEST_KEY1") == "key1" def test_get_variab...
def test_metadata(system_config) -> None: assert system_config.provider_code == 'system' assert system_config._prefix == 'TEST' def test_prefixize(system_config) -> None: assert system_config.prefixize('key1') == 'TEST_KEY1' assert system_config.unprefixize('TEST_KEY1') == 'key1' def test_get_variable...
def read_matrix(): rows_count = int(input()) matrix = [] for _ in range(rows_count): row = [int(r) for r in input().split(' ')] matrix.append(row) return matrix def get_primary_diagonal_sum(matrix): p_d_sum = 0 for i in range(len(matrix)): p_d_sum += matrix[i][i] ...
def read_matrix(): rows_count = int(input()) matrix = [] for _ in range(rows_count): row = [int(r) for r in input().split(' ')] matrix.append(row) return matrix def get_primary_diagonal_sum(matrix): p_d_sum = 0 for i in range(len(matrix)): p_d_sum += matrix[i][i] ret...
''' 1. The algorithm is a substitution cipher. It shifts each letter by a certain key. 2. Python Library Functions used : a) ord() : Converts a character to its equivalent ASCII value. b) chr() : Converts an ASCII value to its equivalent character. 3. What are 65 and 97? a) 65 is the ASCII value of 'A'. ...
""" 1. The algorithm is a substitution cipher. It shifts each letter by a certain key. 2. Python Library Functions used : a) ord() : Converts a character to its equivalent ASCII value. b) chr() : Converts an ASCII value to its equivalent character. 3. What are 65 and 97? a) 65 is the ASCII value of 'A'. ...
#!/usr/bin/env python3 #!/usr/bin/python3 dict1 = { 'a': 1, 'b': 2, } dict2 = { 'a': 0, 'b': 2, } if dict1 == dict2: print("FAIL") else: print("PASS") dict1 = { 'a': { 'c': 'bake' }, 'b': 2, } dict2 = { 'a': { 'c': 'shake' }, 'b': 2, } if dict1 == di...
dict1 = {'a': 1, 'b': 2} dict2 = {'a': 0, 'b': 2} if dict1 == dict2: print('FAIL') else: print('PASS') dict1 = {'a': {'c': 'bake'}, 'b': 2} dict2 = {'a': {'c': 'shake'}, 'b': 2} if dict1 == dict2: print('FAIL') else: print('PASS') dict1 = {'a': {'c': [0, 1]}, 'b': 2} dict2 = {'a': {'c': [0, 2]}, 'b': 2}...
## Grasshopper - Summation ## 8 kyu ## https://www.codewars.com/kata/55d24f55d7dd296eb9000030 def summation(num): return sum([i for i in range(num+1)])
def summation(num): return sum([i for i in range(num + 1)])
LEFT_ALIGNED = 0 RIGHT_ALIGNED = 1 CENTER_ALIGNED = 2 JUSTIFIED_ALIGNED = 3 NATURAL_ALIGNED = 4
left_aligned = 0 right_aligned = 1 center_aligned = 2 justified_aligned = 3 natural_aligned = 4
score_1 = float(input('Type your 1st score: ')) score_2 = float(input('Type your 2nd score: ')) average = (score_1 + score_2) / 2 print(f'Your average is {average}, therefore you...') print('Pass. Congrats.') if average > 6 \ else print('Fail. Study again, you\'ll get it. :)')
score_1 = float(input('Type your 1st score: ')) score_2 = float(input('Type your 2nd score: ')) average = (score_1 + score_2) / 2 print(f'Your average is {average}, therefore you...') print('Pass. Congrats.') if average > 6 else print("Fail. Study again, you'll get it. :)")
class NoDataError(Exception): def __init__(self, field, obj, module): message = "Missing field '" + field + "' in the object " + str(obj) + " needed in " + module super(NoDataError, self).__init__(message)
class Nodataerror(Exception): def __init__(self, field, obj, module): message = "Missing field '" + field + "' in the object " + str(obj) + ' needed in ' + module super(NoDataError, self).__init__(message)
class Event(): def __init__(self, guild_id, event_type, target_id, target_name, actor, reason, timestamp, role_id=None, role_name=None, count=None, message_id=None): self.guild_id = guild_id self.event_type = event_type self.target_id = target_id self.target_name = target_name ...
class Event: def __init__(self, guild_id, event_type, target_id, target_name, actor, reason, timestamp, role_id=None, role_name=None, count=None, message_id=None): self.guild_id = guild_id self.event_type = event_type self.target_id = target_id self.target_name = target_name ...
nintendo_games = ['Zelda', 'Mario', 'Donkey Kong', 'Zelda'] nintendo_games.remove('Zelda') print(nintendo_games) if 'Wario' in nintendo_games: nintendo_games.remove('Wario')
nintendo_games = ['Zelda', 'Mario', 'Donkey Kong', 'Zelda'] nintendo_games.remove('Zelda') print(nintendo_games) if 'Wario' in nintendo_games: nintendo_games.remove('Wario')
class Test: def initialize(self): self.x = 42 t = Test() t.initialize() def calc(self, n): return self.x + n Test.calc = calc assert t.calc(4) == 46
class Test: def initialize(self): self.x = 42 t = test() t.initialize() def calc(self, n): return self.x + n Test.calc = calc assert t.calc(4) == 46
# Time: O(n) # Space: O(1) # # 123 # Say you have an array for which the ith element # is the price of a given stock on day i. # # Design an algorithm to find the maximum profit. # You may complete at most two transactions. # # Note: # You may not engage in multiple transactions at the same time # (ie, you must sell t...
try: xrange except NameError: xrange = range class Solution(object): def max_profit(self, prices): (hold1, hold2) = (float('-inf'), float('-inf')) (cash1, cash2) = (0, 0) for p in prices: hold1 = max(hold1, -p) cash1 = max(cash1, hold1 + p) hold2...
def firstDuplicateValue(array): for n in array: n = abs(n) if array[n - 1] < 0: return n array[n - 1] *= -1 return -1
def first_duplicate_value(array): for n in array: n = abs(n) if array[n - 1] < 0: return n array[n - 1] *= -1 return -1
#!/usr/bin/python # -*- coding: utf-8 -*- def read_gowalla_data(file_path): train_file = open(file_path, 'r') x_data = {} for i in open(file_path): line = train_file.readline() # line = line.strip('\n') if len(line) == 0: continue items = line.split("\t") ...
def read_gowalla_data(file_path): train_file = open(file_path, 'r') x_data = {} for i in open(file_path): line = train_file.readline() if len(line) == 0: continue items = line.split('\t') user_id = items[0] if len(user_id) == 0: continue ...
# Which environment frames do we need to keep during evaluation? # There is a set of active environments Values and frames in active environments consume memory # Memory that is used for other values and frames can be recycled # Active environments: # Environments for any functions calls currently being evaluated ...
def count_frames(f): def counted(*arg): counted.open_count += 1 if counted.max_count < counted.open_count: counted.max_count = counted.open_count result = f(*arg) counted.open_count -= 1 return result counted.open_count = 0 counted.max_count = 0 retur...
class Solution: def XXX(self, nums: List[int]) -> List[List[int]]: return [[nums[j] for j in range(len(nums)) if i&2**j] for i in range(2**len(nums))]
class Solution: def xxx(self, nums: List[int]) -> List[List[int]]: return [[nums[j] for j in range(len(nums)) if i & 2 ** j] for i in range(2 ** len(nums))]
def viralAdvertising(n): return if __name__ == '__main__': n = int(input()) viralAdvertising(n)
def viral_advertising(n): return if __name__ == '__main__': n = int(input()) viral_advertising(n)
# This is just a demo file print("Hello world") print("this is update to my previous code")
print('Hello world') print('this is update to my previous code')
n = int(input()) # n = 3 sum1 = 0 sum2 = 0 for i in range(1, n + 1): # print("i = ", i) if i % 2 == 0: sum1 += i else: sum2 += i if sum1 == 0: print(sum2) else: print(sum2 - sum1)
n = int(input()) sum1 = 0 sum2 = 0 for i in range(1, n + 1): if i % 2 == 0: sum1 += i else: sum2 += i if sum1 == 0: print(sum2) else: print(sum2 - sum1)
class Solution: # @return a tuple, (index1, index2) def twoSum(self, num, target): length = len(num) # use dict: value: index + 1 # since there is only one solution, the right value must not be duplicated dic = {} for i in xrange(0, length): val = num[i] ...
class Solution: def two_sum(self, num, target): length = len(num) dic = {} for i in xrange(0, length): val = num[i] if target - val in dic: return (dic[target - val], i + 1) dic[val] = i + 1
#Tree Size class Node: def __init__(self, data): self.data = data self.left = None self.right = None def sizeTree(node): if node is None: return 0 else: return (sizeTree(node.left) + 1 + sizeTree(node.right)) # Driver program to test above function root = Node(1) ro...
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def size_tree(node): if node is None: return 0 else: return size_tree(node.left) + 1 + size_tree(node.right) root = node(1) root.left = node(2) root.right = node(3) root.left.l...
''' One Away: There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away. Example: pale, ple -> true pales, pale -> true pale, bale -> true pale, bake -> false b...
""" One Away: There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away. Example: pale, ple -> true pales, pale -> true pale, bale -> true pale, bake -> false b...
max_n = 10**17 fibs = [ (1, 1), (2, 1), ] while fibs[-1][0] < max_n: fibs.append( (fibs[-1][0] + fibs[-2][0], fibs[-1][1] + fibs[-2][1]) ) print(fibs) counts = [ 1, 1 ] for i in range(2, len(fibs)): fib = fibs[i] counts.append(fib[1] + sum(counts[j] for j in range(i - 1))) ...
max_n = 10 ** 17 fibs = [(1, 1), (2, 1)] while fibs[-1][0] < max_n: fibs.append((fibs[-1][0] + fibs[-2][0], fibs[-1][1] + fibs[-2][1])) print(fibs) counts = [1, 1] for i in range(2, len(fibs)): fib = fibs[i] counts.append(fib[1] + sum((counts[j] for j in range(i - 1)))) print(counts) def count(n): smal...
class StateMachine: def __init__(self, initialState): self.currentState = initialState self.currentState.run() # Template method: def runAll(self, inputs): self.currentState = self.currentState.next_state(inputs) self.currentState.run()
class Statemachine: def __init__(self, initialState): self.currentState = initialState self.currentState.run() def run_all(self, inputs): self.currentState = self.currentState.next_state(inputs) self.currentState.run()
numbers = [8, 6, 4, 1, 3, 7, 9, 5, 2] def pancake_sort(array): target_index = len(array)-1 while target_index > 0: max_value = array[target_index] max_index = target_index for number in range(0, target_index): if array[number] > max_value: max_value = array[number] max_index = num...
numbers = [8, 6, 4, 1, 3, 7, 9, 5, 2] def pancake_sort(array): target_index = len(array) - 1 while target_index > 0: max_value = array[target_index] max_index = target_index for number in range(0, target_index): if array[number] > max_value: max_value = array...