content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class Observable: def __init__(self): self.result = None def callback(self, result): self.result = result def format_response(self): results = [] for d in self.result.search.docs: for idx, match in enumerate(d.matches): score = match.score.value ...
class Observable: def __init__(self): self.result = None def callback(self, result): self.result = result def format_response(self): results = [] for d in self.result.search.docs: for (idx, match) in enumerate(d.matches): score = match.score.val...
# Copyright 2014 Doug Latornell and The University of British Columbia # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by ap...
"""Python packaging metadata for ECget. """ __all__ = ['PROJECT', 'DESCRIPTION', 'VERSION', 'DEV_STATUS'] project = 'ECget' description = 'Get Environment Canada Weather & Hydrometric Data' version = '0.5' dev_status = '4 - Beta'
# -*- coding: UTF-8 -*- logger.info("Loading 1 objects to table notes_eventtype...") # fields: id, name, remark, body loader.save(create_notes_eventtype(1,['System note', 'System note', 'System note'],u'',['', '', ''])) loader.flush_deferred_objects()
logger.info('Loading 1 objects to table notes_eventtype...') loader.save(create_notes_eventtype(1, ['System note', 'System note', 'System note'], u'', ['', '', ''])) loader.flush_deferred_objects()
expected_output = { "bridge_domain": { 3051: { "number_of_ports_in_all": 2, "state": "UP", "member_ports": [ "vfi VPLS-3051 neighbor 192.168.36.220 3051", "GigabitEthernet0/0/3 service instance 3051", ], "mac_table":...
expected_output = {'bridge_domain': {3051: {'number_of_ports_in_all': 2, 'state': 'UP', 'member_ports': ['vfi VPLS-3051 neighbor 192.168.36.220 3051', 'GigabitEthernet0/0/3 service instance 3051'], 'mac_table': {'GigabitEthernet0/0/3.EFP3051': {'pseudoport': 'GigabitEthernet0/0/3.EFP3051', 'mac_address': {'0000.A0FF.01...
# -*- coding: utf-8 -*- """ overholt ~~~~~~~~ overholt application package """
""" overholt ~~~~~~~~ overholt application package """
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ { 'target_name': 'duplicate_names', 'type': 'shared_library', 'dependencies': [ 'one/sub.gyp:one', ...
{'targets': [{'target_name': 'duplicate_names', 'type': 'shared_library', 'dependencies': ['one/sub.gyp:one', 'two/sub.gyp:two']}]}
class FinnHubAPI: TOKEN="yourTokenHere" # Get a FinHubb API from # https://finnhub.io/
class Finnhubapi: token = 'yourTokenHere'
""" Config for Reddit Giveaway I need some configuration, so that the script itself is more reusable. """ SUBMISSION = '40idxl' MATCH_TEXT = 'I would build'
""" Config for Reddit Giveaway I need some configuration, so that the script itself is more reusable. """ submission = '40idxl' match_text = 'I would build'
B = BLOCK_SIZE = 30 SURFACE_WIDTH = 300 SURFACE_HEIGHT = 600 S = [['.....', '.....', '..00.', '.00..', '.....'], ['.....', '..0..', '..00.', '...0.', '.....' ]] Z = [['.....', '.....', '.00..', '..00.', '.....'], ['.....', ...
b = block_size = 30 surface_width = 300 surface_height = 600 s = [['.....', '.....', '..00.', '.00..', '.....'], ['.....', '..0..', '..00.', '...0.', '.....']] z = [['.....', '.....', '.00..', '..00.', '.....'], ['.....', '..,0.', '..00.', '..0..', '.....']] i = [['.....', '..0..', '..0..', '..0..', '.....'], ['.....',...
lista = ('Lapis', 1.5, 'caneta', 2.5, 'caderno', 16.90, 'mochila', 67.99, 'livro', 37.89) print('-'*40) print(f'{"LISTA ESCOLAR":^40}') print('-'*40) for c in range(0, len(lista)): if c % 2 == 0: print(f'{lista[c]:.<30}', end=' ') else: print(f'R$ {lista[c]:.2f}') print('-'*40)
lista = ('Lapis', 1.5, 'caneta', 2.5, 'caderno', 16.9, 'mochila', 67.99, 'livro', 37.89) print('-' * 40) print(f"{'LISTA ESCOLAR':^40}") print('-' * 40) for c in range(0, len(lista)): if c % 2 == 0: print(f'{lista[c]:.<30}', end=' ') else: print(f'R$ {lista[c]:.2f}') print('-' * 40)
class WindowDatas(): def __init__(self): self.previousWindow = None self.nextWindow = None self.finalWindow = None self.accountDATA = None self.actions= None self.show= True self.database = None
class Windowdatas: def __init__(self): self.previousWindow = None self.nextWindow = None self.finalWindow = None self.accountDATA = None self.actions = None self.show = True self.database = None
# Flask Config Variables to be Auto-Loaded config = { 'flask': { 'SECRET_KEY': b'!T3DxK;L1jJGYf$', # Please change. See Flask for requirements. 'TESTING': True, 'TEMPLATES_AUTO_RELOAD': True, 'SERVER_NAME': 'flask.mvc' }, 'templati...
config = {'flask': {'SECRET_KEY': b'!T3DxK;L1jJGYf$', 'TESTING': True, 'TEMPLATES_AUTO_RELOAD': True, 'SERVER_NAME': 'flask.mvc'}, 'templating': {'template_folder': 'application/views', 'static_folder': 'public/assets'}}
class FVTADD : def __init__(self): self.default = '' def runTest(self,self) : return TemplateTest.runTest(self) def tearDown(self,self) : return TemplateTest.tearDown(self) def setUp(self,self) : return TemplateTest.setUp(self) def chkSetUpCondition(self,self,fv,...
class Fvtadd: def __init__(self): self.default = '' def run_test(self, self): return TemplateTest.runTest(self) def tear_down(self, self): return TemplateTest.tearDown(self) def set_up(self, self): return TemplateTest.setUp(self) def chk_set_up_condition(self, se...
class ITopBanner(Interface): """marker interface for Front Page""" class IThemeSpecific(Interface): """marker interface for theme layer"""
class Itopbanner(Interface): """marker interface for Front Page""" class Ithemespecific(Interface): """marker interface for theme layer"""
#Your task is to complete this function # function should strictly return a string else answer wont be printed def multiplyStrings(str1, str2): return str(int(str1) * int(str2))
def multiply_strings(str1, str2): return str(int(str1) * int(str2))
#!/usr/bin/env python # # Copyright (c) 2015 Pavel Lazar pavel.lazar (at) gmail.com # # The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. ##################################################################### class EngineClientError(Exception): """ An exception in the EE client. """ pas...
class Engineclienterror(Exception): """ An exception in the EE client. """ pass
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # Prefixes CONSOLE_LOG_PREFIX = "LanguageWorkerConsoleLog" # Capabilities RAW_HTTP_BODY_BYTES = "RawHttpBodyBytes" TYPED_DATA_COLLECTION = "TypedDataCollection" RPC_HTTP_BODY_ONLY = "RpcHttpBodyOnly" RPC_HTTP_TRIGGER_METADAT...
console_log_prefix = 'LanguageWorkerConsoleLog' raw_http_body_bytes = 'RawHttpBodyBytes' typed_data_collection = 'TypedDataCollection' rpc_http_body_only = 'RpcHttpBodyOnly' rpc_http_trigger_metadata_removed = 'RpcHttpTriggerMetadataRemoved' pyazure_webhost_debug = 'PYAZURE_WEBHOST_DEBUG' python_rollback_cwd_path = 'PY...
n = int(input()) res = 0 for i in range(n): res += int((input().strip())[:25]) print(str(res)[:10])
n = int(input()) res = 0 for i in range(n): res += int(input().strip()[:25]) print(str(res)[:10])
class Solution: def numDecodings(self, s: str) -> int: if not s or s[0] == '0': return 0 dp = [1, 1] for i in range(2, len(s) + 1): if '10' < s[i - 2: i] <= '26' and s[i - 1] != '0': dp.append(dp[i - 1] + dp[i - 2]) elif s[i - 2: i] == '10' or s[i - 2:...
class Solution: def num_decodings(self, s: str) -> int: if not s or s[0] == '0': return 0 dp = [1, 1] for i in range(2, len(s) + 1): if '10' < s[i - 2:i] <= '26' and s[i - 1] != '0': dp.append(dp[i - 1] + dp[i - 2]) elif s[i - 2:i] == '10'...
version = "0.1.0" # Application version class Signal(object): """ A "Observer" implementation. Note: ONLY works with class methods. Example: from loremdb.common import Signal class Observed(object): def __init__(self): self.changed = Signal() ...
version = '0.1.0' class Signal(object): """ A "Observer" implementation. Note: ONLY works with class methods. Example: from loremdb.common import Signal class Observed(object): def __init__(self): self.changed = Signal() self.val = 0 ...
print("Welcome to the birthday dictionary. We know the birthdays of:") birthdays = {"Albert Einstein": "03/14/1879", "Benjamin Franklin": "01/17/1706", "Ada Lovelace": "12/10/1815"} for person in birthdays: print(person) name = input("Who's birthday do you want to look up? ") if(name in birthdays): print(...
print('Welcome to the birthday dictionary. We know the birthdays of:') birthdays = {'Albert Einstein': '03/14/1879', 'Benjamin Franklin': '01/17/1706', 'Ada Lovelace': '12/10/1815'} for person in birthdays: print(person) name = input("Who's birthday do you want to look up? ") if name in birthdays: print(name + ...
JAVA_LANGUAGE_LEVEL = "1.8" KOTLIN_LANGUAGE_LEVEL = "1.3" KOTLINC_VERSION = "1.3.41" KOTLINC_ROOT = "https://github.com/JetBrains/kotlin/releases/download" KOTLINC_SHA = "c44ab6866895606e408b60934ebe45d4befcbc33ea0e4ea73c4b3b89ad770132" KOTLIN_RULES_VERSION = "legacy-modded-0_26_1-02" KOTLIN_RULES_SHA = "245d0bc1511048...
java_language_level = '1.8' kotlin_language_level = '1.3' kotlinc_version = '1.3.41' kotlinc_root = 'https://github.com/JetBrains/kotlin/releases/download' kotlinc_sha = 'c44ab6866895606e408b60934ebe45d4befcbc33ea0e4ea73c4b3b89ad770132' kotlin_rules_version = 'legacy-modded-0_26_1-02' kotlin_rules_sha = '245d0bc1511048...
"Listing of all e2e tests, used to set up their repositories in /WORKSPACE" ALL_E2E = [ "bazel_managed_deps", "fine_grained_symlinks", "jasmine", "karma", "karma_stack_trace", "karma_typescript", "less", "node_loader_no_preserve_symlinks", "node_loader_preserve_symlinks", "packag...
"""Listing of all e2e tests, used to set up their repositories in /WORKSPACE""" all_e2_e = ['bazel_managed_deps', 'fine_grained_symlinks', 'jasmine', 'karma', 'karma_stack_trace', 'karma_typescript', 'less', 'node_loader_no_preserve_symlinks', 'node_loader_preserve_symlinks', 'packages', 'stylus', 'symlinked_node_modul...
# Ian McLoughlin # A program that displays Fibonacci numbers using people's names. # Exercise executed by Simona Vasiliauskaite def fib(n): """This function returns the nth Fibonacci number.""" i = 0 j = 1 n = n - 1 while n >= 0: i, j = j, i + j n = n - 1 return i name = "Vasiliauskaite" first...
def fib(n): """This function returns the nth Fibonacci number.""" i = 0 j = 1 n = n - 1 while n >= 0: (i, j) = (j, i + j) n = n - 1 return i name = 'Vasiliauskaite' first = name[0] last = name[-1] firstno = ord(first) lastno = ord(last) x = firstno + lastno ans = fib(x) print('My...
# Copyright (c) 2021 Gerald E. Fux # # Licensed under the MIT License """ This module just defines what version of example_py_package we are currently looking at. """ __version__ = '0.0.1'
""" This module just defines what version of example_py_package we are currently looking at. """ __version__ = '0.0.1'
# Time: O(nlogn) # Space: O(1) class Solution(object): def videoStitching(self, clips, T): """ :type clips: List[List[int]] :type T: int :rtype: int """ if T == 0: return 0 result = 1 curr_reachable, reachable = 0, 0 clips.sort() ...
class Solution(object): def video_stitching(self, clips, T): """ :type clips: List[List[int]] :type T: int :rtype: int """ if T == 0: return 0 result = 1 (curr_reachable, reachable) = (0, 0) clips.sort() for (left, right) i...
base_api = "https://myanimelist.net/" #Anime anime = base_api + "api/animelist/" search_anime = base_api + "api/anime/search.xml" add_anime = anime + "add/{}.xml" update_anime = anime + "update/{}.xml" delete_anime = anime + "delete/{}.xml" #Manga manga = base_api + "api/mangalist/" search_manga = base_api + "api/ma...
base_api = 'https://myanimelist.net/' anime = base_api + 'api/animelist/' search_anime = base_api + 'api/anime/search.xml' add_anime = anime + 'add/{}.xml' update_anime = anime + 'update/{}.xml' delete_anime = anime + 'delete/{}.xml' manga = base_api + 'api/mangalist/' search_manga = base_api + 'api/manga/search.xml' a...
{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "name": "Untitled16.ipynb", "provenance": [], "collapsed_sections": [], "authorship_tag": "ABX9TyOm2YDBa+1KtqbwxKRFb+3Y", "include_colab_link": true }, "kernelspec": { "name": "python3", "display_n...
{'nbformat': 4, 'nbformat_minor': 0, 'metadata': {'colab': {'name': 'Untitled16.ipynb', 'provenance': [], 'collapsed_sections': [], 'authorship_tag': 'ABX9TyOm2YDBa+1KtqbwxKRFb+3Y', 'include_colab_link': true}, 'kernelspec': {'name': 'python3', 'display_name': 'Python 3'}}, 'cells': [{'cell_type': 'markdown', 'metadata...
#WAP to accept the following data in a dictionary: #Item_Name, CP, SP #Displaying #Item_Name, Profit or Loss #The program should continue as long as the user wishes to. itemInt = int(input("Enter number of items to be stored: ")) x = "y" shopping = dict() while x == "y" or x == "Y": Item_name = input("Enter...
item_int = int(input('Enter number of items to be stored: ')) x = 'y' shopping = dict() while x == 'y' or x == 'Y': item_name = input('Enter the Item Name: ') cp = int(input('Enter the Cost Price: ')) sp = int(input('Enter the Selling price: ')) shopping[Item_name] = [cp, sp, sp - cp] print('\n\nITE...
class Group(object): def __init__(self, _name): self.name = _name self.groups = [] self.users = [] def add_group(self, group): self.groups.append(group) def add_user(self, user): self.users.append(user) def get_groups(self): return self.groups def ...
class Group(object): def __init__(self, _name): self.name = _name self.groups = [] self.users = [] def add_group(self, group): self.groups.append(group) def add_user(self, user): self.users.append(user) def get_groups(self): return self.groups def...
#carriers [ x ] # substrates [ x ] guanine_mods = {'G_to_m7G' : {'name' : '7-methylguanosine', 'input' : 'G', 'output' : 'm7G', 'machines' : {'RlmL_dim' : {'proteins' : {'b0948' : 'RlmKL'}, 'RNA_position_substrates' :{'rRNA' : {2...
guanine_mods = {'G_to_m7G': {'name': '7-methylguanosine', 'input': 'G', 'output': 'm7G', 'machines': {'RlmL_dim': {'proteins': {'b0948': 'RlmKL'}, 'RNA_position_substrates': {'rRNA': {2069: {'LSU/23S/prokaryotic': 1}}}, 'carriers': None}, 'enzyme_new_RmtB': {'proteins': {'bnum': 'RmtB'}, 'RNA_position_substrates': {'rR...
doc = dict( __class__="""Performs k-means clustering on an H2O dataset.""", ) examples = dict( categorical_encoding=""" >>> prostate = h2o.import_file("http://s3.amazonaws.com/h2o-public-test-data/smalldata/prostate/prostate.csv") >>> predictors = ["AGE", "RACE", "DPROS", "DCAPS", "PSA", "VOL", "GLEASON"] >>> ...
doc = dict(__class__='Performs k-means clustering on an H2O dataset.') examples = dict(categorical_encoding='\n>>> prostate = h2o.import_file("http://s3.amazonaws.com/h2o-public-test-data/smalldata/prostate/prostate.csv")\n>>> predictors = ["AGE", "RACE", "DPROS", "DCAPS", "PSA", "VOL", "GLEASON"]\n>>> train, valid = p...
list1=[] limit=int(input('Enter the size of list')) for i in range(1,limit+1,1): items=input('Enter the items of list:') list1.append(items) for i in list1: print(i) del list1[0] print(list1)
list1 = [] limit = int(input('Enter the size of list')) for i in range(1, limit + 1, 1): items = input('Enter the items of list:') list1.append(items) for i in list1: print(i) del list1[0] print(list1)
def get_me(): print('hi') if __name__ == '__main__': # This is executed you run via terminal print('Running other_module.py...')
def get_me(): print('hi') if __name__ == '__main__': print('Running other_module.py...')
options = {0 : "zero", 1 : "sqr", 4 : "sqr", 9 : "sqr", 2 : "even", 3 : "prime", 5 : "prime", 7 : "prime", } def zero(): print ("You typed zero.\n") def sqr(): print ("n is a perfect square\n") def...
options = {0: 'zero', 1: 'sqr', 4: 'sqr', 9: 'sqr', 2: 'even', 3: 'prime', 5: 'prime', 7: 'prime'} def zero(): print('You typed zero.\n') def sqr(): print('n is a perfect square\n') def even(): print('n is an even number\n') def prime(): print('n is a prime number\n') num = int(input('Enter a number...
""" TESTS: Test consistency between modular forms and modular symbols Eisenstein series charpolys, which are computed in completely separate ways. :: sage: for N in range(25,33): ....: m = ModularForms(N) ....: e = m.eisenstein_subspace() ....: f = e.hecke_polynomial(2) ....: g = Modul...
""" TESTS: Test consistency between modular forms and modular symbols Eisenstein series charpolys, which are computed in completely separate ways. :: sage: for N in range(25,33): ....: m = ModularForms(N) ....: e = m.eisenstein_subspace() ....: f = e.hecke_polynomial(2) ....: g = Modul...
model_imp = DecisionTreeClassifier(random_state=22) model_imp.fit(X_Smote_train,Y_Smote_train) importance = model_imp.feature_importances_ for i,v in enumerate(importance): print('Feature: %0d, Score: %.5f' % (i,v)) plt.bar([x for x in range(len(importance))], importance) plt.show() np.where(importance>0.015) X_Smote...
model_imp = decision_tree_classifier(random_state=22) model_imp.fit(X_Smote_train, Y_Smote_train) importance = model_imp.feature_importances_ for (i, v) in enumerate(importance): print('Feature: %0d, Score: %.5f' % (i, v)) plt.bar([x for x in range(len(importance))], importance) plt.show() np.where(importance > 0.0...
class Solution: """ Level0: [] level1: [1] [2] [3] level2: [1,2] [1,3] [2,1] [2,3] [3,1] [3,2] level3: [1,2,3] [1,3,2] [2,1,3][2,3,1] [3,1,2][3,2,1] """ def permute(self, nums: List[int]) -> List[List[int]]: visit...
class Solution: """ Level0: [] level1: [1] [2] [3] level2: [1,2] [1,3] [2,1] [2,3] [3,1] [3,2] level3: [1,2,3] [1,3,2] [2,1,3][2,3,1] [3,1,2][3,2,1] """ def permute(self, nums: List[int]) -> List[List[int]]: visited =...
n1 = int n2 = int n3 = int n4 = int n5 = int n6 = int n7 = int n8 = int n9 = int n = int(input("Digite un Numero: ")) n1 = n*1 n2 = n*2 n3 = n*3 n4 = n*4 n5 = n*5 n6 = n*6 n7 = n*7 n8 = n*8 n9 = n*9 n10 = n*10 print ("El calculo Uno es: ", n1) print ("El calculo dos es: ", n2) print ("El calculo tres es: "...
n1 = int n2 = int n3 = int n4 = int n5 = int n6 = int n7 = int n8 = int n9 = int n = int(input('Digite un Numero: ')) n1 = n * 1 n2 = n * 2 n3 = n * 3 n4 = n * 4 n5 = n * 5 n6 = n * 6 n7 = n * 7 n8 = n * 8 n9 = n * 9 n10 = n * 10 print('El calculo Uno es: ', n1) print('El calculo dos es: ', n2) print('El calculo ...
# QUICK SORT # BEST: O(nlogn) time, O(logn) space # AVERAGE: O(nlogn) time, O(logn) space # WORST: O(n^2) time, O(logn) space def quickSort(array): # Write your code here. partition(array, 0, len(array) - 1) return array def partition(array, low, high): if low < high: print("Inside partition") pivot =...
def quick_sort(array): partition(array, 0, len(array) - 1) return array def partition(array, low, high): if low < high: print('Inside partition') pivot = quick_sort_helper(array, low, high) print('low', low, 'high', high, 'pivot', pivot) partition(array, low, pivot - 1) ...
#!/usr/bin/python3 def list_division(my_list_1, my_list_2, list_length): "divides element by element 2 lists" i = result = 0 list = [] for i in range(list_length): try: result = (my_list_1[i] / my_list_2[i]) except TypeError: result = 0 print("wrong ty...
def list_division(my_list_1, my_list_2, list_length): """divides element by element 2 lists""" i = result = 0 list = [] for i in range(list_length): try: result = my_list_1[i] / my_list_2[i] except TypeError: result = 0 print('wrong type') exce...
""" Given an array of values, determine whether a subset of the array adds up to a target sum. This problem is NP-Complete. However, it can be solved in pseudo-polynomial time, as shown below. Pseudo-polynomial means that the complexity is determined by the actual value of the input (in this case, the target number) a...
""" Given an array of values, determine whether a subset of the array adds up to a target sum. This problem is NP-Complete. However, it can be solved in pseudo-polynomial time, as shown below. Pseudo-polynomial means that the complexity is determined by the actual value of the input (in this case, the target number) a...
print('How old are you?') #ask the age my_Age = input() # input age if int(my_Age) < 18: # age comparision print('You are not on age') elif int(my_Age) >= 18: print('You are on age') if int(my_Age) >= 100: print('You are a vampire or maybe inmortal') if int(my_Age) >= 500: ...
print('How old are you?') my__age = input() if int(my_Age) < 18: print('You are not on age') elif int(my_Age) >= 18: print('You are on age') if int(my_Age) >= 100: print('You are a vampire or maybe inmortal') if int(my_Age) >= 500: print('You are inmortal') while int(my_Age) < 18...
# https://github.com/tensorflow/tensorflow/issues/2169 # MAX Unpooling in tensorflow # Solution from fabianbormann: # Limitations: # 1. //, argmax run ONLY on GPUs. def unravel_argmax(argmax, shape): output_list = [] output_list.append(argmax // (shape[2] * shape[3])) output_list.append(argmax % (shape[2]...
def unravel_argmax(argmax, shape): output_list = [] output_list.append(argmax // (shape[2] * shape[3])) output_list.append(argmax % (shape[2] * shape[3]) // shape[3]) return tf.stack(output_list) def unpool_layer2x2(x, raveled_argmax, out_shape): argmax = unravel_argmax(raveled_argmax, tf.to_int64(...
#Task No. 02 print('3rd graph') graph_3 = {7:[11,8],2:[],3:[8,10],11:[2,9,10],5:[11],9:[],8:[9]} keys_3 = list(graph_3.keys()) ## ##for i in range(len(keys_3)): ## temp = graph_3.get(keys_3[i]) ## print(str(keys_3[i]) + ' is connected with ' + str(temp) + ' and has degree of ' + str(len(temp))) for i in graph_3:...
print('3rd graph') graph_3 = {7: [11, 8], 2: [], 3: [8, 10], 11: [2, 9, 10], 5: [11], 9: [], 8: [9]} keys_3 = list(graph_3.keys()) for i in graph_3: in = 0 for j in graph_3: if i in graph_3[j]: in = In + 1 print(i, ' is connected with ', str(graph_3[i]), ' and has out-degree ', str(len(g...
print('Hello World') name = input('Please enter your name: ') print('Welcome', name) input1 = int(input('Please enter a number: ')) input2 = int(input('Please enter another number: ')) value = input1 + input2 print(f'The result of {input1} + {input2} is', value) print('The type of the value is', type(value)) input_s...
print('Hello World') name = input('Please enter your name: ') print('Welcome', name) input1 = int(input('Please enter a number: ')) input2 = int(input('Please enter another number: ')) value = input1 + input2 print(f'The result of {input1} + {input2} is', value) print('The type of the value is', type(value)) input_stri...
class Solution: def maxProfit(self, prices, fee): N = len(prices) if N < 2: return 0 ans = 0 minimum = prices[0] for i in range(1, N): if prices[i] < minimum: minimum = prices[i] elif prices[i] > minimum + fee: ...
class Solution: def max_profit(self, prices, fee): n = len(prices) if N < 2: return 0 ans = 0 minimum = prices[0] for i in range(1, N): if prices[i] < minimum: minimum = prices[i] elif prices[i] > minimum + fee: ...
ARGUMENT_PROCESS_NAME = 'process_name' ARGUMENT_FLOW_NAME = 'flow_name' ARGUMENT_STEP_NAME = 'step_name' ARGUMENT_TIMEPERIOD = 'timeperiod' ARGUMENT_START_TIMEPERIOD = 'start_timeperiod' ARGUMENT_END_TIMEPERIOD = 'end_timeperiod' ARGUMENT_UNIT_OF_WORK_TYPE = 'unit_of_work_type' # whether the unit_of_work is TYPE_MA...
argument_process_name = 'process_name' argument_flow_name = 'flow_name' argument_step_name = 'step_name' argument_timeperiod = 'timeperiod' argument_start_timeperiod = 'start_timeperiod' argument_end_timeperiod = 'end_timeperiod' argument_unit_of_work_type = 'unit_of_work_type' argument_run_mode = 'run_mode' run_mode_r...
class Plot(object): def __init__(self): pass def __call__(self): pass
class Plot(object): def __init__(self): pass def __call__(self): pass
# # PySNMP MIB module EQLEXT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EQLEXT-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:05:18 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:...
(eql_ext,) = mibBuilder.importSymbols('APENT-MIB', 'eqlExt') (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, single_value_constraint, const...
#Open file file = open('inputs\input4.txt') data = file.read().split('\n\n') file.close() #Clean input dataClean = [] for x in data: dataClean.append(x.split()) #Split with no argument splits on whitespace #Solution 1 reqFields = ['byr','iyr','eyr','hgt','hcl','ecl','pid'] valid = 0 for passport in dataClean:...
file = open('inputs\\input4.txt') data = file.read().split('\n\n') file.close() data_clean = [] for x in data: dataClean.append(x.split()) req_fields = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'] valid = 0 for passport in dataClean: reqs_met = 0 for field in passport: field = field.split(':') ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ """ class Math(): def addition(value1, value2): if not isinstance(value1, int) and not isinstance(value2, int): return 'Invalid input' else: return value1 + value2 def soustraction (val...
""" """ class Math: def addition(value1, value2): if not isinstance(value1, int) and (not isinstance(value2, int)): return 'Invalid input' else: return value1 + value2 def soustraction(value1, value2): if not isinstance(value1, int) and (not isinstance(value2,...
""" focli exceptions """ class FoliException(Exception): """ Base exception """ def __init__(self, message): self.message = message class FoliStopNameException(FoliException): """ Stop name error """ class FoliServerException(FoliException): """ Stop name error """ class FoliParseDataErr...
""" focli exceptions """ class Foliexception(Exception): """ Base exception """ def __init__(self, message): self.message = message class Folistopnameexception(FoliException): """ Stop name error """ class Foliserverexception(FoliException): """ Stop name error """ class Foliparsedataerror(...
def get_input(file): with open(file, 'rt', encoding='utf8') as f: lines = [line.strip() for line in f] p1_cars = get_player_cards(lines, 1) p2_cars = get_player_cards(lines, 2) return p1_cars, p2_cars def get_player_cards(lines, player): start = lines.index(f'Player {player}:') + 1 en...
def get_input(file): with open(file, 'rt', encoding='utf8') as f: lines = [line.strip() for line in f] p1_cars = get_player_cards(lines, 1) p2_cars = get_player_cards(lines, 2) return (p1_cars, p2_cars) def get_player_cards(lines, player): start = lines.index(f'Player {player}:') + 1 en...
__all__ = [ "int_to_bytes", "bytes_to_int", "bytes_to_hex", "hex_to_bytes" ] def bytes_to_hex(src: bytes, with0x: bool = True, max_length: int = None) -> str: if max_length is not None: assert len(src) <= max_length, f"input bytes length is too long ({len(src)} > {max_length})" res = s...
__all__ = ['int_to_bytes', 'bytes_to_int', 'bytes_to_hex', 'hex_to_bytes'] def bytes_to_hex(src: bytes, with0x: bool=True, max_length: int=None) -> str: if max_length is not None: assert len(src) <= max_length, f'input bytes length is too long ({len(src)} > {max_length})' res = src.hex() if max_len...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Assignment 3 Binary Search Tree.""" class NullBinaryTreeNode(object): """Null object pattern for a BST.""" SINGLETON = None def __new__(cls): """__new__.""" if NullBinaryTreeNode.SINGLETON is not None: return NullBinaryTreeNod...
"""Assignment 3 Binary Search Tree.""" class Nullbinarytreenode(object): """Null object pattern for a BST.""" singleton = None def __new__(cls): """__new__.""" if NullBinaryTreeNode.SINGLETON is not None: return NullBinaryTreeNode.SINGLETON NullBinaryTreeNode.SINGLETON ...
# -*- coding: utf-8 -*- """ Created on Tue Dec 3 11:19:30 2019 @author: DEVANSH JAIN """ x=input('Enter first number') y=input('Second Number') z=x+y print(z)
""" Created on Tue Dec 3 11:19:30 2019 @author: DEVANSH JAIN """ x = input('Enter first number') y = input('Second Number') z = x + y print(z)
class Solution: def longestPalindrome(self, s: str) -> str: lst = [] for ch in s: lst.append('#') lst.append(ch) lst.append('#') S = ''.join(lst) def helper(S): mx = 0 n = len(S) P = [0] * n c = 0 ...
class Solution: def longest_palindrome(self, s: str) -> str: lst = [] for ch in s: lst.append('#') lst.append(ch) lst.append('#') s = ''.join(lst) def helper(S): mx = 0 n = len(S) p = [0] * n c = 0 ...
LOG_DIR = "/tmp/mylogdir" def write_message(filename, message): try: path = os.path.join(LOG_DIR, filename) with open(path, 'a') as writer: writer.write(message) except OSError as error: print('Unable to write log message to {}: {}'.format(path, error))
log_dir = '/tmp/mylogdir' def write_message(filename, message): try: path = os.path.join(LOG_DIR, filename) with open(path, 'a') as writer: writer.write(message) except OSError as error: print('Unable to write log message to {}: {}'.format(path, error))
#!/usr/bin/env python3 n1 = int(input("Enter 1st subject degree: ")) n2 = int(input("Enter 2nd subject degree: ")) n3 = int(input("Enter 3rd subject degree: ")) if n1 >= 50 and n2 >= 50 and n3 >= 50: print("Pass") else: print("Fail")
n1 = int(input('Enter 1st subject degree: ')) n2 = int(input('Enter 2nd subject degree: ')) n3 = int(input('Enter 3rd subject degree: ')) if n1 >= 50 and n2 >= 50 and (n3 >= 50): print('Pass') else: print('Fail')
class Solution(object): # O(N^2) solution TLE # def maxArea(self, height): # """ # :type height: List[int] # :rtype: int # """ # maxcap = 0 # length = len(height) # for left in range(length - 1): # for right in range(left + 1, length): # ...
class Solution(object): def max_area(self, height): """ :type height: List[int] :rtype: int """ maxcap = 0 (left, right) = (0, len(height) - 1) while left < right: curcap = min(height[left], height[right]) * (right - left) if curcap > ...
# Python3 def bishopAndPawn(bishop, pawn): getPos = lambda s: ('abcdefgh'.index(s[0]), '12345678'.index(s[1])) bishopPos = getPos(bishop) pawnPos = getPos(pawn) return abs(bishopPos[0] - pawnPos[0]) == abs(bishopPos[1] - pawnPos[1])
def bishop_and_pawn(bishop, pawn): get_pos = lambda s: ('abcdefgh'.index(s[0]), '12345678'.index(s[1])) bishop_pos = get_pos(bishop) pawn_pos = get_pos(pawn) return abs(bishopPos[0] - pawnPos[0]) == abs(bishopPos[1] - pawnPos[1])
""" Instructions: 1. Create a class named ReversedString that inherits from StringOperations class 2. Implement the function reverse 3. reverse function should be a one liner function that returns the reverse string to_be_reversed 4. Instantiate the class ReversedString 5. Print to show your function implementation re...
""" Instructions: 1. Create a class named ReversedString that inherits from StringOperations class 2. Implement the function reverse 3. reverse function should be a one liner function that returns the reverse string to_be_reversed 4. Instantiate the class ReversedString 5. Print to show your function implementation re...
class Solution: # @param A : integer # @param B : integer # @return an integer def gcd(self,A, B): if(B==0): return A return self.gcd(B,A%B)
class Solution: def gcd(self, A, B): if B == 0: return A return self.gcd(B, A % B)
class Solution: # @param A : list of strings # @return a strings def longestCommonPrefix(self, A): A.sort() minLen = min(len(A[0]), len(A[len(A) - 1])) prefix = '' for i in range(minLen): if A[0][i] == A[len(A) - 1][i]: prefix += A[0][i] ...
class Solution: def longest_common_prefix(self, A): A.sort() min_len = min(len(A[0]), len(A[len(A) - 1])) prefix = '' for i in range(minLen): if A[0][i] == A[len(A) - 1][i]: prefix += A[0][i] else: break return str(pref...
k = int(input()) q = input() cut = [0] topset = set([q[0]]) for i in range(1, len(q)): if len(cut) == k: break if q[i] not in topset: cut.append(i) topset.add(q[i]) if len(cut) < k: print('NO') else: print('YES') for i in range(k-1): print(q[cut[i]:cut[i+1]])...
k = int(input()) q = input() cut = [0] topset = set([q[0]]) for i in range(1, len(q)): if len(cut) == k: break if q[i] not in topset: cut.append(i) topset.add(q[i]) if len(cut) < k: print('NO') else: print('YES') for i in range(k - 1): print(q[cut[i]:cut[i + 1]]) ...
def new(): return {} def to_map(raw_metadata): return {tuple(md['breadcrumb']): md['metadata'] for md in raw_metadata} def to_list(compiled_metadata): return [{'breadcrumb': k, 'metadata': v} for k, v in compiled_metadata.items()] def delete(compiled_metadata, breadcrumb, k): del compiled_metadata[br...
def new(): return {} def to_map(raw_metadata): return {tuple(md['breadcrumb']): md['metadata'] for md in raw_metadata} def to_list(compiled_metadata): return [{'breadcrumb': k, 'metadata': v} for (k, v) in compiled_metadata.items()] def delete(compiled_metadata, breadcrumb, k): del compiled_metadata[...
"""Top-level package for ICBC Test to Anki.""" __author__ = """genzj""" __email__ = 'zj0512@gmail.com' __version__ = '0.1.0'
"""Top-level package for ICBC Test to Anki.""" __author__ = 'genzj' __email__ = 'zj0512@gmail.com' __version__ = '0.1.0'
batch_sizes = [4, 16, 128] def get_iterations(starting_size, batch_size, compute_budget): compute_budget_without_starting_size = compute_budget - starting_size iterations_without_start = compute_budget_without_starting_size // batch_size if (iterations_without_start) == 0: raise Exception(f"Compu...
batch_sizes = [4, 16, 128] def get_iterations(starting_size, batch_size, compute_budget): compute_budget_without_starting_size = compute_budget - starting_size iterations_without_start = compute_budget_without_starting_size // batch_size if iterations_without_start == 0: raise exception(f'Compute b...
# noinspection PyUnusedLocal # skus = unicode string def checkout(skus): """ I am assuming products are sepereted by commas and their quantity follows as an int sperated with an asterisk e.g. skus="A*3,B*1" the server tests will reveal the input string's format after the penalty I also have no...
def checkout(skus): """ I am assuming products are sepereted by commas and their quantity follows as an int sperated with an asterisk e.g. skus="A*3,B*1" the server tests will reveal the input string's format after the penalty I also have no information on the offers for multiple items """ ...
class DebuggerInterface: def is_debug_mode_enabled(self) -> bool: """Determines if debug mode is enabled for the application. The value is based on the configurations. Returns ------- bool True, if debug mode is enabled. """ raise NotImp...
class Debuggerinterface: def is_debug_mode_enabled(self) -> bool: """Determines if debug mode is enabled for the application. The value is based on the configurations. Returns ------- bool True, if debug mode is enabled. """ raise NotImp...
text = input("Text: ") letters = 0 for letter in text: if letter.isalpha(): letters += 1 # Assign words to 1 if user actually typed a word at the start but not a space words = 1 if (len(text) > 0 and text[0] != ' ') else 0 print(words) print(letters)
text = input('Text: ') letters = 0 for letter in text: if letter.isalpha(): letters += 1 words = 1 if len(text) > 0 and text[0] != ' ' else 0 print(words) print(letters)
class MonteCarlo(object): def __init__(self, board, **kwargs): # Takes an instance of a Board and optionally some keyword # arguments. Initializes the list of game states and the # statistics tables. milliseconds = kwargs.get('calculation_ms', 10) self.calculation_time_ms =...
class Montecarlo(object): def __init__(self, board, **kwargs): milliseconds = kwargs.get('calculation_ms', 10) self.calculation_time_ms = datatime.timedelta(milliseconds=milliseconds) self.max_moves = kwargs.get('max_moves', 10) self.board = board self.states = [] def u...
print("Welcome to Python") print("Welcome to Python") print("Welcome to Python") print("Welcome to Python") print("Welcome to Python")
print('Welcome to Python') print('Welcome to Python') print('Welcome to Python') print('Welcome to Python') print('Welcome to Python')
def test_win10(helpers): caps = {} caps['browserName'] = 'internet explorer' caps['platform'] = 'Windows 10' caps['version'] = '11' driver = helpers.start_driver(caps) helpers.validate_google(driver) def test_late_win7(helpers): caps = {} caps['browserName'] = 'internet explorer' c...
def test_win10(helpers): caps = {} caps['browserName'] = 'internet explorer' caps['platform'] = 'Windows 10' caps['version'] = '11' driver = helpers.start_driver(caps) helpers.validate_google(driver) def test_late_win7(helpers): caps = {} caps['browserName'] = 'internet explorer' ca...
#The provided code stub reads two integers from STDIN, a and b. Add code to print three lines where: #1.The first line contains the sum of the two numbers. #2.The second line contains the difference of the two numbers (first - second). #3.The third line contains the product of the two numbers. #code a=int(raw_input())...
a = int(raw_input()) b = int(raw_input()) print(a + b) print(a - b) print(a * b)
""" These routines only appear to be used by the peering_speed tests. """ def gen_args(name, args): """ Called from argify to generate arguments. """ usage = [""] usage += [name + ':'] usage += \ [" {key}: <{usage}> ({default})".format( key=key, usage=_usage, default=defau...
""" These routines only appear to be used by the peering_speed tests. """ def gen_args(name, args): """ Called from argify to generate arguments. """ usage = [''] usage += [name + ':'] usage += [' {key}: <{usage}> ({default})'.format(key=key, usage=_usage, default=default) for (key, _usage, ...
def route_allow_all(*args, **kwargs): return args, kwargs def route_defarg(reqarg, defarg=1): return defarg def route_json_dict(jsondict, dbg=False): pass def route_validator(alphanum, filepath, key, novalidation): """ put descriptive docstring here """ pass def route...
def route_allow_all(*args, **kwargs): return (args, kwargs) def route_defarg(reqarg, defarg=1): return defarg def route_json_dict(jsondict, dbg=False): pass def route_validator(alphanum, filepath, key, novalidation): """ put descriptive docstring here """ pass def route_min(count): "...
class Jugador(): def __init__(self, nombre): self.nombre = nombre def __str__(self): return self.nombre def elegirTargetsDeLaPartida(self, partida): """Recibe el estado del juego, NO LO MODIFICA (dummy/copy/simulacion) Devuelve todos los turnos a jugar""" raise NotImplementedError
class Jugador: def __init__(self, nombre): self.nombre = nombre def __str__(self): return self.nombre def elegir_targets_de_la_partida(self, partida): """Recibe el estado del juego, NO LO MODIFICA (dummy/copy/simulacion) Devuelve todos los turnos a jugar""" raise NotImpl...
""" Problem Statement Given arrival and departure times of trains on a single day in a railway platform, find out the minimum number of platforms required so that no train has to wait for the other(s) to leave. In other words, when a train is about to arrive, at least one platform must be available to accommodate i...
""" Problem Statement Given arrival and departure times of trains on a single day in a railway platform, find out the minimum number of platforms required so that no train has to wait for the other(s) to leave. In other words, when a train is about to arrive, at least one platform must be available to accommodate i...
def main(): f = [line.rstrip("\n") for line in open("Data.txt")] map_ = [list(line) for line in f] info = [] for i in range(len(map_)): for j in range(len(map_[0])): if map_[i][j] == "v": info.append([i, j, "down", "left"]) map_[i][j] = "|" ...
def main(): f = [line.rstrip('\n') for line in open('Data.txt')] map_ = [list(line) for line in f] info = [] for i in range(len(map_)): for j in range(len(map_[0])): if map_[i][j] == 'v': info.append([i, j, 'down', 'left']) map_[i][j] = '|' ...
def escape_librtmp(value): if isinstance(value, bool): value = "1" if value else "0" if isinstance(value, int): value = str(value) # librtmp expects some characters to be escaped value = value.replace("\\", "\\5c") value = value.replace(" ", "\\20") value = value.replace('"', "\...
def escape_librtmp(value): if isinstance(value, bool): value = '1' if value else '0' if isinstance(value, int): value = str(value) value = value.replace('\\', '\\5c') value = value.replace(' ', '\\20') value = value.replace('"', '\\22') return value def stream_to_url(stream): ...
coordinates_E0E1E1 = ((125, 114), (126, 93), (126, 114), (126, 130), (126, 132), (127, 92), (127, 93), (127, 104), (127, 114), (127, 115), (127, 130), (128, 91), (128, 92), (128, 102), (128, 104), (128, 114), (128, 117), (128, 119), (128, 131), (128, 132), (129, 91), (129, 101), (129, 114), (129, 119), (129, 131), (1...
coordinates_e0_e1_e1 = ((125, 114), (126, 93), (126, 114), (126, 130), (126, 132), (127, 92), (127, 93), (127, 104), (127, 114), (127, 115), (127, 130), (128, 91), (128, 92), (128, 102), (128, 104), (128, 114), (128, 117), (128, 119), (128, 131), (128, 132), (129, 91), (129, 101), (129, 114), (129, 119), (129, 131), (1...
# Be sure to update these values if you decide to run this bot! APP_NAME = "Boston Snowbot" REPO_URL = "https://github.com/molly/snowbot" # Precipitation probability above which we will add snowfall to prediction PROBABILITY_THRESHOLD = 0 # Get these values from hitting this URL with your latitude and longitude: # h...
app_name = 'Boston Snowbot' repo_url = 'https://github.com/molly/snowbot' probability_threshold = 0 office = 'BOX' grid_x = 70 grid_y = 76 timezone = 'US/Eastern' enable_french_toast = True toast_gif_delay = 24 * 60 * 60 severe_toast_gif = 'https://t.co/Bs8UzBRswG'
# Given two lists of equal sizes, sum all the corresponding index elements and return a new list. # Lis1 = [1,2,3,4,5] List2=[6,7,8,9,0] # new list output = [7, 9, 11,13,5] def sum_index_elements(alist, blist): new_list = [] for a in range(len(alist)): new_list.append(alist[a]+blist[a]) return new_list t...
def sum_index_elements(alist, blist): new_list = [] for a in range(len(alist)): new_list.append(alist[a] + blist[a]) return new_list test_code = sum_index_elements([2, 3, 1, 4, 2], [1, 4, 2, 4, 2]) print(test_code)
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
"""Bazel rules for building and packaging OCPDiag tests""" load('@rules_pkg//:pkg.bzl', 'pkg_tar') load('@rules_pkg//:providers.bzl', 'PackageFilegroupInfo', 'PackageFilesInfo', 'PackageSymlinkInfo') load('@bazel_skylib//lib:paths.bzl', 'paths') load('@rules_proto//proto:defs.bzl', 'ProtoInfo') _ocpdiag_workspace = 'oc...
class LinearCongruentialGenerator: mul = 1103515245 # a, 0 < a < m inc = 12345 # c, 0 <= c < m mod = 2 ** 31 # m, 0 < m def __init__(self, seed): self.seed_ = seed % self.mod # X[0], 0 <= X[0] < m def rand(self): # X[n + 1] = (a * X[n] + c) mod m self.seed_ = (s...
class Linearcongruentialgenerator: mul = 1103515245 inc = 12345 mod = 2 ** 31 def __init__(self, seed): self.seed_ = seed % self.mod def rand(self): self.seed_ = (self.seed_ * self.mul + self.inc) % self.mod return self.seed_
#Search in a 2D Matrix class Solution(object): def searchMatrix(self, matrix, target): if not len(matrix) or not len(matrix[0]): return False m, n = len(matrix) , len(matrix[0]) #Start adaptive search from left bottom corner x,y = m-1 , 0 ...
class Solution(object): def search_matrix(self, matrix, target): if not len(matrix) or not len(matrix[0]): return False (m, n) = (len(matrix), len(matrix[0])) (x, y) = (m - 1, 0) while True: if x < 0 or y >= n: break current = matr...
"""This problem was asked by Pinterest. Given a binary tree, write a function to determine whether the tree is a mirror image of itself. Two trees are a mirror image if their root values are the same and the left subtree is a mirror image of the right subtree. """
"""This problem was asked by Pinterest. Given a binary tree, write a function to determine whether the tree is a mirror image of itself. Two trees are a mirror image if their root values are the same and the left subtree is a mirror image of the right subtree. """
alphabet = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", ] direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:...
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n") text = input('Type your message:\n').lower() shift = int(input('Type the shift number:\n')) def encryp...
class Solution: def checkInclusion(self, s1: str, s2: str) -> bool: w_size = len(s1) n = len(s2) if n<w_size: return False rem_counts = collections.defaultdict(int) for i in range(w_size): if rem_counts[s1[i]] == -1: ...
class Solution: def check_inclusion(self, s1: str, s2: str) -> bool: w_size = len(s1) n = len(s2) if n < w_size: return False rem_counts = collections.defaultdict(int) for i in range(w_size): if rem_counts[s1[i]] == -1: rem_counts.pop(...
class Product(object): def __init__(self, name, base_price): self.name = name self.base_price = base_price def get_price(self, item_quantities): return item_quantities[self.name] * self.base_price class DiscountedProduct(Product): def __init__(self, name, base_pric...
class Product(object): def __init__(self, name, base_price): self.name = name self.base_price = base_price def get_price(self, item_quantities): return item_quantities[self.name] * self.base_price class Discountedproduct(Product): def __init__(self, name, base_price, offers=()): ...
def lengthN(n, cache): count = 1 while n > 1: if len(cache) >= n: count = count + cache[n-1] break if n % 2: n = 3*n + 1 else: n /= 2 count += 1 cache[int(n)-1] = count return count, cache if __name__ == '__main__': n...
def length_n(n, cache): count = 1 while n > 1: if len(cache) >= n: count = count + cache[n - 1] break if n % 2: n = 3 * n + 1 else: n /= 2 count += 1 cache[int(n) - 1] = count return (count, cache) if __name__ == '__main__':...
class Solution: def permuteUnique(self, nums: List[int]) -> List[List[int]]: results = [] def Combination(permutation, counter): if len(permutation) == len(nums): results.append(list(permutation)) return for num in counter: if ...
class Solution: def permute_unique(self, nums: List[int]) -> List[List[int]]: results = [] def combination(permutation, counter): if len(permutation) == len(nums): results.append(list(permutation)) return for num in counter: i...
#using this for test values for config class TestConfig: host = "irc.rizon.net" port = 6667 nickname = "testNickName8462" username = "testUserName8462" hostname = "testHostName8462" servername = "testServerName8462" realname = "testRealName8462"
class Testconfig: host = 'irc.rizon.net' port = 6667 nickname = 'testNickName8462' username = 'testUserName8462' hostname = 'testHostName8462' servername = 'testServerName8462' realname = 'testRealName8462'
# Copyright (C) 2020 The Dagger Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
"""Macros for building compiler tests.""" def compiler_test(name, size='large', compiler_deps=None, **kwargs): """Generates a java_test that tests java compilation with the given compiler deps. This macro separates the compiler dependencies from the test dependencies to avoid 1-version violations. For exa...
load("@rules_python//python:defs.bzl", "py_test") load("@bazel_skylib//rules:write_file.bzl", "write_file") # End to end "Shell" test that a breakpoint can resolve a location # Consider just allow running a breakpoint without crashing # It does the following # 1. Take the (compiled) application and boot up a sim match...
load('@rules_python//python:defs.bzl', 'py_test') load('@bazel_skylib//rules:write_file.bzl', 'write_file') def ios_lldb_breakpoint_po_test(name, application, set_cmd, variable, sdk, device, expected_value=None, lldbinit=None, **kwargs): test_spec = struct(variable_name=variable, substrs=['variable_result: ' + var...
""" Tests for qal.common :copyright: Copyright 2010-2014 by Nicklas Boerjesson :license: BSD, see LICENSE for details. """
""" Tests for qal.common :copyright: Copyright 2010-2014 by Nicklas Boerjesson :license: BSD, see LICENSE for details. """
phonebook = { "John" : 938477566, "Jack" : 938377264, "Jill" : 947662781 } # Add "Jake" to the phonebook with the phone number 938273443, and remove Jill from the phonebook phonebook["Jake"] = 938273443 del phonebook["Jill"] # testing code if "Jake" in phonebook: print("Jake is listed in the phonebook...
phonebook = {'John': 938477566, 'Jack': 938377264, 'Jill': 947662781} phonebook['Jake'] = 938273443 del phonebook['Jill'] if 'Jake' in phonebook: print('Jake is listed in the phonebook.') if 'Jill' not in phonebook: print('Jill is not listed in the phonebook.') for (name, number) in phonebook.items(): print...
""" Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree. Example 1: Input: 1 / \ 0 2 L = 1 R...
""" Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree. Example 1: Input: 1 / 0 2 L = 1 R =...