content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
#!/usr/bin/env python3 n = int(input()) i = 1 while i < n + 1: if i % 3 == 0 and i % 5 != 0: print("fizz") elif i % 5 == 0 and i % 3 != 0: print("buzz") elif i % 5 == 0 and i % 3 == 0: print("fizz-buzz") else: print(i) i = i + 1
n = int(input()) i = 1 while i < n + 1: if i % 3 == 0 and i % 5 != 0: print('fizz') elif i % 5 == 0 and i % 3 != 0: print('buzz') elif i % 5 == 0 and i % 3 == 0: print('fizz-buzz') else: print(i) i = i + 1
def _printf(fh, fmt, *args): """Implementation of perl $fh->printf method""" global OS_ERROR, TRACEBACK, AUTODIE try: print(_format(fmt, *args), end='', file=fh) return True except Exception as _e: OS_ERROR = str(_e) if TRACEBACK: if isinstance(fmt,...
def _printf(fh, fmt, *args): """Implementation of perl $fh->printf method""" global OS_ERROR, TRACEBACK, AUTODIE try: print(_format(fmt, *args), end='', file=fh) return True except Exception as _e: os_error = str(_e) if TRACEBACK: if isinstance(fmt, str): ...
region = 'us-west-2' vpc = dict( source='./vpc' ) inst = dict( source='./inst', vpc_id='${module.vpc.vpc_id}' ) config = dict( provider=dict( aws=dict(region=region) ), module=dict( vpc=vpc, inst=inst ) )
region = 'us-west-2' vpc = dict(source='./vpc') inst = dict(source='./inst', vpc_id='${module.vpc.vpc_id}') config = dict(provider=dict(aws=dict(region=region)), module=dict(vpc=vpc, inst=inst))
{ "targets": [ { "target_name": "userid", "sources": [ '<!@(ls -1 src/*.cc)' ], "include_dirs": ["<!@(node -p \"require('node-addon-api').include\")"], "dependencies": ["<!(node -p \"require('node-addon-api').gyp\")"], "cflags!": [ "-fno-exceptions" ], "cflags_cc!": [ "-fno-exc...
{'targets': [{'target_name': 'userid', 'sources': ['<!@(ls -1 src/*.cc)'], 'include_dirs': ['<!@(node -p "require(\'node-addon-api\').include")'], 'dependencies': ['<!(node -p "require(\'node-addon-api\').gyp")'], 'cflags!': ['-fno-exceptions'], 'cflags_cc!': ['-fno-exceptions'], 'xcode_settings': {'GCC_ENABLE_CPP_EXCE...
""" Single linked list based on two pointer approach. """ class Node: def __init__(self, val=0, next=None): self.val = val self.next = next class slist: """ singly linked list class """ def __init__(self): self._first = None self._last = None def _build_a_no...
""" Single linked list based on two pointer approach. """ class Node: def __init__(self, val=0, next=None): self.val = val self.next = next class Slist: """ singly linked list class """ def __init__(self): self._first = None self._last = None def _build_a_no...
algorithm_defaults = { 'ERM': { 'train_loader': 'standard', 'uniform_over_groups': False, 'eval_loader': 'standard', 'randaugment_n': 2, # When running ERM + data augmentation }, 'groupDRO': { 'train_loader': 'standard', 'uniform_over_groups': True, ...
algorithm_defaults = {'ERM': {'train_loader': 'standard', 'uniform_over_groups': False, 'eval_loader': 'standard', 'randaugment_n': 2}, 'groupDRO': {'train_loader': 'standard', 'uniform_over_groups': True, 'distinct_groups': True, 'eval_loader': 'standard', 'group_dro_step_size': 0.01}, 'deepCORAL': {'train_loader': 'g...
"""django-anchors""" __version__ = '0.1.dev0' __license__ = 'BSD License' __author__ = 'Fantomas42' __email__ = 'fantomas42@gmail.com' __url__ = 'https://github.com/Fantomas42/django-anchors'
"""django-anchors""" __version__ = '0.1.dev0' __license__ = 'BSD License' __author__ = 'Fantomas42' __email__ = 'fantomas42@gmail.com' __url__ = 'https://github.com/Fantomas42/django-anchors'
def isinteger(s): return s.isdigit() or s[0] == '-' and s[1:].isdigit() def isfloat(x): s = x.partition(".") if s[1]=='.': if s[0]=='' or s[0]=='-': if s[2]=='' or s[2][0]=='-': return False else: return isinteger(s[2]) elif isinteger(...
def isinteger(s): return s.isdigit() or (s[0] == '-' and s[1:].isdigit()) def isfloat(x): s = x.partition('.') if s[1] == '.': if s[0] == '' or s[0] == '-': if s[2] == '' or s[2][0] == '-': return False else: return isinteger(s[2]) eli...
class Solution: def diameterOfBinaryTree(self, root: TreeNode) -> int: if not root: return 0 elif not root.right and not root.left: return 0 elif not root.right: return max(self.diameterOfBinaryTree(root.left), 1 + self.height(root.l...
class Solution: def diameter_of_binary_tree(self, root: TreeNode) -> int: if not root: return 0 elif not root.right and (not root.left): return 0 elif not root.right: return max(self.diameterOfBinaryTree(root.left), 1 + self.height(root.left)) eli...
# Copyright (C) 2019 FireEye, Inc. All Rights Reserved. """ english letter probabilities table from http://en.algoritmy.net/article/40379/Letter-frequency-English """ english_letter_probs_percent = [ ['a', 8.167], ['b', 1.492], ['c', 2.782], ['d', 4.253], ['e', 12.702], ['f', 2.228], ['g'...
""" english letter probabilities table from http://en.algoritmy.net/article/40379/Letter-frequency-English """ english_letter_probs_percent = [['a', 8.167], ['b', 1.492], ['c', 2.782], ['d', 4.253], ['e', 12.702], ['f', 2.228], ['g', 2.015], ['h', 6.094], ['i', 6.966], ['j', 0.153], ['k', 0.772], ['l', 4.025], ['m', 2...
arima = { 'order':[(2,1,0),(0,1,2),(1,1,1)], 'seasonal_order':[(0,0,0,0),(0,1,1,12)], 'trend':['n','c','t','ct'] } elasticnet = { 'alpha':[i/10 for i in range(1,101)], 'l1_ratio':[0,0.25,0.5,0.75,1], 'normalizer':['scale','minmax',None] } gbt = { 'max_depth':[2,3], 'n_estimators':[100,500] } hwes = { 'trend':...
arima = {'order': [(2, 1, 0), (0, 1, 2), (1, 1, 1)], 'seasonal_order': [(0, 0, 0, 0), (0, 1, 1, 12)], 'trend': ['n', 'c', 't', 'ct']} elasticnet = {'alpha': [i / 10 for i in range(1, 101)], 'l1_ratio': [0, 0.25, 0.5, 0.75, 1], 'normalizer': ['scale', 'minmax', None]} gbt = {'max_depth': [2, 3], 'n_estimators': [100, 50...
"""Incoming data loaders This file contains loader classes that allow reading iteratively through vehicle entry data for various different data formats Classes: Vehicle Entry """ class Vehicle(): """Representation of a single vehicle.""" def __init__(self, entry, pce): # vehicle propertie...
"""Incoming data loaders This file contains loader classes that allow reading iteratively through vehicle entry data for various different data formats Classes: Vehicle Entry """ class Vehicle: """Representation of a single vehicle.""" def __init__(self, entry, pce): self.id = entry.id ...
# This is a pytest config file # https://docs.pytest.org/en/2.7.3/plugins.html # It allows us to tell nbval (the py.text plugin we use to run # notebooks and check their output is unchanged) to skip comparing # notebook outputs for particular mimetypes. def pytest_collectstart(collector): if ( collector....
def pytest_collectstart(collector): if collector.fspath and collector.fspath.ext == '.ipynb' and hasattr(collector, 'skip_compare'): collector.skip_compare += ('application/vnd.plotly.v1+json',)
# model model = Model() i1 = Input("op1", "TENSOR_FLOAT32", "{2, 2, 2, 2}") i3 = Output("op3", "TENSOR_FLOAT32", "{2, 2, 2, 2}") model = model.Operation("RSQRT", i1).To(i3) # Example 1. Input in operand 0, input0 = {i1: # input 0 [1.0, 36.0, 2.0, 90, 4.0, 16.0, 25.0, 100.0, 23.0, 19.0, 40.0, 256.0, 4.0,...
model = model() i1 = input('op1', 'TENSOR_FLOAT32', '{2, 2, 2, 2}') i3 = output('op3', 'TENSOR_FLOAT32', '{2, 2, 2, 2}') model = model.Operation('RSQRT', i1).To(i3) input0 = {i1: [1.0, 36.0, 2.0, 90, 4.0, 16.0, 25.0, 100.0, 23.0, 19.0, 40.0, 256.0, 4.0, 43.0, 8.0, 36.0]} output0 = {i3: [1.0, 0.166667, 0.70710678118, 0....
#It's a simple calculator for doing Addition, Subtraction, Multiplication, Division and Percentage. first_number = int(input("Enter your first number: ")) operators = input("Enter what you wanna do +,-,*,/,%: ") second_number = int(input("Enter your second Number: ")) if operators == "+" : first_number...
first_number = int(input('Enter your first number: ')) operators = input('Enter what you wanna do +,-,*,/,%: ') second_number = int(input('Enter your second Number: ')) if operators == '+': first_number += second_number print(f'Your Addition result is: {first_number}') elif operators == '-': first_number -=...
description = 'system setup' group = 'lowlevel' sysconfig = dict( cache='localhost', instrument='Fluco', experiment='Exp', datasinks=['conssink', 'filesink', 'daemonsink',], ) modules = ['nicos.commands.standard', 'nicos_ess.commands.epics'] devices = dict( Fluco=device('nicos.devices.instrument...
description = 'system setup' group = 'lowlevel' sysconfig = dict(cache='localhost', instrument='Fluco', experiment='Exp', datasinks=['conssink', 'filesink', 'daemonsink']) modules = ['nicos.commands.standard', 'nicos_ess.commands.epics'] devices = dict(Fluco=device('nicos.devices.instrument.Instrument', description='in...
i=2 while i < 10: j=1 while j < 10: print(i,"*",j,"=",i*j) j += 1 i += 1
i = 2 while i < 10: j = 1 while j < 10: print(i, '*', j, '=', i * j) j += 1 i += 1
# Program that asks the user to input any positive integer and # outputs the successive value of the following calculation. # It should at each step calculate the next value by taking the current value # if the it is even, divide it by two, if it is odd, multiply # it by three and add one # the program ends if the cur...
n = int(input('please enter a number: ')) while n != 1: if n <= 0: print('Please enter a positive number.') break elif n % 2 == 0: n = int(n / 2) print(n) else: n = int(n * 3 + 1) print(n)
df =[['4', '1', '2', '7', '2', '5', '1'], ['9', '9', '8', '0', '2', '0', '8', '5', '0', '1', '3']] str='' dcf = ''.join(df) print(dcf) print()
df = [['4', '1', '2', '7', '2', '5', '1'], ['9', '9', '8', '0', '2', '0', '8', '5', '0', '1', '3']] str = '' dcf = ''.join(df) print(dcf) print()
parameters = { "results": [ { "type": "max", "identifier": { "symbol": "S22", "elset": "ALL_ELEMS", "position": "Element 1 Int Point 1 Sec Pt SPOS, (fraction = 1:0)" }, "referenceValue": 6...
parameters = {'results': [{'type': 'max', 'identifier': {'symbol': 'S22', 'elset': 'ALL_ELEMS', 'position': 'Element 1 Int Point 1 Sec Pt SPOS, (fraction = 1:0)'}, 'referenceValue': 62.3, 'tolerance': 0.05}, {'type': 'disp_at_zero_y', 'step': 'Step-1', 'identifier': [{'symbol': 'U2', 'nset': 'Y+', 'position': 'Node 3'}...
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: def check(t, a, dp): n=len(t) for k in range(1, n): if dp[a+0][a+k-1] and dp[a+k][a+n-1]: return 1 return 0 n=len(s) dp=[[0 for j in r...
class Solution: def word_break(self, s: str, wordDict: List[str]) -> bool: def check(t, a, dp): n = len(t) for k in range(1, n): if dp[a + 0][a + k - 1] and dp[a + k][a + n - 1]: return 1 return 0 n = len(s) dp = [[0 f...
expected_output = { "clock_state": { "system_status": { "associations_address": "10.16.2.2", "associations_local_mode": "client", "clock_offset": 27.027, "clock_refid": "127.127.1.1", "clock_state": "synchronized", "clock_stratum": 3, ...
expected_output = {'clock_state': {'system_status': {'associations_address': '10.16.2.2', 'associations_local_mode': 'client', 'clock_offset': 27.027, 'clock_refid': '127.127.1.1', 'clock_state': 'synchronized', 'clock_stratum': 3, 'root_delay': 5.61}}, 'peer': {'10.16.2.2': {'local_mode': {'client': {'delay': 5.61, 'j...
#!/usr/python3.5 #-*- coding: utf-8 -*- for row in range(10): for j in range(row): print (" ",end=" ") for i in range(10-row): print (i,end=" ") print ()
for row in range(10): for j in range(row): print(' ', end=' ') for i in range(10 - row): print(i, end=' ') print()
# SUM def twoSumI(nums, target): result = {} for k, v in enumerate(nums): sub = target - v if sub in result: return [result[sub], k] result[v] = k def twoSum(nums, target): l, r = 0, len(nums) - 1 result = [] while l < r: total = nums[l] + nums[r] ...
def two_sum_i(nums, target): result = {} for (k, v) in enumerate(nums): sub = target - v if sub in result: return [result[sub], k] result[v] = k def two_sum(nums, target): (l, r) = (0, len(nums) - 1) result = [] while l < r: total = nums[l] + nums[r] ...
# -*- coding: utf-8 -*- """ Created on 24 Dec 2019 20:40:06 @author: jiahuei """ def get_dict(fp): data = {} with open(fp, 'r') as f: for ll in f.readlines(): _ = ll.split(',') data[_[0]] = _[1].rstrip() return data def dump(data, keys, out_path): out_str = '' fo...
""" Created on 24 Dec 2019 20:40:06 @author: jiahuei """ def get_dict(fp): data = {} with open(fp, 'r') as f: for ll in f.readlines(): _ = ll.split(',') data[_[0]] = _[1].rstrip() return data def dump(data, keys, out_path): out_str = '' for k in keys: out_s...
__author__ = 'Aaron Yang' __email__ = 'byang971@usc.edu' __date__ = '1/10/2021 10:53 PM' class Solution: def smallestStringWithSwaps(self, s: str, pairs) -> str: chars = list(s) pairs.sort(key=lambda item: (item[0], item[1])) for pair in pairs: a, b = pair[0], pair[1] ...
__author__ = 'Aaron Yang' __email__ = 'byang971@usc.edu' __date__ = '1/10/2021 10:53 PM' class Solution: def smallest_string_with_swaps(self, s: str, pairs) -> str: chars = list(s) pairs.sort(key=lambda item: (item[0], item[1])) for pair in pairs: (a, b) = (pair[0], pair[1]) ...
"""Exceptions for Ambee.""" class AmbeeError(Exception): """Generic Ambee exception.""" class AmbeeConnectionError(AmbeeError): """Ambee connection exception.""" class AmbeeAuthenticationError(AmbeeConnectionError): """Ambee authentication exception.""" class AmbeeConnectionTimeoutError(AmbeeConnect...
"""Exceptions for Ambee.""" class Ambeeerror(Exception): """Generic Ambee exception.""" class Ambeeconnectionerror(AmbeeError): """Ambee connection exception.""" class Ambeeauthenticationerror(AmbeeConnectionError): """Ambee authentication exception.""" class Ambeeconnectiontimeouterror(AmbeeConnectionE...
# test bignum unary operations i = 1 << 65 print(bool(i)) print(+i) print(-i) print(~i)
i = 1 << 65 print(bool(i)) print(+i) print(-i) print(~i)
def zeroes(n, cnt): if n == 0: return cnt elif n % 10 == 0: return zeroes(n//10, cnt+1) else: return zeroes(n//10, cnt) n = int(input()) print(zeroes(n, 0))
def zeroes(n, cnt): if n == 0: return cnt elif n % 10 == 0: return zeroes(n // 10, cnt + 1) else: return zeroes(n // 10, cnt) n = int(input()) print(zeroes(n, 0))
req = { "userId": "admin", "metadata": { "@context": [ "https://w3id.org/ro/crate/1.0/context", { "@vocab": "https://schema.org/", "osfcategory": "https://www.research-data-services.org/jsonld/osfcategory", "zenodocategory": "https:...
req = {'userId': 'admin', 'metadata': {'@context': ['https://w3id.org/ro/crate/1.0/context', {'@vocab': 'https://schema.org/', 'osfcategory': 'https://www.research-data-services.org/jsonld/osfcategory', 'zenodocategory': 'https://www.research-data-services.org/jsonld/zenodocategory'}], '@graph': [{'@id': 'ro-crate-meta...
class GoogleException(Exception): def __init__(self, code, message, response): self.status_code = code self.error_type = message self.message = message self.response = response self.get_error_type() def get_error_type(self): json_response = self.response.json() ...
class Googleexception(Exception): def __init__(self, code, message, response): self.status_code = code self.error_type = message self.message = message self.response = response self.get_error_type() def get_error_type(self): json_response = self.response.json() ...
command = input().lower() in_progress = True car_stopped = True while in_progress: if command == 'help': print("start - to start the car") print("stop - to stop the car") print("quit - to ext") elif command == 'start': if car_stopped: print("You started the car") ...
command = input().lower() in_progress = True car_stopped = True while in_progress: if command == 'help': print('start - to start the car') print('stop - to stop the car') print('quit - to ext') elif command == 'start': if car_stopped: print('You started the car') ...
def create_xml_doc(text): JS(""" try //Internet Explorer { var xmlDoc=new ActiveXObject("Microsoft['XMLDOM']"); xmlDoc['async']="false"; xmlDoc['loadXML'](@{{text}}); } catch(e) { try //Firefox, Mozilla, Opera, etc. { var parser=new DOMParser(); xmlDoc=parser['parseFromString'](@{{text}},...
def create_xml_doc(text): js('\ntry //Internet Explorer\n {\n var xmlDoc=new ActiveXObject("Microsoft[\'XMLDOM\']");\n xmlDoc[\'async\']="false";\n xmlDoc[\'loadXML\'](@{{text}});\n }\ncatch(e)\n {\n try //Firefox, Mozilla, Opera, etc.\n {\n var parser=new DOMParser();\n xmlDoc=parser[\'parseFromStr...
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2014, Chris Hoffman <choffman@chathamfinancial.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) DOCUMENTATION = r''' --- module: win_service short_description: Manage and query Windows services description: - M...
documentation = "\n---\nmodule: win_service\nshort_description: Manage and query Windows services\ndescription:\n- Manage and query Windows services.\n- For non-Windows targets, use the M(ansible.builtin.service) module instead.\noptions:\n dependencies:\n description:\n - A list of service dependencies to set f...
class Solution: """ @param candidates: A list of integers @param target: An integer @return: A list of lists of integers """ def combinationSum(self, candidates, target): # write your code here if not candidates or len(candidates) == 0: return [[]] candidates...
class Solution: """ @param candidates: A list of integers @param target: An integer @return: A list of lists of integers """ def combination_sum(self, candidates, target): if not candidates or len(candidates) == 0: return [[]] candidates.sort() self.results =...
# test exception matching against a tuple try: fail except (Exception,): print('except 1') try: fail except (Exception, Exception): print('except 2') try: fail except (TypeError, NameError): print('except 3') try: fail except (TypeError, ValueError, Exception): print('except 4')
try: fail except (Exception,): print('except 1') try: fail except (Exception, Exception): print('except 2') try: fail except (TypeError, NameError): print('except 3') try: fail except (TypeError, ValueError, Exception): print('except 4')
def printMaximum(num): d = {} for i in range(10): d[i] = 0 for i in str(num): d[int(i)] += 1 res = 0 m = 1 for i in list(d.keys()): while d[i] > 0: res = res + i*m d[i] -= 1 m *= 10 return res # Driver co...
def print_maximum(num): d = {} for i in range(10): d[i] = 0 for i in str(num): d[int(i)] += 1 res = 0 m = 1 for i in list(d.keys()): while d[i] > 0: res = res + i * m d[i] -= 1 m *= 10 return res num = 38293367 print(print_maximum(n...
NUMERIC = "numeric" CATEGORICAL = "categorical" TEST_MODEL = "test" SINGLE_MODEL = "single" MODEL_SEARCH = "search" SHUTDOWN = "shutdown" DEFAULT_PORT = 8042 DEFAULT_MAX_JOBS = 4 ERROR = "error" QUEUED = "queued" STARTED = "started" IN_PROGRESS = "in-progress" FINISHED = "finished" # This can be any x where np.exp(...
numeric = 'numeric' categorical = 'categorical' test_model = 'test' single_model = 'single' model_search = 'search' shutdown = 'shutdown' default_port = 8042 default_max_jobs = 4 error = 'error' queued = 'queued' started = 'started' in_progress = 'in-progress' finished = 'finished' large_exp = 512 epsilon = 0.0001 matr...
class TopTen: def __init__(self): self.num = 1 def __iter__(self): return self def __next__(self): if self.num <= 10: val = self.num self.num += 1 return val else: raise StopIteration values = TopTen() print(next(values)) f...
class Topten: def __init__(self): self.num = 1 def __iter__(self): return self def __next__(self): if self.num <= 10: val = self.num self.num += 1 return val else: raise StopIteration values = top_ten() print(next(values)) fo...
class cached_property: def __init__(self, func): self.__doc__ = getattr(func, "__doc__") self.func = func def __get__(self, obj, cls): if obj is None: return self value = obj.__dict__[self.func.__name__] = self.func(obj) return value
class Cached_Property: def __init__(self, func): self.__doc__ = getattr(func, '__doc__') self.func = func def __get__(self, obj, cls): if obj is None: return self value = obj.__dict__[self.func.__name__] = self.func(obj) return value
# Copyright (C) 2018-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 def tf_pack_ext(pb): assert (pb.attr["N"].i == len(pb.input)) return { 'axis': pb.attr["axis"].i, 'N': pb.attr["N"].i, 'infer': None }
def tf_pack_ext(pb): assert pb.attr['N'].i == len(pb.input) return {'axis': pb.attr['axis'].i, 'N': pb.attr['N'].i, 'infer': None}
class ZoomAdminAccount(object): """ Model to hold Zoom Admin Account info """ def __init__(self, api_key, api_secret): self.api_key = api_key self.api_secret = api_secret
class Zoomadminaccount(object): """ Model to hold Zoom Admin Account info """ def __init__(self, api_key, api_secret): self.api_key = api_key self.api_secret = api_secret
#!/usr/bin/python3 ls = [l.strip().split(" ") for l in open("inputs/08.in", "r").readlines()] def run(sw): acc,p,ps = 0,0,[] while p < len(ls): if p in ps: return acc if sw == -1 else -1 ps.append(p) acc += int(ls[p][1]) if ls[p][0] == "acc" else 0 p += int(ls[p][1]) if (ls[p][0...
ls = [l.strip().split(' ') for l in open('inputs/08.in', 'r').readlines()] def run(sw): (acc, p, ps) = (0, 0, []) while p < len(ls): if p in ps: return acc if sw == -1 else -1 ps.append(p) acc += int(ls[p][1]) if ls[p][0] == 'acc' else 0 p += int(ls[p][1]) if ls[p][0...
counter = 0 def merge(array, left, right): i = j = k = 0 global counter while i < len(left) and j < len(right): if left[i] <= right[j]: array[k] = left[i] k += 1 i += 1 else: array[k] = right[j] counter += len(left) - i ...
counter = 0 def merge(array, left, right): i = j = k = 0 global counter while i < len(left) and j < len(right): if left[i] <= right[j]: array[k] = left[i] k += 1 i += 1 else: array[k] = right[j] counter += len(left) - i ...
# Copyright 2004-2008 Roman Yakovenko. # Distributed under the Boost Software License, Version 1.0. (See # accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) """ This file contains C++ code needed to export one dimensional static arrays. """ namespace = "pyplusplus::conven...
""" This file contains C++ code needed to export one dimensional static arrays. """ namespace = 'pyplusplus::convenience' file_name = '__convenience.pypp.hpp' code = '// Copyright 2004-2008 Roman Yakovenko.\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy...
""" This module contains the error messages issued by the Cerberus Validator. The test suite uses this module as well. """ ERROR_SCHEMA_MISSING = "validation schema missing" ERROR_SCHEMA_FORMAT = "'%s' is not a schema, must be a dict" ERROR_DOCUMENT_MISSING = "document is missing" ERROR_DOCUMENT_FORMAT = "'%s' is not a...
""" This module contains the error messages issued by the Cerberus Validator. The test suite uses this module as well. """ error_schema_missing = 'validation schema missing' error_schema_format = "'%s' is not a schema, must be a dict" error_document_missing = 'document is missing' error_document_format = "'%s' is not a...
class ExtDefines(object): EDEFINE1 = 'ED1' EDEFINE2 = 'ED2' EDEFINE3 = 'ED3' EDEFINES = ( (EDEFINE1, 'EDefine 1'), (EDEFINE2, 'EDefine 2'), (EDEFINE3, 'EDefine 3'), ) class EmptyDefines(object): """ This should not show up when a module is dumped! """ pass
class Extdefines(object): edefine1 = 'ED1' edefine2 = 'ED2' edefine3 = 'ED3' edefines = ((EDEFINE1, 'EDefine 1'), (EDEFINE2, 'EDefine 2'), (EDEFINE3, 'EDefine 3')) class Emptydefines(object): """ This should not show up when a module is dumped! """ pass
# n = n # time = O(logn) # space = O(1) # done time = 5m class Solution: def firstBadVersion(self, n): """ :type n: int :rtype: int """ left = 1 right = n + 1 while left < right: mid = left + right >> 1 comp = isBadVersion(mid) ...
class Solution: def first_bad_version(self, n): """ :type n: int :rtype: int """ left = 1 right = n + 1 while left < right: mid = left + right >> 1 comp = is_bad_version(mid) if comp: right = mid ...
def fib(n: int) -> int: if n < 2: # base case return n return fib(n - 2) + fib(n - 1) if __name__ == "__main__": print(fib(2)) print(fib(10))
def fib(n: int) -> int: if n < 2: return n return fib(n - 2) + fib(n - 1) if __name__ == '__main__': print(fib(2)) print(fib(10))
#!/usr/bin/env python3 class ApiDefaults: url_verify = "/api/verify_api_key" url_refresh = "/api/import/refresh" url_add = "/api/import/add"
class Apidefaults: url_verify = '/api/verify_api_key' url_refresh = '/api/import/refresh' url_add = '/api/import/add'
""" entradas nbilletes50-->int-->n1 nbilletes20-->int-->n2 nbilletes10-->int-->n3 nbilletes5-->int-->n4 nbilletes2-->int-->n5 nbilletes1-->int-->n6 nbilletes500-->int-->n7 nbilletes100-->int-->n8 salidas total_dinero-->str-->td """ n1=(int(input("digite la cantidad de billetes de $50000 "))) n2=(int(input("digite la...
""" entradas nbilletes50-->int-->n1 nbilletes20-->int-->n2 nbilletes10-->int-->n3 nbilletes5-->int-->n4 nbilletes2-->int-->n5 nbilletes1-->int-->n6 nbilletes500-->int-->n7 nbilletes100-->int-->n8 salidas total_dinero-->str-->td """ n1 = int(input('digite la cantidad de billetes de $50000 ')) n2 = int(input('digite la c...
class Solution(object): def islandPerimeter(self, grid): """ :type grid: List[List[int]] :rtype: int """ sum = 0 for w in range(len(grid)): for h in range(len(grid[0])): if grid[w][h] == 1: add_length = 4 else: continue ...
class Solution(object): def island_perimeter(self, grid): """ :type grid: List[List[int]] :rtype: int """ sum = 0 for w in range(len(grid)): for h in range(len(grid[0])): if grid[w][h] == 1: add_length = 4 ...
"""Exceptions raised by this package.""" class MetaloaderError(Exception): """Base exception for all errors within this package.""" class MetaloaderNotImplemented(MetaloaderError): """Something is yet not implemented in the library."""
"""Exceptions raised by this package.""" class Metaloadererror(Exception): """Base exception for all errors within this package.""" class Metaloadernotimplemented(MetaloaderError): """Something is yet not implemented in the library."""
words = "sort the inner content in descending order" result = [] for w in words.split(): if len(w)>3: result.append(w[0]+''.join(sorted(w[1:-1], reverse=True))+w[-1]) else: result.append(w)
words = 'sort the inner content in descending order' result = [] for w in words.split(): if len(w) > 3: result.append(w[0] + ''.join(sorted(w[1:-1], reverse=True)) + w[-1]) else: result.append(w)
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def __init__(self): self.total = 0 def sumOfLeftLeaves(self, root: TreeNode) -> int: if not root: return 0 ...
class Treenode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def __init__(self): self.total = 0 def sum_of_left_leaves(self, root: TreeNode) -> int: if not root: return 0 def dfs(node, type): ...
language_map = { 'ko': 'ko_KR', 'ja': 'ja_JP', 'zh': 'zh_CN' }
language_map = {'ko': 'ko_KR', 'ja': 'ja_JP', 'zh': 'zh_CN'}
# Time: O(n) # Space: O(1) # Given an array nums of integers, you can perform operations on the array. # # In each operation, you pick any nums[i] and delete it to earn nums[i] points. # After, you must delete every element equal to nums[i] - 1 or nums[i] + 1. # # You start with 0 points. # Return the maximum number ...
class Solution(object): def delete_and_earn(self, nums): """ :type nums: List[int] :rtype: int """ vals = [0] * 10001 for num in nums: vals[num] += num (val_i, val_i_1) = (vals[0], 0) for i in xrange(1, len(vals)): (val_i_1, va...
global numbering numbering = [0,1,2,3] num = 0 filterbegin = '''res(); for (i=0, o=0; i<115; i++){''' o = ['MSI', 'APPV', 'Citrix MSI', 'Normal','Express','Super Express (BOPO)', 'Simple', 'Medium', 'Complex', 'May', 'June', 'July', 'August'] filterending = '''if (val1 == eq1){ if (val2 == eq2){ if (val3 =...
global numbering numbering = [0, 1, 2, 3] num = 0 filterbegin = 'res(); for (i=0, o=0; i<115; i++){' o = ['MSI', 'APPV', 'Citrix MSI', 'Normal', 'Express', 'Super Express (BOPO)', 'Simple', 'Medium', 'Complex', 'May', 'June', 'July', 'August'] filterending = 'if (val1 == eq1){ if (val2 == eq2){ if (val3 == eq3){ if (va...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def countUnivalSubtrees(self, root: TreeNode) -> int: self.count = 0 self.is_uni(root) ...
class Solution: def count_unival_subtrees(self, root: TreeNode) -> int: self.count = 0 self.is_uni(root) return self.count def is_uni(self, node): if not node: return True if node.left is None and node.right is None: self.count += 1 r...
#!/usr/bin/env python3 # Label key for repair state # (IN_SERVICE, OUT_OF_POOL, READY_FOR_REPAIR, IN_REPAIR, AFTER_REPAIR) REPAIR_STATE = "REPAIR_STATE" # Annotation key for the last update time of the repair state REPAIR_STATE_LAST_UPDATE_TIME = "REPAIR_STATE_LAST_UPDATE_TIME" # Annotation key for the last email ti...
repair_state = 'REPAIR_STATE' repair_state_last_update_time = 'REPAIR_STATE_LAST_UPDATE_TIME' repair_state_last_email_time = 'REPAIR_STATE_LAST_EMAIL_TIME' repair_unhealthy_rules = 'REPAIR_UNHEALTHY_RULES' repair_cycle = 'REPAIR_CYCLE' repair_message = 'REPAIR_MESSAGE'
###################################################################################################################### # Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # ...
boolean_false_values = ['false', 'no', 'disabled', 'off', '0'] boolean_true_values = ['true', 'yes', 'enabled', 'on', '1'] env_config_table = 'CONFIG_TABLE' env_config_bucket = 'CONFIG_BUCKET' tasks_objects = 'TaskConfigurationObjects' config_action_name = 'Action' config_debug = 'Debug' config_task_notifications = 'Ta...
{ "targets": [ { "target_name": "ecdh", "include_dirs": ["<!(node -e \"require('nan')\")"], "cflags": ["-Wall", "-O2"], "sources": ["ecdh.cc"], "conditions": [ ["OS=='win'", { "conditions": [ [ "target_arch=='x64'", { "varia...
{'targets': [{'target_name': 'ecdh', 'include_dirs': ['<!(node -e "require(\'nan\')")'], 'cflags': ['-Wall', '-O2'], 'sources': ['ecdh.cc'], 'conditions': [["OS=='win'", {'conditions': [["target_arch=='x64'", {'variables': {'openssl_root%': 'C:/OpenSSL-Win64'}}, {'variables': {'openssl_root%': 'C:/OpenSSL-Win32'}}]], '...
class Contact: def __init__(self, name, phone, email): self.name = name self.phone = phone self.email = email
class Contact: def __init__(self, name, phone, email): self.name = name self.phone = phone self.email = email
""" Discover & provide the log group name """ class LogGroupProvider(object): """ Resolve the name of log group given the name of the resource """ @staticmethod def for_lambda_function(function_name): """ Returns the CloudWatch Log Group Name created by default for the AWS Lambda ...
""" Discover & provide the log group name """ class Loggroupprovider(object): """ Resolve the name of log group given the name of the resource """ @staticmethod def for_lambda_function(function_name): """ Returns the CloudWatch Log Group Name created by default for the AWS Lambda f...
''' This module contains some exception classes ''' class SecondryStructureError(Exception): ''' Raised when the Secondry structure is not correct ''' def __init__(self, residue, value): messgae = ''' ERROR: Secondary Structure Input is not parsed correctly. Please make sure th...
""" This module contains some exception classes """ class Secondrystructureerror(Exception): """ Raised when the Secondry structure is not correct """ def __init__(self, residue, value): messgae = '\n ERROR: Secondary Structure Input is not parsed correctly.\n Please make sure th...
class get_method_name_decorator: def __init__(self, fn): self.fn = fn def __set_name__(self, owner, name): owner.method_names.add(self.fn) setattr(owner, name, self.fn)
class Get_Method_Name_Decorator: def __init__(self, fn): self.fn = fn def __set_name__(self, owner, name): owner.method_names.add(self.fn) setattr(owner, name, self.fn)
# https://www.devdungeon.com/content/colorize-terminal-output-python # https://www.geeksforgeeks.org/print-colors-python-terminal/ class CONST: class print_color: class control: ''' Full name: Perfect_color_text ''' reset='\033[0m' bold='\033[0...
class Const: class Print_Color: class Control: """ Full name: Perfect_color_text """ reset = '\x1b[0m' bold = '\x1b[01m' disable = '\x1b[02m' underline = '\x1b[04m' reverse = '\x1b[07m' strikethroug...
found = False while not found: num = float(input()) if 1 <= num <= 100: print(f"The number {num} is between 1 and 100") found = True
found = False while not found: num = float(input()) if 1 <= num <= 100: print(f'The number {num} is between 1 and 100') found = True
# MathHelper.py - Some helpful math utilities. # Created by Josh Kennedy on 18 May 2014 # # Pop a Dots # Copyright 2014 Chad Jensen and Josh Kennedy # Copyright 2015-2016 Sirkles LLC def lerp(value1, value2, amount): return value1 + ((value2 - value1) * amount) def isPowerOfTwo(value): return (value > 0) an...
def lerp(value1, value2, amount): return value1 + (value2 - value1) * amount def is_power_of_two(value): return value > 0 and value & value - 1 == 0 def to_degrees(radians): return radians * 57.29577951308232 def to_radians(degrees): return degrees * 0.017453292519943295 def clamp(value, low, high):...
## Function def insertShiftArray(arr, num): """ This function takes in two parameters: a list, and an integer. insertShiftArray will place the integer at the middle index of the list provided. """ answerArr = [] middle = 0 # No math methods, if/else to determine odd or even to find middle index ...
def insert_shift_array(arr, num): """ This function takes in two parameters: a list, and an integer. insertShiftArray will place the integer at the middle index of the list provided. """ answer_arr = [] middle = 0 if len(arr) % 2 == 0: middle = len(arr) / 2 else: middle = len...
# Adds testing.TestEnvironment provider if "env" attr is specified # https://bazel.build/rules/lib/testing#TestEnvironment def phase_test_environment(ctx, p): test_env = ctx.attr.env if test_env: return struct( external_providers = { "TestingEnvironment": testing.TestEnviro...
def phase_test_environment(ctx, p): test_env = ctx.attr.env if test_env: return struct(external_providers={'TestingEnvironment': testing.TestEnvironment(test_env)}) return struct()
# coding: utf-8 """ .. _available-parsers: Available Parsers ================= This package contains a collection of parsers which you can use in conjonction with builders to convert tables from one format to another. You can pick a builder in the :ref:`Available Builders <available-builders>`. """
""" .. _available-parsers: Available Parsers ================= This package contains a collection of parsers which you can use in conjonction with builders to convert tables from one format to another. You can pick a builder in the :ref:`Available Builders <available-builders>`. """
def keyquery(): return( set([]) ) def getval(prob): return( prob.file )
def keyquery(): return set([]) def getval(prob): return prob.file
#!/usr/bin/env python3 print('1a') print('1b') print('2a\n') print('2b\n') print('3a\r\n') print('3b\r\n') print('4a\r') print('4b\r') print('5a\n\r') print('5b\n\r')
print('1a') print('1b') print('2a\n') print('2b\n') print('3a\r\n') print('3b\r\n') print('4a\r') print('4b\r') print('5a\n\r') print('5b\n\r')
# You are given a string and your task is to swap cases. # In other words, convert all lowercase letters to uppercase letters and vice versa. def swap_case(s): return s.swapcase() if __name__ == '__main__': s = input() result = swap_case(s) print(result)
def swap_case(s): return s.swapcase() if __name__ == '__main__': s = input() result = swap_case(s) print(result)
# uncompyle6 version 3.7.2 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)] # Embedded file name: extract__one_file_exe__pyinstaller\_test_file.py __author__ = 'ipetrash' def say(): print('Hello World!') if __name__ == '__main__': say()
__author__ = 'ipetrash' def say(): print('Hello World!') if __name__ == '__main__': say()
input = """ d(1). d(2). d(3). d(4) :- #min{V : d(V)} = 1. """ output = """ d(1). d(2). d(3). d(4) :- #min{V : d(V)} = 1. """
input = '\nd(1).\nd(2).\nd(3).\n\nd(4) :- #min{V : d(V)} = 1.\n\n' output = '\nd(1).\nd(2).\nd(3).\n\nd(4) :- #min{V : d(V)} = 1.\n\n'
""" Count the number of inversions in a sequence of orderable items. Description: Informally, when we say inversion we mean inversion from the (ascending) sorted order. For a more formal definition, let's call the list of items L. We call inversion a pair of indices i, j with i < j and L[i] > L[j], where L...
""" Count the number of inversions in a sequence of orderable items. Description: Informally, when we say inversion we mean inversion from the (ascending) sorted order. For a more formal definition, let's call the list of items L. We call inversion a pair of indices i, j with i < j and L[i] > L[j], where L...
# Law of large number # How to get first line input n, m, k = map(int, input().split()) data = list(map(int, input().split())) solution = 0 count_use_max_value = 0 data.sort(reverse=True) for i in range(0, m): if count_use_max_value >= k: solution += data[1] count_use_max_value = 0 else: ...
(n, m, k) = map(int, input().split()) data = list(map(int, input().split())) solution = 0 count_use_max_value = 0 data.sort(reverse=True) for i in range(0, m): if count_use_max_value >= k: solution += data[1] count_use_max_value = 0 else: solution += data[0] count_use_max_value +...
# FIXME need to fix TWO_RIG_AX_TO_MOVE here; empirically-derived, like we did with safe trajectories # define rig_ax to be moved to achieve either min or max given that we are at designated rough home position TWO_RIG_AX_TO_MOVE = { # rough_home ax1 min max ax2 min max '+x': [('pitch', ...
two_rig_ax_to_move = {'+x': [('pitch', -10, +10), ('roll', -10, +10)], '-x': [('pitch', +160, +172), ('roll', -10, +10)], '+y': [('pitch', +70, +90), ('yaw', -80, -100)], '-y': [('pitch', -90, -110), ('roll', -10, +10)], '+z': [('pitch', -90, -110), ('roll', -10, +10)], '-z': [('pitch', +70, +90), ('yaw', -10, +10)]} e...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: if root == None: return [] ...
class Solution: def preorder_traversal(self, root: TreeNode) -> List[int]: if root == None: return [] else: cur_list = [root] while True: next_list = [] expanded = False for cur_root in curList: ...
def lambda_handler(event, context): n = int(event['number']) n = n * -1 if n < 0 else n subject = event.get('__TRIGGERFLOW_SUBJECT', None) return {'number': n, '__TRIGGERFLOW_SUBJECT': subject}
def lambda_handler(event, context): n = int(event['number']) n = n * -1 if n < 0 else n subject = event.get('__TRIGGERFLOW_SUBJECT', None) return {'number': n, '__TRIGGERFLOW_SUBJECT': subject}
# -*- coding: utf-8 -*- # Copyright 2021 Cohesity Inc. class UpdateLinuxPasswordReqParams(object): """Implementation of the 'UpdateLinuxPasswordReqParams' model. Specifies the user input parameters. Attributes: linux_current_password (string): Specifies the current password. linux_passw...
class Updatelinuxpasswordreqparams(object): """Implementation of the 'UpdateLinuxPasswordReqParams' model. Specifies the user input parameters. Attributes: linux_current_password (string): Specifies the current password. linux_password (string): Specifies the new linux password. li...
load("@bazel_skylib//lib:paths.bzl", "paths") load("@bazel_skylib//lib:shell.bzl", "shell") def _addlicense_impl(ctx): out_file = ctx.actions.declare_file(ctx.label.name + ".bash") exclude_patterns_str = "" if ctx.attr.exclude_patterns: exclude_patterns = ["-not -path %s" % shell.quote(pattern) fo...
load('@bazel_skylib//lib:paths.bzl', 'paths') load('@bazel_skylib//lib:shell.bzl', 'shell') def _addlicense_impl(ctx): out_file = ctx.actions.declare_file(ctx.label.name + '.bash') exclude_patterns_str = '' if ctx.attr.exclude_patterns: exclude_patterns = ['-not -path %s' % shell.quote(pattern) for...
class Solution: def findComplement(self, num: int) -> int: res =i = 0 while num: if not num & 1: res |= 1 << i num = num >> 1 i += 1 return res class Solution: def findComplement(self, num: int) -> int: i = 1 while i <=...
class Solution: def find_complement(self, num: int) -> int: res = i = 0 while num: if not num & 1: res |= 1 << i num = num >> 1 i += 1 return res class Solution: def find_complement(self, num: int) -> int: i = 1 while...
class C: def foo(self): pass class D: def bar(self): pass class E: def baz(self): pass def f(): return 0 def g(): return x = (C(), D(), E()) a, b, c = x x[0].bar() # NO bar x[1].baz() # NO baz x[2].foo() # baz a.bar() # NO bar b.baz() # NO baz c.foo() # NO ...
class C: def foo(self): pass class D: def bar(self): pass class E: def baz(self): pass def f(): return 0 def g(): return x = (c(), d(), e()) (a, b, c) = x x[0].bar() x[1].baz() x[2].foo() a.bar() b.baz() c.foo()
# 2019-01-15 # csv file reading f = open('score.csv', 'r') lines = f.readlines() f.close() for line in lines: total = 0 count = 0 scores = line[:-1].split(',') # print(scores) for score in scores: total += int(score) count += 1 print("Total = %3d, Avg = %.2f" % (total, t...
f = open('score.csv', 'r') lines = f.readlines() f.close() for line in lines: total = 0 count = 0 scores = line[:-1].split(',') for score in scores: total += int(score) count += 1 print('Total = %3d, Avg = %.2f' % (total, total / count))
# # PySNMP MIB module INTEL-RSVP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/INTEL-RSVP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:43:25 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2...
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, constraints_union, value_size_constraint, value_range_constraint, single_value_constraint) ...
""" For each character in the `S` (if it is not a number), it has 2 possibilities, upper or lower. So starting from an empty string We explore all the possibilities for the character at index i is upper or lower. The time complexity is `O(2^N)`. The space took `O(2^N), too. And the recursion level has N level. """ cla...
""" For each character in the `S` (if it is not a number), it has 2 possibilities, upper or lower. So starting from an empty string We explore all the possibilities for the character at index i is upper or lower. The time complexity is `O(2^N)`. The space took `O(2^N), too. And the recursion level has N level. """ cl...
def create_mapping(table_name): """ Return the Elasticsearch mapping for a given table in the database. :param table_name: The name of the table in the upstream database. :return: """ mapping = { 'image': { "mappings": { "doc": { "properties"...
def create_mapping(table_name): """ Return the Elasticsearch mapping for a given table in the database. :param table_name: The name of the table in the upstream database. :return: """ mapping = {'image': {'mappings': {'doc': {'properties': {'license_version': {'type': 'text', 'fields': {'keywor...
""" Clear separation of the near universal extensions API from the default implementations. """
""" Clear separation of the near universal extensions API from the default implementations. """
# Algorithms > Bit Manipulation > Counter game # Louise and Richard play a game, find the winner of the game. # # https://www.hackerrank.com/challenges/counter-game/problem # pow2 = [1 << i for i in range(63, -1, -1)] def counterGame(n): player = 0 while n != 1: # print( ["Louise", "Richard"][player]...
pow2 = [1 << i for i in range(63, -1, -1)] def counter_game(n): player = 0 while n != 1: for i in pow2: if n == i: n = n // 2 if n != 1: player = 1 - player break elif n & i == i: n = n - i ...
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- def sub_report(): print("Hey, I'm a function inside my subscript.")
def sub_report(): print("Hey, I'm a function inside my subscript.")
# -*- coding: utf-8 -*- TOTAL_SESSION_NUM = 2 REST_DURATION = 5 * 60 BLOCK_DURATION = 2 * 60 MINIMUM_PULSE_CYCLE = 0.5 MAXIMUM_PULSE_CYCLE = 1.2 PPG_SAMPLE_RATE = 200 PPG_FIR_FILTER_TAP_NUM = 200 PPG_FILTER_CUTOFF = [0.5, 5.0] PPG_SYSTOLIC_PEAK_DETECTION_THRESHOLD_COEFFICIENT = 0.5 BIOPAC_HEADER_LINES = 11 BIOPAC_...
total_session_num = 2 rest_duration = 5 * 60 block_duration = 2 * 60 minimum_pulse_cycle = 0.5 maximum_pulse_cycle = 1.2 ppg_sample_rate = 200 ppg_fir_filter_tap_num = 200 ppg_filter_cutoff = [0.5, 5.0] ppg_systolic_peak_detection_threshold_coefficient = 0.5 biopac_header_lines = 11 biopac_msec_per_sample_line_num = 2 ...
# Link to the problem: https://www.codechef.com/problems/STACKS def binary_search(arr, x): l = 0 r = len(arr) while l < r: mid = (r + l) // 2 if x < arr[mid]: r = mid else: l = mid + 1 return l def main(): T = int(input()) while T: T ...
def binary_search(arr, x): l = 0 r = len(arr) while l < r: mid = (r + l) // 2 if x < arr[mid]: r = mid else: l = mid + 1 return l def main(): t = int(input()) while T: t -= 1 _ = int(input()) given_stack = list(map(int, inp...
class CorruptedStateSpaceModelStructureException(Exception): pass class CorruptedStochasticModelStructureException(Exception): pass
class Corruptedstatespacemodelstructureexception(Exception): pass class Corruptedstochasticmodelstructureexception(Exception): pass
API_ACCESS = 'YOUR_API_ACCESS' API_SECRET = 'YOUR_API_SECRET' BTC_UNIT = 0.001 BTC_AMOUNT = BTC_UNIT CNY_UNIT = 0.01 CNY_STEP = CNY_UNIT DIFFERENCE_STEP = 2.0 MIN_SURPLUS = 0.5 NO_GOOD_SLEEP = 15 MAX_TRIAL = 3 MAX_OPEN_ORDERS = 3 TOO_MANY_OPEN_SLEEP = 10 DEBUG_MODE = True REMOVE_THRESHOLD = 20.0 REMOVE_UNREA...
api_access = 'YOUR_API_ACCESS' api_secret = 'YOUR_API_SECRET' btc_unit = 0.001 btc_amount = BTC_UNIT cny_unit = 0.01 cny_step = CNY_UNIT difference_step = 2.0 min_surplus = 0.5 no_good_sleep = 15 max_trial = 3 max_open_orders = 3 too_many_open_sleep = 10 debug_mode = True remove_threshold = 20.0 remove_unrealistic = Tr...
''' Description: python solution of AddTwoNumbers (https://leetcode-cn.com/problems/add-two-numbers/) Author: Kotori Y Date: 2021-04-20 16:49:38 LastEditors: Kotori Y LastEditTime: 2021-04-20 16:51:04 FilePath: \LeetCode-Code\codes\LinkedList\AddTwoNumbers\AddTwoNumbers.py AuthorMail: kotori@cbdd.me ''' # Definition f...
""" Description: python solution of AddTwoNumbers (https://leetcode-cn.com/problems/add-two-numbers/) Author: Kotori Y Date: 2021-04-20 16:49:38 LastEditors: Kotori Y LastEditTime: 2021-04-20 16:51:04 FilePath: \\LeetCode-Code\\codes\\LinkedList\\AddTwoNumbers\\AddTwoNumbers.py AuthorMail: kotori@cbdd.me """ class Sol...
""" DFS Steps: - create and empty stack and and list of explored elements - take the starting element and push it into the stack and add it to the visited list - check if it has any children that are unvisited. - if it has unvisited kids, pick one and add it to the top of the stack and the visited list - recursively ch...
""" DFS Steps: - create and empty stack and and list of explored elements - take the starting element and push it into the stack and add it to the visited list - check if it has any children that are unvisited. - if it has unvisited kids, pick one and add it to the top of the stack and the visited list - recursively ch...
class Solution: def rob(self, nums: List[int]) -> int: if len(nums) < 3: return max(nums) n = len(nums) ans1 = self.robHouse(nums[:n-1]) ans2 = self.robHouse(nums[1:]) return max(ans1, ans2) def robHouse(self, nums): prev, curr = 0, 0 for num...
class Solution: def rob(self, nums: List[int]) -> int: if len(nums) < 3: return max(nums) n = len(nums) ans1 = self.robHouse(nums[:n - 1]) ans2 = self.robHouse(nums[1:]) return max(ans1, ans2) def rob_house(self, nums): (prev, curr) = (0, 0) ...