content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
#Simple base for the agent class Agent: def __init__(self): pass def select(self,game_state): raise NotImplementedError()
class Agent: def __init__(self): pass def select(self, game_state): raise not_implemented_error()
# Example of a singleton design pattern class single: # instance is a class variable/attribute and not # an instance variable/attribute instance = None def getinstance(): if single.instance is None: # This creates a new object, and hence calls __init__ # single() ...
class Single: instance = None def getinstance(): if single.instance is None: return single() return single.instance def __init__(self): if single.instance is not None: raise exception('this is single') else: single.instance = self s = sin...
def is_palindrome(n): s = str(n) return s == s[::-1] lower, upper = 99, 999 largest = -1 for i in range(upper, lower, -1): for j in range(i, lower, -1): p = i * j if p > largest and is_palindrome(p): largest = p print(largest)
def is_palindrome(n): s = str(n) return s == s[::-1] (lower, upper) = (99, 999) largest = -1 for i in range(upper, lower, -1): for j in range(i, lower, -1): p = i * j if p > largest and is_palindrome(p): largest = p print(largest)
def nthroot(x,n): return x**(1/n) a=int(input("Enter Main Number\n")) b=int(input("Enter Root Number\n")) print("Square Root of",a,"is : ",a**(1/2)) print(b,"th Root of",a,"is : ",nthroot(a,b))
def nthroot(x, n): return x ** (1 / n) a = int(input('Enter Main Number\n')) b = int(input('Enter Root Number\n')) print('Square Root of', a, 'is : ', a ** (1 / 2)) print(b, 'th Root of', a, 'is : ', nthroot(a, b))
#!/usr/bin/env python3 n, a, b = map(int, input().split()) def p(a):print(a);exit() if a > b:p(0) elif n < 2:p(0+(a == b)) else: p((b-a) * (n-2) + 1)
(n, a, b) = map(int, input().split()) def p(a): print(a) exit() if a > b: p(0) elif n < 2: p(0 + (a == b)) else: p((b - a) * (n - 2) + 1)
class MODEL_PIPELINE: def __init__(self, config=None, data_pipeline=None): self._config = config self.compile() def compile(self): return def train(self): return def train_step(self, x, y): return def summary(self): return def callbac...
class Model_Pipeline: def __init__(self, config=None, data_pipeline=None): self._config = config self.compile() def compile(self): return def train(self): return def train_step(self, x, y): return def summary(self): return def callback(self):...
class Solution: def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int: s = 0 for i in range(len(points) - 1): s += max(abs((points[i][0] - points[i+1][0])), abs((points[i][1] - points[i+1][1]))) return s
class Solution: def min_time_to_visit_all_points(self, points: List[List[int]]) -> int: s = 0 for i in range(len(points) - 1): s += max(abs(points[i][0] - points[i + 1][0]), abs(points[i][1] - points[i + 1][1])) return s
# # # # # # # # Define the validate function # # # # # # # def validate(hand): # # # # # # # if hand < 0 or hand > 2: # # # # # # # return False # # # # # # # else: # # # # # # # return True # # # # # # # # # # # # # # # Add control flow based on the value hand # # # # # # # # # # # # # # # ...
class Menuitem: def info(self): return self.name + ': $' + str(self.price) def get_total_price(self, count): total_price = count * self.price return total_price return 'Your total is $' + str(result) menu_item1 = menu_item() menu_item1.name = 'Sandwich' menu_item1.price = 5 res...
## Ejercicio 01 n = int(input(":")) ## Numeros con los que se va a trabajar k = int(input(":")) ## Divisor num_total = 0 for i in range(n): num = int(input("::")) ## Leemos los 'n' numeros if num % k == 0: num_total += 1 print(num_total)
n = int(input(':')) k = int(input(':')) num_total = 0 for i in range(n): num = int(input('::')) if num % k == 0: num_total += 1 print(num_total)
# Question 4 - Find repeated number # Asmit De # 04/28/2017 ######################################## Solution 1 ######################################### # Input n n = int(input('Enter n: ')) # Enter list data user_input = input('Enter the list: ') nums = [int(n) for n in user_input.split()] # Initiali...
n = int(input('Enter n: ')) user_input = input('Enter the list: ') nums = [int(n) for n in user_input.split()] present = [False] * n for e in nums: if present[e - 1]: print('The repeated number is:', e) break else: present[e - 1] = True n = int(input('Enter n: ')) user_input = input('Ent...
row = 4 for i in range(5): for k in range(i): print("*",end = " ") for k in range(2*(row - i)): print(" ",end = " ") for k in range(i): print("*",end = " ") print()
row = 4 for i in range(5): for k in range(i): print('*', end=' ') for k in range(2 * (row - i)): print(' ', end=' ') for k in range(i): print('*', end=' ') print()
coco_params = { 'model_dir': '/home/dan/work/light-head-rcnn/models/run00/', 'train_dataset_path': '/mnt/datasets/COCO/train_shards/', 'val_dataset_path': '/mnt/datasets/COCO/val_shards/', 'pretrained_checkpoint': 'pretrained/resnet_v1_50.ckpt', 'num_classes': 80, # IMAGE SIZES: # an int...
coco_params = {'model_dir': '/home/dan/work/light-head-rcnn/models/run00/', 'train_dataset_path': '/mnt/datasets/COCO/train_shards/', 'val_dataset_path': '/mnt/datasets/COCO/val_shards/', 'pretrained_checkpoint': 'pretrained/resnet_v1_50.ckpt', 'num_classes': 80, 'evaluation_min_dimension': 800, 'evaluation_max_dimensi...
{ "targets": [ { "target_name": "binding_png", "sources": [ "image/node/c/binding_png.cpp" ] } ] }
{'targets': [{'target_name': 'binding_png', 'sources': ['image/node/c/binding_png.cpp']}]}
class PredictionInstances(object): def __init__(self, true_labels, predicted_labels, predicted_probs): self.true_labels = true_labels self.predicted_labels = predicted_labels self.predicted_probs = predicted_probs
class Predictioninstances(object): def __init__(self, true_labels, predicted_labels, predicted_probs): self.true_labels = true_labels self.predicted_labels = predicted_labels self.predicted_probs = predicted_probs
''' A Range Module is a module that tracks ranges of numbers. Your task is to design and implement the following interfaces in an efficient manner. addRange(int left, int right) Adds the half-open interval [left, right), tracking every real number in that interval. Adding an interval that partially overlaps with curre...
""" A Range Module is a module that tracks ranges of numbers. Your task is to design and implement the following interfaces in an efficient manner. addRange(int left, int right) Adds the half-open interval [left, right), tracking every real number in that interval. Adding an interval that partially overlaps with curre...
# Making a cup of tea in Python code switchOnKettle() getCup() addTeaBag() # If the user takes sugar, add it if takesSugar == True: addSugar() # Wait for kettle to boil while kettleBoiled == False: useSnapChat() pourWaterIntoCup() # Let it brew for 3 minutes. We could change 3 if we wanted to brewTime(3) ...
switch_on_kettle() get_cup() add_tea_bag() if takesSugar == True: add_sugar() while kettleBoiled == False: use_snap_chat() pour_water_into_cup() brew_time(3) dispose_tea_bag() if takesMilk == True: add_milk() drink_tea()
#!/usr/bin/env python3 #encoding=utf-8 #--------------------------------------------- # Usage: python3 6-access2.py # Description: class decorator with private and public attribute declaration #--------------------------------------------- ''' File 6-access2.py (3.X + 2.X) Class decorator with Private and Public at...
""" File 6-access2.py (3.X + 2.X) Class decorator with Private and Public attribute declarations. Controls external access to attributes stored on an instance, or Inherited by it from its classes. Private declares attribute names that cannot be fetched or assigned outside the decorated class, and Public declares all th...
ETCD_URLS = { "3.4.3": { "linux_amd64": ( "https://github.com/etcd-io/etcd/releases/download/v3.4.3/etcd-v3.4.3-linux-amd64.tar.gz", "6c642b723a86941b99753dff6c00b26d3b033209b15ee33325dc8e7f4cd68f07", ), "mac_amd64": ( "https://github.com/etcd-io/etcd/rele...
etcd_urls = {'3.4.3': {'linux_amd64': ('https://github.com/etcd-io/etcd/releases/download/v3.4.3/etcd-v3.4.3-linux-amd64.tar.gz', '6c642b723a86941b99753dff6c00b26d3b033209b15ee33325dc8e7f4cd68f07'), 'mac_amd64': ('https://github.com/etcd-io/etcd/releases/download/v3.4.3/etcd-v3.4.3-darwin-amd64.zip', '9e530371ac2a0b10e...
def isbuiltin(obj: object): return ( obj is None or obj is True or obj is False or isinstance(obj, (int, float, bytes, complex, str)) )
def isbuiltin(obj: object): return obj is None or obj is True or obj is False or isinstance(obj, (int, float, bytes, complex, str))
a=10 b=20 print("Swap the two given numbers a=10 and b=20") c=a a=b b=c print("After swapping the value of a=",a,"b=",b)
a = 10 b = 20 print('Swap the two given numbers a=10 and b=20') c = a a = b b = c print('After swapping the value of a=', a, 'b=', b)
'''Defines the `java_import` rule. ''' load("//java:providers/JavaDependencyInfo.bzl", "JavaDependencyInfo") load("//java:common/providers.bzl", "jar_list_java_dependency_info") def _java_import_impl(ctx): return [ jar_list_java_dependency_info(ctx.files.jars), JavaInfo( # The 0-th JAR...
"""Defines the `java_import` rule. """ load('//java:providers/JavaDependencyInfo.bzl', 'JavaDependencyInfo') load('//java:common/providers.bzl', 'jar_list_java_dependency_info') def _java_import_impl(ctx): return [jar_list_java_dependency_info(ctx.files.jars), java_info(output_jar=ctx.files.jars[0], compile_jar=ct...
Team1=input("enter a team name : ") Team2=input("enter 2 team name : ") Team1_member1,Team1_member2,Team2_member1,Team2_member2=input('first team enter first member name : '),input('first team enter second member name : '),input('second team enter first member name : '),input('second team enter second member name : ') ...
team1 = input('enter a team name : ') team2 = input('enter 2 team name : ') (team1_member1, team1_member2, team2_member1, team2_member2) = (input('first team enter first member name : '), input('first team enter second member name : '), input('second team enter first member name : '), input('second team enter second me...
BOGUS_BENCHMARK_NAME = "bogus" DUMMY_BENCHMARK_NAME = "dummy" DUMMY_PREDICTION_ID = "lewtun/benchmarks-dummy-prediction" DUMMY_EVALUATION_ID = "lewtun/benchmarks-dummy-evaluation" DUMMY_MODEL_ID = "lewtun/benchmarks-dummy-model"
bogus_benchmark_name = 'bogus' dummy_benchmark_name = 'dummy' dummy_prediction_id = 'lewtun/benchmarks-dummy-prediction' dummy_evaluation_id = 'lewtun/benchmarks-dummy-evaluation' dummy_model_id = 'lewtun/benchmarks-dummy-model'
def part1(): with open('in.txt') as inp: valid_pass_count = 0 for line in inp.readlines(): line = line.strip() parts = line.split(' ') nr_of_repetitions_min = int(parts[0].split('-')[0]) nr_of_repetitions_max = int(parts[0].split('-')[1]) l...
def part1(): with open('in.txt') as inp: valid_pass_count = 0 for line in inp.readlines(): line = line.strip() parts = line.split(' ') nr_of_repetitions_min = int(parts[0].split('-')[0]) nr_of_repetitions_max = int(parts[0].split('-')[1]) l...
#!/usr/bin/env python3 # Any line that starts with a "#" is also known as a comment, # these lines are ignored by the python interpreter even if # they contain code. The very first line is called a Shebang line, # it is used to tell the system which interpreter to # use(python2, python3, bash, etc). # Description:...
print('Hello world')
n = 40 print("Fibonachi of", n," with python is ",end='') fib = [0, 1] [fib.append(fib[x - 1] + fib[x - 2]) for x in range(2, n)] print(fib[n-1])
n = 40 print('Fibonachi of', n, ' with python is ', end='') fib = [0, 1] [fib.append(fib[x - 1] + fib[x - 2]) for x in range(2, n)] print(fib[n - 1])
class Packer: def pack(self): def dig_pack(obj): if isinstance(obj, list) or isinstance(obj, tuple): tmplist = [] for m in obj: if 'pack' in dir(m): tmplist.append(m.pack()) else: ...
class Packer: def pack(self): def dig_pack(obj): if isinstance(obj, list) or isinstance(obj, tuple): tmplist = [] for m in obj: if 'pack' in dir(m): tmplist.append(m.pack()) else: ...
t = int(input()) def smallfact(n): if n==1: return 1 return n*smallfact(n-1) for i in range(t): n=int(input()) print(smallfact(n))
t = int(input()) def smallfact(n): if n == 1: return 1 return n * smallfact(n - 1) for i in range(t): n = int(input()) print(smallfact(n))
### naive DP class Solution: def rob(self, nums: List[int]) -> int: if not nums: return 0 if len(nums) == 1: return nums[0] if len(nums) > 1: opt = [nums[0]] checker = True if nums[1] > nums[0]: opt.append(nums[1]) ...
class Solution: def rob(self, nums: List[int]) -> int: if not nums: return 0 if len(nums) == 1: return nums[0] if len(nums) > 1: opt = [nums[0]] checker = True if nums[1] > nums[0]: opt.append(nums[1]) e...
def bsearch(power, string, upper, lower): res = 0 for i in range(power): if string[i] == upper: res += 2 ** ((power-1)-i) return res with open("input.txt", 'r') as f: idxs = [] maxidx = 0 for l in f.readlines(): line = l.replace("\n", "") row = bs...
def bsearch(power, string, upper, lower): res = 0 for i in range(power): if string[i] == upper: res += 2 ** (power - 1 - i) return res with open('input.txt', 'r') as f: idxs = [] maxidx = 0 for l in f.readlines(): line = l.replace('\n', '') row = bsearch(7, li...
val = 1 print(val) while val % 6 != 0: val += 1 print(val)
val = 1 print(val) while val % 6 != 0: val += 1 print(val)
class Solution: def isPalindrome(self, s: str) -> bool: s = ''.join(ch for ch in s if ch.isalnum()).lower() return s == s[::-1] s = Solution() print(s.isPalindrome("abc Ba"))
class Solution: def is_palindrome(self, s: str) -> bool: s = ''.join((ch for ch in s if ch.isalnum())).lower() return s == s[::-1] s = solution() print(s.isPalindrome('abc Ba'))
class TaxaException(Exception): pass class MissingKey(TaxaException): pass class InvalidKey(TaxaException): pass class InvalidRequest(TaxaException): pass class TaxaClientException(TaxaException): pass class AttestationException(TaxaException): pass class InvalidAttestationStatus(Attestati...
class Taxaexception(Exception): pass class Missingkey(TaxaException): pass class Invalidkey(TaxaException): pass class Invalidrequest(TaxaException): pass class Taxaclientexception(TaxaException): pass class Attestationexception(TaxaException): pass class Invalidattestationstatus(Attestati...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def cmn(n, m): if m == n or m == 0: return 1 if m != 1: return cmn(n - 1, m) + cmn(n - 1, m - 1) else: return n if __name__ == '__main__': print(cmn(9, 4))
def cmn(n, m): if m == n or m == 0: return 1 if m != 1: return cmn(n - 1, m) + cmn(n - 1, m - 1) else: return n if __name__ == '__main__': print(cmn(9, 4))
text = open('blankText.txt', 'r+') # create a file that we car write text to for i in range(0,11): text.write(str(i)+30*' ') text.write('\n') text.write('The End') text.seek(0) text.write('The Start') # write a sequence of numbers each on a new line # write a note at the start and the end of sequence
text = open('blankText.txt', 'r+') for i in range(0, 11): text.write(str(i) + 30 * ' ') text.write('\n') text.write('The End') text.seek(0) text.write('The Start')
word_list=['awkward', 'jazz', 'fluff', 'banjo', 'buffalo', 'cycle', 'haphazard', 'injury', 'gullible', 'fiance', 'gelatin', 'jaundice', 'envy', 'jelly', 'jukebox', 'jigsaw', 'ivory', 'kangaroo', 'lymph', 'mnemonic', 'monotonous', 'pneumonia', 'queue', 'syndrome', 'rickshaw', 'vixen', 'fabulous', 'magnanimous', 'witchcr...
word_list = ['awkward', 'jazz', 'fluff', 'banjo', 'buffalo', 'cycle', 'haphazard', 'injury', 'gullible', 'fiance', 'gelatin', 'jaundice', 'envy', 'jelly', 'jukebox', 'jigsaw', 'ivory', 'kangaroo', 'lymph', 'mnemonic', 'monotonous', 'pneumonia', 'queue', 'syndrome', 'rickshaw', 'vixen', 'fabulous', 'magnanimous', 'witch...
#!/usr/bin/env python3 def print_model_info(model, text_name): layer_names = model.getLayerNames() print('{0}.getLayerNames() ='.format(text_name), layer_names) output_layer_indices = model.getUnconnectedOutLayers() print('{0}.getUnconnectedOutLayers() ='.format(text_name), output_layer_indices) o...
def print_model_info(model, text_name): layer_names = model.getLayerNames() print('{0}.getLayerNames() ='.format(text_name), layer_names) output_layer_indices = model.getUnconnectedOutLayers() print('{0}.getUnconnectedOutLayers() ='.format(text_name), output_layer_indices) output_layer_names = [laye...
# Eoin Lees # This program reads in a students percentage result # and prints out the corresponding grade percentage = float(input("Enter the percentage: ")) if percentage < 0 or percentage > 100: print("Please enter a number between 0 and 100") elif percentage < 40: # Less than 40 print("Fail") elif percenta...
percentage = float(input('Enter the percentage: ')) if percentage < 0 or percentage > 100: print('Please enter a number between 0 and 100') elif percentage < 40: print('Fail') elif percentage < 50: print('Pass') elif percentage < 60: print('Merit 1') elif percentage < 70: print('Merit 2') else: ...
class TokenError(Exception): pass class TokenHandlerNotFound(TokenError): def __init__(self, action, *args, **kwargs): super(TokenHandlerNotFound, self).__init__(*args, **kwargs) self.action = action class UnsupportedSanctionHandlerKind(Exception): pass
class Tokenerror(Exception): pass class Tokenhandlernotfound(TokenError): def __init__(self, action, *args, **kwargs): super(TokenHandlerNotFound, self).__init__(*args, **kwargs) self.action = action class Unsupportedsanctionhandlerkind(Exception): pass
''' Override the default characterise config parameters by putting them in here. e.g.: config.doWrite = False ''' # doWrite needs to be set to True as charImage and calibrate use the postISR # images. config.doWrite = True config.doOverscan = False config.doDefect = False config.doAssembleIsrExposures = False config....
""" Override the default characterise config parameters by putting them in here. e.g.: config.doWrite = False """ config.doWrite = True config.doOverscan = False config.doDefect = False config.doAssembleIsrExposures = False config.doBias = False config.doDark = False config.doFlat = False config.doSaturationInterpolati...
print(0) print(-0) print(1) print(-1) print(type(1)) print(int(1))
print(0) print(-0) print(1) print(-1) print(type(1)) print(int(1))
def main(): OnFwd(OUT_A, 100) OnRev(OUT_B, 100) while 1: pass
def main(): on_fwd(OUT_A, 100) on_rev(OUT_B, 100) while 1: pass
a = 10 b = 60 if a > 50 and b < 50: print("True") elif a < 50 or b > 50: print("False")
a = 10 b = 60 if a > 50 and b < 50: print('True') elif a < 50 or b > 50: print('False')
#!/usr/bin/env python3 # https://www.hackerrank.com/challenges/dynamic-array n,q=map(int,input().split()) a=[list() for _ in range(n)] l = 0 for _ in range(q): t,x,y=map(int,input().split()) if t == 1: a[(x^l)%n].append(y) else: i=(x^l)%n l=a[i][y%len(a[i])] print(l)
(n, q) = map(int, input().split()) a = [list() for _ in range(n)] l = 0 for _ in range(q): (t, x, y) = map(int, input().split()) if t == 1: a[(x ^ l) % n].append(y) else: i = (x ^ l) % n l = a[i][y % len(a[i])] print(l)
class Node: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def getDiameter(root, diameter): if root is None: return 0, diameter left_height, diameter = getDiameter(root.left, diameter) right_height, diameter = ge...
class Node: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def get_diameter(root, diameter): if root is None: return (0, diameter) (left_height, diameter) = get_diameter(root.left, diameter) (right_height, diameter)...
def solve(array): nums = [0]*8001 counted = [False]*8001 tmp = 0 limit = 0 length = len(array) for i in range(length): nums[array[i]] += 1 if limit < array[i]: limit = array[i] for i in range(length-1): candidate = array[i] + array[i+1] j = i+1 ...
def solve(array): nums = [0] * 8001 counted = [False] * 8001 tmp = 0 limit = 0 length = len(array) for i in range(length): nums[array[i]] += 1 if limit < array[i]: limit = array[i] for i in range(length - 1): candidate = array[i] + array[i + 1] j =...
# Python program to illustrate destructor class Employee: # Initializing def __init__(self): print('Employee created.') # Deleting (Calling destructor) def __del__(self): print('Destructor called, Employee deleted.') obj = Employee() del obj
class Employee: def __init__(self): print('Employee created.') def __del__(self): print('Destructor called, Employee deleted.') obj = employee() del obj
n = int(input()) data=[] for i in range(0,n): x, y, h = map(int,input().split()) data.append((x,y,h)) data = sorted(data,key=lambda x:x[2],reverse=True) st_x, st_y, st_h = data[0] def get_search_area(x,y,n): area_list=[] for i in range(-n,n+1): for j in range(-n,n+1): ...
n = int(input()) data = [] for i in range(0, n): (x, y, h) = map(int, input().split()) data.append((x, y, h)) data = sorted(data, key=lambda x: x[2], reverse=True) (st_x, st_y, st_h) = data[0] def get_search_area(x, y, n): area_list = [] for i in range(-n, n + 1): for j in range(-n, n + 1): ...
def mod(n, d): while n >= d: n -= d return n def main(): print(2) print(3) limit = 10000 candidate = 5 while candidate < limit: factor = 1 prime = True while prime and factor * factor <= candidate: factor += 2 if mod(candidate, factor)...
def mod(n, d): while n >= d: n -= d return n def main(): print(2) print(3) limit = 10000 candidate = 5 while candidate < limit: factor = 1 prime = True while prime and factor * factor <= candidate: factor += 2 if mod(candidate, factor)...
users = {} status = "" def displayMenu(): status = input("Are you a registered user? y/n? Press q to quit") if status == 'y': oldUser() elif status == 'n': newUser() def newUser(): createLogin = input("Create login name: ") if createLogin in users: print("\nL...
users = {} status = '' def display_menu(): status = input('Are you a registered user? y/n? Press q to quit') if status == 'y': old_user() elif status == 'n': new_user() def new_user(): create_login = input('Create login name: ') if createLogin in users: print('\nLogin name ...
# Initialise VM, memory size vm = [] memsize = 0 # Build the VM from input with open('input08.txt') as f: for str in (line.strip() for line in f): vm.append(dict(op=str[:3], arg=int(str[4:]), addr=memsize, ord=0)) memsize += 1 def run(): # Initialise accumulator, instruction pointer, execution order acc = ip =...
vm = [] memsize = 0 with open('input08.txt') as f: for str in (line.strip() for line in f): vm.append(dict(op=str[:3], arg=int(str[4:]), addr=memsize, ord=0)) memsize += 1 def run(): acc = ip = ord = 0 for i in vm: i['ord'] = 0 while ip >= 0 and ip < memsize and (vm[ip]['ord'] =...
class Mux (): input_1 = [] input_2 = [] output = None def mux ( self, input_1,input_2, output): if (output == False): return input_1 else: return input_2
class Mux: input_1 = [] input_2 = [] output = None def mux(self, input_1, input_2, output): if output == False: return input_1 else: return input_2
class AwmExceptions(Exception): pass class AwmConnectionException(AwmExceptions): pass class AwmKeyException(AwmExceptions): pass
class Awmexceptions(Exception): pass class Awmconnectionexception(AwmExceptions): pass class Awmkeyexception(AwmExceptions): pass
class Solution: def addOneRow(self, root: TreeNode, v: int, d: int) -> TreeNode: if d == 1: return TreeNode(v, root, None) elif d == 2: root.left = TreeNode(v, root.left, None) root.right = TreeNode(v, None, root.right) else: if root.left: ...
class Solution: def add_one_row(self, root: TreeNode, v: int, d: int) -> TreeNode: if d == 1: return tree_node(v, root, None) elif d == 2: root.left = tree_node(v, root.left, None) root.right = tree_node(v, None, root.right) else: if root.left...
dp[i][j] = dp[i-1][j] + dp[i][j-1] dp[j] = dp[j - 1] + dp[j] class Solution(): def uniquePath(self, m, n): dp = [[1 for j in range(n)] for i in range(m)] for i in range(1, m): for j in range(1, n): dp[i][j] = dp[i][j - 1] + dp[i - 1][j] return dp[-1][-1] if m a...
dp[i][j] = dp[i - 1][j] + dp[i][j - 1] dp[j] = dp[j - 1] + dp[j] class Solution: def unique_path(self, m, n): dp = [[1 for j in range(n)] for i in range(m)] for i in range(1, m): for j in range(1, n): dp[i][j] = dp[i][j - 1] + dp[i - 1][j] return dp[-1][-1] if m...
''' from django.contrib import admin from article.models import Article, ArticleIndex class ArticleAdmin(admin.ModelAdmin): list_display = ('id', 'username', 'title', 'fid_func','cate_id_func', 'date_update', 'date_create') search_fields = ['title', 'content'] list_filter = ['date_create', 'username', 'fi...
""" from django.contrib import admin from article.models import Article, ArticleIndex class ArticleAdmin(admin.ModelAdmin): list_display = ('id', 'username', 'title', 'fid_func','cate_id_func', 'date_update', 'date_create') search_fields = ['title', 'content'] list_filter = ['date_create', 'username', 'fi...
# demo def f(x): if (x==1): return 'ok' else: return 'Error' result = f(2) if not(result == 'ok'): print('failure {}'.format(result))
def f(x): if x == 1: return 'ok' else: return 'Error' result = f(2) if not result == 'ok': print('failure {}'.format(result))
# encoding:utf-8 ''' @Author: catnlp @Email: wk_nlp@163.com @Time: 2018/8/13 19:41 '''
""" @Author: catnlp @Email: wk_nlp@163.com @Time: 2018/8/13 19:41 """
# initialize variables map_rocket = { "x" : 4, "y" : 4 } enemies = [ {"x" : 0, "y" : 1}, {"x" : 2, "y" : 3} ] hit_object = [] missed_object = [] rockets = 5 enemies_left = 2 # print first map print(" ", end=" ") for a in range(4): print(a, end=" ") print() for y in range(map_rocket["y"]): pri...
map_rocket = {'x': 4, 'y': 4} enemies = [{'x': 0, 'y': 1}, {'x': 2, 'y': 3}] hit_object = [] missed_object = [] rockets = 5 enemies_left = 2 print(' ', end=' ') for a in range(4): print(a, end=' ') print() for y in range(map_rocket['y']): print(y, end=' ') for x in range(map_rocket['x']): print('-',...
# # PySNMP MIB module CNT241-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CNT241-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:09:24 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:...
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, constraints_intersection, single_value_constraint, value_size_constraint, value_range_constraint) ...
def base_10_to_n(x, n): res = [] while x: res.append(str(x % n)) x //= n res.reverse() return "".join(res) def base_n_to_10(x, n): return int(str(x), n) def main(): x = 17 print(base_10_to_n(x, 9)) str_x = '21' print(int(str_x, 8)) print(base_n_to_10(18, 9)) ...
def base_10_to_n(x, n): res = [] while x: res.append(str(x % n)) x //= n res.reverse() return ''.join(res) def base_n_to_10(x, n): return int(str(x), n) def main(): x = 17 print(base_10_to_n(x, 9)) str_x = '21' print(int(str_x, 8)) print(base_n_to_10(18, 9)) if ...
def test_empty_contacts(client_l): rv = client_l.get('/api/contacts') assert len(rv.json['payload']['contacts']) == 0 def test_add_contact(client_l): rv = client_l.put('/api/contacts', json=dict()) assert rv.status_code == 400 rv = client_l.put('/api/contacts', json=dict(typ...
def test_empty_contacts(client_l): rv = client_l.get('/api/contacts') assert len(rv.json['payload']['contacts']) == 0 def test_add_contact(client_l): rv = client_l.put('/api/contacts', json=dict()) assert rv.status_code == 400 rv = client_l.put('/api/contacts', json=dict(type='email', enabled=True,...
class LinearAveragesService: def __init__(self, dataset): self.dataset = dataset def call(self): averages = {} counts = {} for row in self.dataset: # Get the class of this point cl = row.match averages.setdefault(cl, [0.0] * (len(row.data))...
class Linearaveragesservice: def __init__(self, dataset): self.dataset = dataset def call(self): averages = {} counts = {} for row in self.dataset: cl = row.match averages.setdefault(cl, [0.0] * len(row.data)) counts.setdefault(cl, 0) ...
star = '*' space = ' ' num_of_stars = 1 num_of_spaces = 9 for x in range(1, 11): for i in range(num_of_spaces): print(space, end='') for i in range(num_of_stars): print(star, end='') print() num_of_stars += 2 num_of_spaces -= 1 for x in range(5): for i in range(9): prin...
star = '*' space = ' ' num_of_stars = 1 num_of_spaces = 9 for x in range(1, 11): for i in range(num_of_spaces): print(space, end='') for i in range(num_of_stars): print(star, end='') print() num_of_stars += 2 num_of_spaces -= 1 for x in range(5): for i in range(9): print(...
# Created by MechAviv # Kinesis Introduction # Map ID :: 331002000 # School for the Gifted :: First Floor Corridor KINESIS = 1531000 JAY = 1531001 sm.setNpcOverrideBoxChat(JAY) sm.sendNext("#face9#Kinesis, you need to get back here as soon as you can. I've discovered something very interesting.") sm.setNpcOverrideBo...
kinesis = 1531000 jay = 1531001 sm.setNpcOverrideBoxChat(JAY) sm.sendNext("#face9#Kinesis, you need to get back here as soon as you can. I've discovered something very interesting.") sm.setNpcOverrideBoxChat(KINESIS) sm.sendSay('What is it? The last time you said that, it was a new torrent site for your Japanese cartoo...
class Solution: def CamelCase(self,N,Dictionary,Pattern): # Extract and store only the capital letters of each word arr = [] for i, word in enumerate(Dictionary) : arr.append("") for ch in word : if 65 <= ord(ch) <= 90 : arr[i] = a...
class Solution: def camel_case(self, N, Dictionary, Pattern): arr = [] for (i, word) in enumerate(Dictionary): arr.append('') for ch in word: if 65 <= ord(ch) <= 90: arr[i] = arr[i] + ch ans = [] for (i, short) in enumerate...
def lin_nonlin(x): k=0 l=0 m=1 for i in range(len(x)): k=0 if(m!=0): for j in range(len(x)): if (round((x[i]+x[j]),3)==round(x[i+j],3)): k=k+1 else: print("not linear") ...
def lin_nonlin(x): k = 0 l = 0 m = 1 for i in range(len(x)): k = 0 if m != 0: for j in range(len(x)): if round(x[i] + x[j], 3) == round(x[i + j], 3): k = k + 1 else: print('not linear') ...
# *- coding:utf8 *- ok = 200 error = 405 response_ok = 200 response_system_error = 404 response_error = 405 system_error = 404 none_error = 500
ok = 200 error = 405 response_ok = 200 response_system_error = 404 response_error = 405 system_error = 404 none_error = 500
def vogal (x): if x == "a" or x == "e" or x == "i" or x == "o" or x == "u" or x == "A" or x == "E" or x == "I" or x == "O" or x == "U": return True else: return False
def vogal(x): if x == 'a' or x == 'e' or x == 'i' or (x == 'o') or (x == 'u') or (x == 'A') or (x == 'E') or (x == 'I') or (x == 'O') or (x == 'U'): return True else: return False
# Simon McLain 2018-04-18 # https://stackoverflow.com/questions/7716331/calculating-arithmetic-mean-average-in-python # Calculate Means def mean(n): return float(sum(n)) / max(len(n), 1) with open("iris.csv","rb") as f: for line in f: a = line.split(',') n = (a[0], a[1], a[2], a[3])*1.0 x = mean(n) p...
def mean(n): return float(sum(n)) / max(len(n), 1) with open('iris.csv', 'rb') as f: for line in f: a = line.split(',') n = (a[0], a[1], a[2], a[3]) * 1.0 x = mean(n) print(x)
a = 7 if a > 6: print('a is a big') else: print('a is a small')
a = 7 if a > 6: print('a is a big') else: print('a is a small')
# Space: O(1) # Time: O(n) class Solution: def findMinArrowShots(self, points): length = len(points) if length == 0: return 0 if length == 1: return 1 points.sort(key=lambda x: x[1]) cur = points[0] res = 1 for i in range(length): if cur[1] <...
class Solution: def find_min_arrow_shots(self, points): length = len(points) if length == 0: return 0 if length == 1: return 1 points.sort(key=lambda x: x[1]) cur = points[0] res = 1 for i in range(length): if cur[1] < poin...
# Panel settings: /identity/<default>/roles PANEL_DASHBOARD = 'identity' PANEL_GROUP = 'default' PANEL = 'roles' # We don't want roles to be editable through the GUI. REMOVE_PANEL = True
panel_dashboard = 'identity' panel_group = 'default' panel = 'roles' remove_panel = True
class stk_options: def __init__(self,opts_str,_opts=None): if _opts != None: self._opts = _opts else: if type(opts_str) is dict: opts_str = self.hash_to_string(opts_str) self._opts = stk_build_options(opts_str,len(opts_str)) def ref(self): return self._opts def find_option(self,name): opt = stk_...
class Stk_Options: def __init__(self, opts_str, _opts=None): if _opts != None: self._opts = _opts else: if type(opts_str) is dict: opts_str = self.hash_to_string(opts_str) self._opts = stk_build_options(opts_str, len(opts_str)) def ref(self):...
# Contracts a Row in the following way: # # - Returns only the items "field=value" # in which the 'field' is in 'fields' # class RowReducer(object): def __init__(self, fields): self.fields = fields # It receives a list of "field=value" def reduce(self, row): result = [] for item...
class Rowreducer(object): def __init__(self, fields): self.fields = fields def reduce(self, row): result = [] for item in row: (field, value) = item.split('=') if field in self.fields: result.append(item) return result class Rowmatchexpa...
accumulated_amount = 0 saved_amount_enough = False command = input() while command != 'End': min_budget = float(input()) while accumulated_amount < min_budget: saved_amount = float(input()) accumulated_amount += saved_amount if accumulated_amount >= min_budget: saved_amount_...
accumulated_amount = 0 saved_amount_enough = False command = input() while command != 'End': min_budget = float(input()) while accumulated_amount < min_budget: saved_amount = float(input()) accumulated_amount += saved_amount if accumulated_amount >= min_budget: saved_amount_e...
_base_ = ["../grid_rcnn/grid_rcnn_r50_fpn_gn-head_2x_coco.py"] # learning policy lr_config = dict( policy="step", warmup="linear", warmup_iters=500, warmup_ratio=0.001, step=[8, 11] ) checkpoint_config = dict(interval=1) # runtime settings total_epochs = 12
_base_ = ['../grid_rcnn/grid_rcnn_r50_fpn_gn-head_2x_coco.py'] lr_config = dict(policy='step', warmup='linear', warmup_iters=500, warmup_ratio=0.001, step=[8, 11]) checkpoint_config = dict(interval=1) total_epochs = 12
# # PySNMP MIB module Juniper-ERX-System-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-ERX-System-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:51:45 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (d...
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, constraints_union, single_value_constraint, constraints_intersection, value_range_constraint) ...
r,c = map(int,(input().split())) a = [[0] * r for i in range(r)] for i in range(r): for j in range(r): a[i][j] = int(input()) print (a) col_r = 0 row_d = 0 col_l = -1 row_u = 0 i = 0 j = 0 def print_matrix(x,i,j): print (x[i][j], end=" ") while(j<=c-col_r): for j in range(j,(c-col_r)): pr...
(r, c) = map(int, input().split()) a = [[0] * r for i in range(r)] for i in range(r): for j in range(r): a[i][j] = int(input()) print(a) col_r = 0 row_d = 0 col_l = -1 row_u = 0 i = 0 j = 0 def print_matrix(x, i, j): print(x[i][j], end=' ') while j <= c - col_r: for j in range(j, c - col_r): ...
# Button is a simple tappable screen region. Each has: # - bounding rect ((X,Y,W,H) in pixels) # - a state # - image bitmap # - optional single callback function # - optional single value passed to callback # Default state for all buttons STATE_DEFAULT = 0 # State when the button is currently pressed STATE_PRESS...
state_default = 0 state_pressed = 1 state_available = 2 state_active = 3 state_1 = 4 state_2 = 5 state_3 = 6 state_4_good = 7 state_4_bad = 8 class Button(object): def __init__(self, ui, rect, **kwargs): self.ui = ui self.rect = rect self.imageFiles = {} self.bitmaps = {} s...
randomNumer = 1 def format_position(lat, long): pattern = "Lat{} - Long {}" formatPosition = "Lat{} - Long {}".format(lat, long) print(pattern) global randomNumer randomNumer = 4 return formatPosition def calculate_sum(number1, numberTwo): numeroThree = number1 + numberTwo + randomNumer ...
random_numer = 1 def format_position(lat, long): pattern = 'Lat{} - Long {}' format_position = 'Lat{} - Long {}'.format(lat, long) print(pattern) global randomNumer random_numer = 4 return formatPosition def calculate_sum(number1, numberTwo): numero_three = number1 + numberTwo + randomNume...
class YamoException(Exception): pass class ConfigError(YamoException): pass class IncompleteDocumentData(Exception): pass class ArgumentError(Exception): def __init__(self, obj, val): self.obj = obj self.val = val def __str__(self): return "Object {} encounters wrong...
class Yamoexception(Exception): pass class Configerror(YamoException): pass class Incompletedocumentdata(Exception): pass class Argumenterror(Exception): def __init__(self, obj, val): self.obj = obj self.val = val def __str__(self): return 'Object {} encounters wrong arg...
EXPECTED_RESPONSE_OF_JWKS_ENDPOINT = { 'keys': [ { 'kty': 'RSA', 'n': 'mRkQUiQ271QKj2_LeBefn4PIfHGLWyHGO8x76e' '29z4OzY7JLb6--924yT-IGOcevE3xFudFWL0LdXdAx8X-lxQ', 'e': 'AQAB', 'alg': 'RS256', 'kid': '02B1174234C29F8EFB69911438F597F...
expected_response_of_jwks_endpoint = {'keys': [{'kty': 'RSA', 'n': 'mRkQUiQ271QKj2_LeBefn4PIfHGLWyHGO8x76e29z4OzY7JLb6--924yT-IGOcevE3xFudFWL0LdXdAx8X-lxQ', 'e': 'AQAB', 'alg': 'RS256', 'kid': '02B1174234C29F8EFB69911438F597FF3FFEE6B7', 'use': 'sig'}]} response_of_jwks_endpoint_with_wrong_key = {'keys': [{'kty': 'RSA',...
def main(): data = [ { "category": "cat 1", "count": 2 } ] test(data) def test(data): for d in data: print(d)
def main(): data = [{'category': 'cat 1', 'count': 2}] test(data) def test(data): for d in data: print(d)
__author__ = "Paolo Bellagente, University of Brescia - Department of Information Engineering, Brescia (Italy)" __copyright__ = "" __credits__ = [] __license__ = "" __version__ = "ma-0.1" __email__ = "p.bellagente@unibs.it"
__author__ = 'Paolo Bellagente, University of Brescia - Department of Information Engineering, Brescia (Italy)' __copyright__ = '' __credits__ = [] __license__ = '' __version__ = 'ma-0.1' __email__ = 'p.bellagente@unibs.it'
# language identifiers that currently are not supported by python-babel. # see i18n.utils, Locale.parse() EXCLUDED_LANGUAGE_IDENTIFIERS = ["nso", "oci-es", "x-i18n", "st"] INCLUDED_LICENSE_VERSIONS = ["4.0", "3.0", "1.0"]
excluded_language_identifiers = ['nso', 'oci-es', 'x-i18n', 'st'] included_license_versions = ['4.0', '3.0', '1.0']
# Write your list_stats function here. def list_stats(values): if (len(values) % 2) == 0: # Median Calculation values.sort() mid = len(values)//2 median = (values[mid - 1] + values[mid])/2 # Mean Calculation mean = sum(values)/len(values) return median, mean else: # Median Calcul...
def list_stats(values): if len(values) % 2 == 0: values.sort() mid = len(values) // 2 median = (values[mid - 1] + values[mid]) / 2 mean = sum(values) / len(values) return (median, mean) else: values.sort() mid = len(values) // 2 median = values[mid...
color = input("Enter a Color: ") plural_noun = input("Enter a Plural Noun: ") celebrity = input("Enter a Celebrity: ") print("Roses are " + color) print(plural_noun + " are blue") print("I Love " + celebrity)
color = input('Enter a Color: ') plural_noun = input('Enter a Plural Noun: ') celebrity = input('Enter a Celebrity: ') print('Roses are ' + color) print(plural_noun + ' are blue') print('I Love ' + celebrity)
''' Created on Oct 21, 2016 @author: dj ''' def create_product_class(): class Product(): def __init__(self, name): self.name = name def make(self): print("Make a", self.name) return Product ProductA = create_product_class() ProductB = create_prod...
""" Created on Oct 21, 2016 @author: dj """ def create_product_class(): class Product: def __init__(self, name): self.name = name def make(self): print('Make a', self.name) return Product product_a = create_product_class() product_b = create_product_class() print('Pr...
#!/usr/bin/env python3 #A_1 -> <C> s=[ "#!/usr/bin/env python3", "#A_1 -> <C>", "s=[", " ", "#B_1(<C>) -> <A_2B_2>", "q=chr(34)", "def f(x):", " return q+x+q", "ss=[]", "a, b, c = 0, len(s), 11", "for x in [b-c,b-c+1]:", " ss.append(s[x])", "while a<b-1:", ...
s = ['#!/usr/bin/env python3', '#A_1 -> <C>', 's=[', ' ', '#B_1(<C>) -> <A_2B_2>', 'q=chr(34)', 'def f(x):', ' return q+x+q', 'ss=[]', 'a, b, c = 0, len(s), 11', 'for x in [b-c,b-c+1]:', ' ss.append(s[x])', 'while a<b-1:', ' ss.append(s[3]+f(s[a])+chr(44))', ' a += 1', 'ss.append(s[3]+f(s[a])+chr(93))', ...
# Action.py GOFORWARD = 0 TURNLEFT = 1 TURNRIGHT = 2 GRAB = 3 SHOOT = 4 CLIMB = 5
goforward = 0 turnleft = 1 turnright = 2 grab = 3 shoot = 4 climb = 5
def _simple_rule_impl(ctx): ctx.actions.write("out.txt", ctx.attr.content) simple_rule = rule( implementation = _simple_rule_impl, attrs = { "content": attr.string(), }, )
def _simple_rule_impl(ctx): ctx.actions.write('out.txt', ctx.attr.content) simple_rule = rule(implementation=_simple_rule_impl, attrs={'content': attr.string()})
class Behaviour: def __init__(self, entity): self.game = entity.game self.entity = entity self.complete_init() def complete_init(self): pass def process(self, dt): pass
class Behaviour: def __init__(self, entity): self.game = entity.game self.entity = entity self.complete_init() def complete_init(self): pass def process(self, dt): pass
class Queue: def __init__(self): self.queue =[] def isEmpty(self): if self.queue ==[]: print("Queue is Empty") else: print("Queue is not empty") def enqueue(self,element): self.queue.insert(0,element) def dequeue(self): sel...
class Queue: def __init__(self): self.queue = [] def is_empty(self): if self.queue == []: print('Queue is Empty') else: print('Queue is not empty') def enqueue(self, element): self.queue.insert(0, element) def dequeue(self): self.queue....
def square_list(int_list): for i in range(len(int_list)): int_list[i] = int_list[i] ** 2 return int_list if __name__ == "__main__": input_list = [1, 2, 3] assert square_list(input_list) == [1, 4, 9] input_list.append(4) # add 4 to end of previous list assert square_list(input_list) =...
def square_list(int_list): for i in range(len(int_list)): int_list[i] = int_list[i] ** 2 return int_list if __name__ == '__main__': input_list = [1, 2, 3] assert square_list(input_list) == [1, 4, 9] input_list.append(4) assert square_list(input_list) == [1, 4, 9, 16]
'''Problem statement : Write a function that counts the number of times a given int occurs in a Linked List Approach used: Iterative Time complexity: O(n)''' # Node class class Node: def __init__(self, data): self.data = data self.next = None # Linked list class class LinkedList: def __i...
"""Problem statement : Write a function that counts the number of times a given int occurs in a Linked List Approach used: Iterative Time complexity: O(n)""" class Node: def __init__(self, data): self.data = data self.next = None class Linkedlist: def __init__(self): self.head ...
#printLists.py num1 = 5 / 3 num2 = 5 / 4 num3 = 4 / 3 print("num1:", num1, "\nnum2:", num2, "\nnum3:", num3) print(num_label, num_list) print("\nOr we can print the ith element for each list for all j elements") num_list = [num1, num2, num3] num_label = ["num1:", "num2:", "num3:"] # len() provides the length of the li...
num1 = 5 / 3 num2 = 5 / 4 num3 = 4 / 3 print('num1:', num1, '\nnum2:', num2, '\nnum3:', num3) print(num_label, num_list) print('\nOr we can print the ith element for each list for all j elements') num_list = [num1, num2, num3] num_label = ['num1:', 'num2:', 'num3:'] j = len(num_list) for i in range(j): print(num_la...
# https://www.hackerrank.com/challenges/two-arrays/ # Complete the twoArrays function below. def twoArrays(k, A, B): A.sort() B.sort(reverse=True) C = zip(A, B) for c in C: if sum(c) < k: return 'NO' return 'YES'
def two_arrays(k, A, B): A.sort() B.sort(reverse=True) c = zip(A, B) for c in C: if sum(c) < k: return 'NO' return 'YES'
def square(x): y = x * x return y def sum_of_squares(x,y,z): a = square(x) b = square(y) c = square(z) return a+b+c a = -5 b = 2 c = 10 result = sum_of_squares(a,b,c) print(result) def most_common_letter(s): frequencies = count_freqs(s) return best_key(frequencies) def count_freqs(st...
def square(x): y = x * x return y def sum_of_squares(x, y, z): a = square(x) b = square(y) c = square(z) return a + b + c a = -5 b = 2 c = 10 result = sum_of_squares(a, b, c) print(result) def most_common_letter(s): frequencies = count_freqs(s) return best_key(frequencies) def count_f...
class Result: def __init__(self): self.w = 0 self.d = 0 self.l = 0 self.scores = [] self.times = [] self._quickmoves = 0 def __str__(self): value = "w: " + str(self.w) + " d:" + str(self.d) + " l: " + str(self.l) (x, y) = self.meanScore() ...
class Result: def __init__(self): self.w = 0 self.d = 0 self.l = 0 self.scores = [] self.times = [] self._quickmoves = 0 def __str__(self): value = 'w: ' + str(self.w) + ' d:' + str(self.d) + ' l: ' + str(self.l) (x, y) = self.meanScore() ...