content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
""" Given two binary trees, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical and the nodes have the same value. Example 1: Input: 1 1 / \\ / \\ 2 3 2 3 [1,2,3], [1,...
""" Given two binary trees, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical and the nodes have the same value. Example 1: Input: 1 1 / \\ / \\ 2 3 2 3 [1,2,3], [1,...
class Solution(object): def findWords(self, words): """ :type words: List[str] :rtype: List[str] """ First = ['Q','W','E','R','T','Y','U','I','O','P'] SEC = ['A','S','D','F','G','H','J','K','L'] LAST= ['Z','X','C','V','B','N','M'] answer = [] f...
class Solution(object): def find_words(self, words): """ :type words: List[str] :rtype: List[str] """ first = ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P'] sec = ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L'] last = ['Z', 'X', 'C', 'V', 'B', 'N', 'M'] ...
def eqindexMultiPass(data): "Multi pass" for i in range(len(data)): suml, sumr = sum(data[:i]), sum(data[i+1:]) if suml == sumr: yield i
def eqindex_multi_pass(data): """Multi pass""" for i in range(len(data)): (suml, sumr) = (sum(data[:i]), sum(data[i + 1:])) if suml == sumr: yield i
class languages(): def __init__(self, fDic): self.fDic = fDic self.scripts = set(self.fDic.scripts) self.scripts.discard('dflt') def languageSyntax(self, script, language): return 'languagesystem %s %s;' %(script, language) def syntax(self): result = [self.language...
class Languages: def __init__(self, fDic): self.fDic = fDic self.scripts = set(self.fDic.scripts) self.scripts.discard('dflt') def language_syntax(self, script, language): return 'languagesystem %s %s;' % (script, language) def syntax(self): result = [self.language...
n = int(input()) for i in range(1,n+1): temp = n for j in range(1,i): print(temp,end="") temp = temp -1 for j in range(1,(2*n) - (2*i) + 2): print(n-i+1,end="") for j in range(1,i): temp = temp+1 print(temp,end="") print() for i in range(n-1,0,-1): temp ...
n = int(input()) for i in range(1, n + 1): temp = n for j in range(1, i): print(temp, end='') temp = temp - 1 for j in range(1, 2 * n - 2 * i + 2): print(n - i + 1, end='') for j in range(1, i): temp = temp + 1 print(temp, end='') print() for i in range(n - 1,...
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ stack = [] for i in range(len(s)): if s[i]=='(' or s[i]=='[' or s[i]=='{': stack.append(s[i]) elif s[i] == ')': if len(stack)>0 and ...
class Solution(object): def is_valid(self, s): """ :type s: str :rtype: bool """ stack = [] for i in range(len(s)): if s[i] == '(' or s[i] == '[' or s[i] == '{': stack.append(s[i]) elif s[i] == ')': if len(stack...
class Solution: def shortestPalindrome(self, s: str) -> str: temp = s + '#' + s[::-1] i = 1 l = 0 lps = [0] * len(temp) while i < len(temp): if temp[i] == temp[l]: lps[i] = l + 1 i += 1 l += 1 elif l != 0...
class Solution: def shortest_palindrome(self, s: str) -> str: temp = s + '#' + s[::-1] i = 1 l = 0 lps = [0] * len(temp) while i < len(temp): if temp[i] == temp[l]: lps[i] = l + 1 i += 1 l += 1 elif l !=...
class Solution: """ @param nums: a list of integers @return: return a integer """ def singleNonDuplicate(self, nums): n = len(nums) l = 0 r = n - 1 while l < r: mid = l + (r - l) // 2 p1 = p2 = mid if mid > 0 and nums[mid] == nums[m...
class Solution: """ @param nums: a list of integers @return: return a integer """ def single_non_duplicate(self, nums): n = len(nums) l = 0 r = n - 1 while l < r: mid = l + (r - l) // 2 p1 = p2 = mid if mid > 0 and nums[mid] == num...
l1 = [1, 3, 5, 7, 9] # list mutable (read write) t1 = (1, 3, 5, 7, 9) # tuple imutable (read only) def f(x): x.append(29) f(l1) print(l1) f(t1) print(t1)
l1 = [1, 3, 5, 7, 9] t1 = (1, 3, 5, 7, 9) def f(x): x.append(29) f(l1) print(l1) f(t1) print(t1)
""" Format for midterms(usually) and concepts tested 1. Tracing - higher order functions(*), function scope 2. Iteration/Recursion - Order Of Growth, writing iteration or recursion """ ################## #Order of Growth # ################## n = 100000000 k = 40000 """ Lists """ x = [i for...
""" Format for midterms(usually) and concepts tested 1. Tracing - higher order functions(*), function scope 2. Iteration/Recursion - Order Of Growth, writing iteration or recursion """ n = 100000000 k = 40000 '\nLists\n' x = [i for i in range(n)] y = [i for i in range(k)] x + [1] x.append(1) x....
# A list contains authorized users' discord IDs. OWNER = 184335517947658240 # foxfair # Staff AUTHORIZED = [ OWNER, 129405976020385792, # Auri 423991805156261889, # Kim 699053180079702098, # Gelica 266289895415218177, # Yang 294058604854509589, # Giana 107209352816914432, # Tooch ...
owner = 184335517947658240 authorized = [OWNER, 129405976020385792, 423991805156261889, 699053180079702098, 266289895415218177, 294058604854509589, 107209352816914432, 97145923691347968, 137798184721186817] send_msg_channels = [725807955559055451]
number = [i for i in range(1, 3001330+1)] # number = [i for i in range(1, 10)] number2 = number[:] last = len(number) % 2 != 0 while len(number) > 1: next_last = len(number) % 2 != last number = [j for i, j in enumerate(number) if i % 2 != last] last = next_last print('#1', number[0]) number = number2 ...
number = [i for i in range(1, 3001330 + 1)] number2 = number[:] last = len(number) % 2 != 0 while len(number) > 1: next_last = len(number) % 2 != last number = [j for (i, j) in enumerate(number) if i % 2 != last] last = next_last print('#1', number[0]) number = number2 while len(number) > 1: pop = set()...
class PagingModifier: def __init__(self, Id: int = None, End: int = None, Start: int = None, Limit: int = None, ): self.Id = Id self.Start = Start self.End = End self.Limit = Limit
class Pagingmodifier: def __init__(self, Id: int=None, End: int=None, Start: int=None, Limit: int=None): self.Id = Id self.Start = Start self.End = End self.Limit = Limit
employee_file=open("employee.txt","w") #write mode- erases previous content employee_file.write("David - Software Developer") print(employee_file.readable()) #print(employee_file.read()) employee_file.close() #David - Software Developer # previous data and content is vanished
employee_file = open('employee.txt', 'w') employee_file.write('David - Software Developer') print(employee_file.readable()) employee_file.close()
# Copyright 2020 The Cross-Media Measurement Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
"""Repository rules/macros for Google Cloud Spanner Emulator.""" def _cloud_spanner_emulator_impl(rctx): version = rctx.attr.version sha256 = rctx.attr.sha256 url = 'https://storage.googleapis.com/cloud-spanner-emulator/releases/{version}/cloud-spanner-emulator_linux_amd64-{version}.tar.gz'.format(version=...
# Copyright 2021 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
""" This module provides methods to perform the input validations. """ class Validators: """Validator class""" @classmethod def validate_string(cls, value: str) -> bool: """Validate the string Args: value: value to be checked """ return bool(value and value.str...
__author__ = 'Lena' class Group: def __init__(self, name, header, footer): self.name=name self.header=header self.footer=footer
__author__ = 'Lena' class Group: def __init__(self, name, header, footer): self.name = name self.header = header self.footer = footer
TICKET_PRODUCTS = ''' query getTicketProducts { tutorialProducts { id type name nameKo nameEn desc descKo descEn warning warningKo warningEn startAt finishAt total remainingCount isSoldOut owner { profile { name nameKo n...
ticket_products = '\nquery getTicketProducts {\n tutorialProducts {\n id\n type\n name\n nameKo\n nameEn\n desc\n descKo\n descEn\n warning\n warningKo\n warningEn\n startAt\n finishAt\n total\n remainingCount\n isSoldOut\n owner {\n profile {\n name\n ...
""" International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on. For convenience, the full table for the 26 letters of the English alphabet is given below: [".-","-...","-.-.","-..","."...
""" International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on. For convenience, the full table for the 26 letters of the English alphabet is given below: [".-","-...","-.-.","-..","."...
# This resets variables every time the Supreme While Loop is reset # If you tried to mess around with this code, you'll find results/errors on the second time the While Loop is executed # Messing with this code will generally not break anything on the first topic that Indra talks About yesnorep = True ignoreinteract =...
yesnorep = True ignoreinteract = False repeating = 0 cussed = False sensitive = False topicdone = False nevermind = False if ignoreinteract == False: interactions = interactions + 1 if loveBonus == 3 and interest < 75: print('Hey, ' + name + '.') sleep(1.5) print("Recently I can't help but feel that all...
class AbstractRemoteDatabase(object): """ Abstract base class which all remote database connections must inherit from Defines the public interface of any implementation """ def connect(self, **kwargs): """Connect to the course info database """ raise NotImplementedErro...
class Abstractremotedatabase(object): """ Abstract base class which all remote database connections must inherit from Defines the public interface of any implementation """ def connect(self, **kwargs): """Connect to the course info database """ raise not_implemented_err...
__author__ = "Lucas Grulich (grulich@uni-mainz.de)" __version__ = "0.0.14" # --- Globals ---------------------------------------------------------------------------------------------------------- MONOSCALE_SHADOWLEVEL = 1 OAP_FILE_EXTENSION = ".oap" DEFAULT_TYPE = "ARRAY2D" SLICE_SIZE = 64 # --- Markers -------------...
__author__ = 'Lucas Grulich (grulich@uni-mainz.de)' __version__ = '0.0.14' monoscale_shadowlevel = 1 oap_file_extension = '.oap' default_type = 'ARRAY2D' slice_size = 64 marker = {'poisson': 7, 'flood_fill': 8} color = {0: 0, 1: 100, 2: 200, 3: 255, MARKER['poisson']: 50} undefined = b'u' indefinable = b'i' erroneous =...
# -*- coding: utf-8 -*- class Java(object): KEY = 'java' LABEL = 'Java' DEPENDENCIES = ['java', 'javac'] TEMP_DIR = 'java' SUFFIX = '.java' # javac {class_path} tmp/Estimator.java # class_path = '-cp ./gson.jar' CMD_COMPILE = 'javac {class_path} {src_dir}/{src_file}' # java {cl...
class Java(object): key = 'java' label = 'Java' dependencies = ['java', 'javac'] temp_dir = 'java' suffix = '.java' cmd_compile = 'javac {class_path} {src_dir}/{src_file}' cmd_execute = 'java {class_path} {dest_dir}/{dest_file}'
#Dictionaries Challenge 22: Database Admin Program print("Welcome to the Database Admin Program") #Create a dictionary to hold all username:password key-value pairs log_on_information = { 'mooman74':'alskes145', 'meramo1986':'kehns010101', 'nickyD':'world1star', 'george2':'booo3oha', 'admin00':'a...
print('Welcome to the Database Admin Program') log_on_information = {'mooman74': 'alskes145', 'meramo1986': 'kehns010101', 'nickyD': 'world1star', 'george2': 'booo3oha', 'admin00': 'admin1234'} username = input('Enter your username: ') if username in log_on_information.keys(): password = input('Enter your password:...
class Inventory: def __init__(self): self._prisonKeys = False self._sunflowerSeeds = False self._guardiansMoney = False self._guardiansSword = False self._dragonsKey = False @property def prison_keys(self): return self._prisonKeys @prison_keys.setter ...
class Inventory: def __init__(self): self._prisonKeys = False self._sunflowerSeeds = False self._guardiansMoney = False self._guardiansSword = False self._dragonsKey = False @property def prison_keys(self): return self._prisonKeys @prison_keys.setter ...
class Vulnerability: """ Class for representing necessary information about vulnerability. Dictionary is used for storing cvssv2 and cvssv3 because of constant access. cpe_type contains values: 'h' for hardware, 'a' for application, 'o' for operating system. """ def __in...
class Vulnerability: """ Class for representing necessary information about vulnerability. Dictionary is used for storing cvssv2 and cvssv3 because of constant access. cpe_type contains values: 'h' for hardware, 'a' for application, 'o' for operating system. """ def __in...
_close_methods = [] def session_close_method(close_method: callable) -> callable: """ A method that will be automatically called when the session closes. :param close_method: Method to call on session close. :return: The decorated method that will be called on session close. """ _close_met...
_close_methods = [] def session_close_method(close_method: callable) -> callable: """ A method that will be automatically called when the session closes. :param close_method: Method to call on session close. :return: The decorated method that will be called on session close. """ _close_meth...
#!/usr/bin/env python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required...
"""Deal with Microsoft-specific Authenticode data.""" win_cert_revision_1_0 = 256 win_cert_revision_2_0 = 512 win_cert_type_x509 = 1 win_cert_type_pkcs_signed_data = 2 win_cert_type_reserved_1 = 3 win_cert_type_ts_stack_signed = 4 class Pecoffblob(object): """Encapsulating class for Microsoft-specific Authenticode...
def snail(array): temp_list = [] if array and len(array) > 1: if isinstance(array[0], list): temp_list.extend(array[0]) else: temp_list.append(array[0]) array.pop(0) for lis_index in range(len(array)): temp_list.append(array[lis_index][-1]) ...
def snail(array): temp_list = [] if array and len(array) > 1: if isinstance(array[0], list): temp_list.extend(array[0]) else: temp_list.append(array[0]) array.pop(0) for lis_index in range(len(array)): temp_list.append(array[lis_index][-1]) ...
def get_scale_factor(input_units, sampling_rate=None): if input_units=='ms': return 1e3 elif input_units=='s': return 1 elif input_units=='samples': if sampling_rate is None: raise ValueError('Must provide sampling_rate if input_units=="samples"') return sampling_...
def get_scale_factor(input_units, sampling_rate=None): if input_units == 'ms': return 1000.0 elif input_units == 's': return 1 elif input_units == 'samples': if sampling_rate is None: raise value_error('Must provide sampling_rate if input_units=="samples"') return...
config = {'luna_raw':'/root/ssd_data/LUNA/', 'luna_data':'/research/dept8/jzwang/dataset/LUNA16/combined/', 'preprocess_result_path':'/research/dept8/jzwang/dataset/HKU/preprocessed/numpy/', 'luna_abbr':'./labels/shorter.csv', 'luna_label':'./labels/lunaqualified_all.csv', ...
config = {'luna_raw': '/root/ssd_data/LUNA/', 'luna_data': '/research/dept8/jzwang/dataset/LUNA16/combined/', 'preprocess_result_path': '/research/dept8/jzwang/dataset/HKU/preprocessed/numpy/', 'luna_abbr': './labels/shorter.csv', 'luna_label': './labels/lunaqualified_all.csv', 'luna_candidate_label': './labels/luna_ca...
#! /usr/bin/python3 # -*- coding:utf-8 -*- """ Define functions relative to bcv. """ def checkBcv(bcv): """Check that a bcv is valid. Valid syntax: BBCCVV BBCCVV-vv BBCCVV-ccvv BBCCVV-BBccvv """ if len(bcv) == 6: return True elif len(bcv) == 9: re...
""" Define functions relative to bcv. """ def check_bcv(bcv): """Check that a bcv is valid. Valid syntax: BBCCVV BBCCVV-vv BBCCVV-ccvv BBCCVV-BBccvv """ if len(bcv) == 6: return True elif len(bcv) == 9: return bcv[4:6] < bcv[7:9] elif len(bcv) ==...
# https://www.codechef.com/SEPT20B/problems/TREE2 T = int(input()) for _ in range(T): x = input() l = list(map(int, input().split())) s = set(l) m = min(s) ops = len(s) if m: print(ops) else: print(ops-1)
t = int(input()) for _ in range(T): x = input() l = list(map(int, input().split())) s = set(l) m = min(s) ops = len(s) if m: print(ops) else: print(ops - 1)
class SessionGenerator(object): session: "TrainingSession" def __init__(self, training_cycle, fatigue_rating, current_training_max): load_size = self.determine_load_size( fatigue_rating, training_cycle.previous_large_load_train...
class Sessiongenerator(object): session: 'TrainingSession' def __init__(self, training_cycle, fatigue_rating, current_training_max): load_size = self.determine_load_size(fatigue_rating, training_cycle.previous_large_load_training_max, current_training_max) self.session = self.generate_session(t...
# -*- coding: utf-8 -*- """ @create: 2019-05-30 22:19:12. @author: ppolxda @desc: """ class Error(Exception): pass class InputError(Error): pass class DuplicateError(Error): pass class IndexExpiredError(Error): pass
""" @create: 2019-05-30 22:19:12. @author: ppolxda @desc: """ class Error(Exception): pass class Inputerror(Error): pass class Duplicateerror(Error): pass class Indexexpirederror(Error): pass
DROPS = ((3, 'Pling'), (5, 'Plang'), (7, 'Plong')) def convert(number): """ Converts a number to a string according to the raindrop sounds. """ return "".join(sound for factor, sound in DROPS if number % factor == 0) or str(number)
drops = ((3, 'Pling'), (5, 'Plang'), (7, 'Plong')) def convert(number): """ Converts a number to a string according to the raindrop sounds. """ return ''.join((sound for (factor, sound) in DROPS if number % factor == 0)) or str(number)
filename = "CCaseScene.unity" subA = ("<<<<<<< Updated upstream\n") subB = ("=======\n") subC = (">>>>>>> Stashed changes\n") with open(filename, 'r+') as f: data = f.read() count = 0 # Iterate starts while True: # Find indexes start, end = data.index(subA), data.index(subB) # Slice string ...
filename = 'CCaseScene.unity' sub_a = '<<<<<<< Updated upstream\n' sub_b = '=======\n' sub_c = '>>>>>>> Stashed changes\n' with open(filename, 'r+') as f: data = f.read() count = 0 while True: (start, end) = (data.index(subA), data.index(subB)) data = data[:start] + data[end:] data =...
# New feature in Python 3.8, assignment expressions (known as the walrus operator) # Assignment expression are written with a new notation (:=). This operator is often # called the walrus operator as it resembles the eyes and tusks of a walrus on its side. # # Video explanation: https://realpython.com/lessons/ass...
walrus = True print(walrus) print((walrus := True)) inputs = list() while True: current = input('Write something: ') if current == 'quit': break inputs.append(current) inputs = list() while (current := input('Write something: ')) != 'quit': inputs.append(current)
def solve(): A = int(input()) row = (A + 2) // 3 # from (100 100) to (100+row-1, 100) board = [] for _ in range(1000): board.append([0]*1000) I = J = 100 # [2, 999] for _ in range(1000): print('{} {}'.format(I, J)) I_, J_ = map(int, input().split()) if I_ == 0 and...
def solve(): a = int(input()) row = (A + 2) // 3 board = [] for _ in range(1000): board.append([0] * 1000) i = j = 100 for _ in range(1000): print('{} {}'.format(I, J)) (i_, j_) = map(int, input().split()) if I_ == 0 and J_ == 0: return board[I...
deleteObject = True editObject = True getObject = {'id': 1234, 'fingerprint': 'aa:bb:cc:dd', 'label': 'label', 'notes': 'notes', 'key': 'ssh-rsa AAAAB3N...pa67 user@example.com'} createObject = getObject getAllObjects = [getObject]
delete_object = True edit_object = True get_object = {'id': 1234, 'fingerprint': 'aa:bb:cc:dd', 'label': 'label', 'notes': 'notes', 'key': 'ssh-rsa AAAAB3N...pa67 user@example.com'} create_object = getObject get_all_objects = [getObject]
''' Created on Apr 27, 2015 @author: DHawkins ''' POSITION = [ {'abbrev': 'al', 'column': 7, 'row': 7, 'state': 'alabama'}, {'abbrev': 'ak', 'column': 1, 'row': 8, 'state': 'alaska'}, {'abbrev': 'az', 'column': 2, 'row': 6, 'state': 'arizona'}, {'abbrev': 'ar', 'column': 5, 'row': 6, 'state': 'arkansa...
""" Created on Apr 27, 2015 @author: DHawkins """ position = [{'abbrev': 'al', 'column': 7, 'row': 7, 'state': 'alabama'}, {'abbrev': 'ak', 'column': 1, 'row': 8, 'state': 'alaska'}, {'abbrev': 'az', 'column': 2, 'row': 6, 'state': 'arizona'}, {'abbrev': 'ar', 'column': 5, 'row': 6, 'state': 'arkansas'}, {'abbrev': 'c...
# A ring buffer is a non-growable buffer with a fixed size. When the ring buffer is full # and a new element is inserted, the oldest element in the ring buffer is overwritten with # the newest element. This kind of data structure is very useful for use cases such as # storing logs and history information, where you typ...
class Ringbuffer: def __init__(self, capacity): self.capacity = capacity self.current = 0 self.storage = [None] * capacity def append(self, item): if self.current == self.capacity: self.current = 0 self.storage[self.current] = item self.current += 1 ...
HEADER_JSON_CONTENT = { 'Content-type': 'application/json', 'Accept': 'text/plain' } SUCCESS_MESSAGES = { 201: "Created Propertie: {title} in {provinces} province(s)", } ERROR_MESSAGES = { 422: { 'message': "Please, verify data for register this propertie" }, 404: { 'message': "Pr...
header_json_content = {'Content-type': 'application/json', 'Accept': 'text/plain'} success_messages = {201: 'Created Propertie: {title} in {provinces} province(s)'} error_messages = {422: {'message': 'Please, verify data for register this propertie'}, 404: {'message': 'Provide an valid ID to retrive the queried propert...
#!/usr/bin/env python def reverse(string): """Reverse a given string.""" return string[::-1] def main(): print(reverse('a')) print(reverse('abcd')) print(reverse('hello world')) if __name__ == '__main__': main()
def reverse(string): """Reverse a given string.""" return string[::-1] def main(): print(reverse('a')) print(reverse('abcd')) print(reverse('hello world')) if __name__ == '__main__': main()
jogador = {} soma = 0 gols = [] jogador['nome'] = str(input('Nome do Jogador: ')) jogador['njogos'] = int(input(f'Quanta partidas {jogador["nome"]} Jogou?')) for v in range(0, jogador['njogos']): temp = int(input(f'Quantos gols na partida {v}? ')) soma += temp gols.append(temp) jogador['gols'] = gols[:] p...
jogador = {} soma = 0 gols = [] jogador['nome'] = str(input('Nome do Jogador: ')) jogador['njogos'] = int(input(f"Quanta partidas {jogador['nome']} Jogou?")) for v in range(0, jogador['njogos']): temp = int(input(f'Quantos gols na partida {v}? ')) soma += temp gols.append(temp) jogador['gols'] = gols[:] pri...
""" @file @brief Exceptions. """ class RenderException(Exception): """ Custom exception for all class and functions below. """ pass
""" @file @brief Exceptions. """ class Renderexception(Exception): """ Custom exception for all class and functions below. """ pass
# -*- coding: utf-8 -*- # This file is generated from NI-TClk API metadata version 255.0.0d0 functions = { 'ConfigureForHomogeneousTriggers': { 'documentation': { 'description': '\nConfigures the attributes commonly required for the TClk synchronization\nof device sessions with homogeneous trigg...
functions = {'ConfigureForHomogeneousTriggers': {'documentation': {'description': '\nConfigures the attributes commonly required for the TClk synchronization\nof device sessions with homogeneous triggers in a single PXI chassis or\na single PC. Use niTClk_ConfigureForHomogeneousTriggers to configure\nthe attributes for...
# !/usr/bin/env python # -*- coding: utf-8 -*- ''' Description: Given an integer, write a function to determine if it is a power of two. Tags: Math, Bit Manipulation O(1) runtime; O(1) space ''' class Solution(object): def isPowerOfTwo(self, n): """ :type n: int :rtype: bool "...
""" Description: Given an integer, write a function to determine if it is a power of two. Tags: Math, Bit Manipulation O(1) runtime; O(1) space """ class Solution(object): def is_power_of_two(self, n): """ :type n: int :rtype: bool """ return n > 0 and n & n - 1 == 0
class Lease(object): """ A lease. :ivar id: ID of the lease :ivar ttl: time to live for this lease """ def __init__(self, lease_id, ttl, etcd_client=None): self.id = lease_id self.ttl = ttl self.etcd_client = etcd_client async def _get_lease_info(self, *, keys=Tru...
class Lease(object): """ A lease. :ivar id: ID of the lease :ivar ttl: time to live for this lease """ def __init__(self, lease_id, ttl, etcd_client=None): self.id = lease_id self.ttl = ttl self.etcd_client = etcd_client async def _get_lease_info(self, *, keys=True...
""" Given a set of complex values, find their product. Example For real = [1, 2] and imag = [1, 3], the output should be arrayComplexElementsProduct(real, imag) = [-1, 5]. The task is to calculate product of 1 + 1 * i and 2 + 3 * i, so the answer is (1 + 1i) * (2 + 3i) = -1 + 5i. """ def arrayComplexElementsProduc...
""" Given a set of complex values, find their product. Example For real = [1, 2] and imag = [1, 3], the output should be arrayComplexElementsProduct(real, imag) = [-1, 5]. The task is to calculate product of 1 + 1 * i and 2 + 3 * i, so the answer is (1 + 1i) * (2 + 3i) = -1 + 5i. """ def array_complex_elements_prod...
print(any([True, 1, ""])) print(all([True, 1, ""])) print(dict(zip([1, 2, 3], "abc")))
print(any([True, 1, ''])) print(all([True, 1, ''])) print(dict(zip([1, 2, 3], 'abc')))
top = [2,3,4,5,6] # lst = [1,0,0,4,5] lst = [1,2,3,4,5] k = [9,9,0,0,0] lst1 = [8,3,9,6,4,7,5,2,1] lst2 = [10,11,12,8,3,9,6,4,7,5,2,1] lst3 = [8,9,3,6,7,4,5,2,1] lst4 = [8,3,9,6,4,7,5,2,1] k = [9,0,0,0,0,0,0,0] k = k[::-1] def main(): subtract_1(lst1, k) def helper1(lst, start): new_lst = lst[start:] ind...
top = [2, 3, 4, 5, 6] lst = [1, 2, 3, 4, 5] k = [9, 9, 0, 0, 0] lst1 = [8, 3, 9, 6, 4, 7, 5, 2, 1] lst2 = [10, 11, 12, 8, 3, 9, 6, 4, 7, 5, 2, 1] lst3 = [8, 9, 3, 6, 7, 4, 5, 2, 1] lst4 = [8, 3, 9, 6, 4, 7, 5, 2, 1] k = [9, 0, 0, 0, 0, 0, 0, 0] k = k[::-1] def main(): subtract_1(lst1, k) def helper1(lst, start): ...
day = '2' with open(f'2015/data/day_{day}.in', 'r', encoding='utf-8') as f: content = f.read().strip().split('\n') def make_tup(row): i = row.index('x') a = row[:i] row = row[i + 1:] i = row.index('x') b = row[:i] c = row[i + 1:] return int(a), int(b), int(c) def area(a, b, c): re...
day = '2' with open(f'2015/data/day_{day}.in', 'r', encoding='utf-8') as f: content = f.read().strip().split('\n') def make_tup(row): i = row.index('x') a = row[:i] row = row[i + 1:] i = row.index('x') b = row[:i] c = row[i + 1:] return (int(a), int(b), int(c)) def area(a, b, c): r...
def translate(): return "jQuery(document).ready(function(){jQuery('body').translate('%s');});" % request.args(0).split('.')[0] def changeLanguage(): session._language = request.args[0] #T.force(request.args[0]) #T.set_current_languages(str(request.args[0]),str(request.args[0]) + '-' + str(req...
def translate(): return "jQuery(document).ready(function(){jQuery('body').translate('%s');});" % request.args(0).split('.')[0] def change_language(): session._language = request.args[0] if len(request.args) == 5: redirect(url(request.args[1], request.args[2], request.args[3], args=request.args[4]))...
def main(): square = int(input("Calculate square root of: ")) print("square root of " + str(square) + " is " + str(binsquareroot(square))) def binsquareroot(square): if square < 1: return "an imaginair number" if square == 1: return 1 left = 1 right = square mid =...
def main(): square = int(input('Calculate square root of: ')) print('square root of ' + str(square) + ' is ' + str(binsquareroot(square))) def binsquareroot(square): if square < 1: return 'an imaginair number' if square == 1: return 1 left = 1 right = square mid = right ...
def update_game(api, game, step_fn): """ Takes care of doing one update tick: - call the player's AI - send actions chosen by AI :param api: API object to communicate with the server :param game: The current game's state. :param step_fn: function to call to execute the player's AI ...
def update_game(api, game, step_fn): """ Takes care of doing one update tick: - call the player's AI - send actions chosen by AI :param api: API object to communicate with the server :param game: The current game's state. :param step_fn: function to call to execute the player's AI ...
# helpers.py def url_join(*args, end_slash = True): strip_args = [str(a).rstrip("/") for a in args] url = "/".join(strip_args) if end_slash and not url.endswith("/"): url = url + "/" return url
def url_join(*args, end_slash=True): strip_args = [str(a).rstrip('/') for a in args] url = '/'.join(strip_args) if end_slash and (not url.endswith('/')): url = url + '/' return url
# # Copyright (c) 2010-2016, Fabric Software Inc. All rights reserved. # class DirQualTypeInfo: def __init__(self, dir_qual, type_info): self.dir_qual = dir_qual self.type_info = type_info @property def dq(self): return self.dir_qual @property def ti(self): return self.type_info def g...
class Dirqualtypeinfo: def __init__(self, dir_qual, type_info): self.dir_qual = dir_qual self.type_info = type_info @property def dq(self): return self.dir_qual @property def ti(self): return self.type_info def get_desc(self): return '%s:%s' % (self.di...
grade = 95 if grade >= 90: print("A") elif grade >= 80: print("B") elif grade >= 70: print("C") elif grade >= 60: print("D") else: print("F")
grade = 95 if grade >= 90: print('A') elif grade >= 80: print('B') elif grade >= 70: print('C') elif grade >= 60: print('D') else: print('F')
def gen_src(count): for i in range(1, count): data = "".join(["%d" % x for x in range(1, 10000)]) native.genrule( name = "generated_class_%d" % i, out = "Class%d.java" % i, bash = "echo -e 'package gen;\npublic class Class%d { static String data = \"%s\"; }' > $OU...
def gen_src(count): for i in range(1, count): data = ''.join(['%d' % x for x in range(1, 10000)]) native.genrule(name='generated_class_%d' % i, out='Class%d.java' % i, bash='echo -e \'package gen;\npublic class Class%d { static String data = "%s"; }\' > $OUT' % (i, data)) native.android_libr...
##Exemplo retirado do site http://code.tutsplus.com/tutorials/beginning-test-driven-development-in-python--net-30137 ##//lhekheklqhlekhqkehqkehqkhelqw ##//ljkfhjdhfjkdhfkjlsdhlfkhslkjkljdflksgflsgdf ##//lkhdsklfskfgshgfsjhgfs class Calculator(object): def add(self, x, y): number_types = (int, float, compl...
class Calculator(object): def add(self, x, y): number_types = (int, float, complex) if instance(x, number_types) and instance(y, number_types): return x + y else: raise ValueError def sub(self, x, y): number_types = (int, float, complex) if insta...
''' Prompt: Write a function bestSum(targetSum, numbers) that takes in a targetSum and an array of numbers as arguments. The function should return an array containing the shortest combination of numbers that add up to exactly the targetSum. If there is a tie for the shotest combination, you may return any of the sh...
""" Prompt: Write a function bestSum(targetSum, numbers) that takes in a targetSum and an array of numbers as arguments. The function should return an array containing the shortest combination of numbers that add up to exactly the targetSum. If there is a tie for the shotest combination, you may return any of the sh...
apps_details = [ { "app": "Learning xc functional from experimental data", "repo": "https://github.com/mfkasim1/xcnn", # leave blank if no repo available # leave blank if no paper available, strongly suggested to link to open-access paper "paper": "https://arxiv.org/abs/2102.04229",...
apps_details = [{'app': 'Learning xc functional from experimental data', 'repo': 'https://github.com/mfkasim1/xcnn', 'paper': 'https://arxiv.org/abs/2102.04229'}, {'app': 'Basis optimization', 'repo': 'https://github.com/diffqc/dqc-apps/tree/main/01-basis-opt', 'paper': ''}, {'app': 'Alchemical perturbation', 'repo': '...
class TempChDir: """ Context manager to step into a directory temporarily. Use in a `with` block: with TempChDir(path): ...do stuff... This automatically changes cwd if necessary, upon entry of the block, and changes it back on exit. Note that if `path` is ".", this is ...
class Tempchdir: """ Context manager to step into a directory temporarily. Use in a `with` block: with TempChDir(path): ...do stuff... This automatically changes cwd if necessary, upon entry of the block, and changes it back on exit. Note that if `path` is ".", this is ...
class ChainMap: def __init__(self, *maps): if maps: self.maps = list(maps) else: self.maps = [{}] def __getitem__(self, k): for m in self.maps: if k in m: return m[k] raise KeyError(k) def __setitem__(self, k, v): ...
class Chainmap: def __init__(self, *maps): if maps: self.maps = list(maps) else: self.maps = [{}] def __getitem__(self, k): for m in self.maps: if k in m: return m[k] raise key_error(k) def __setitem__(self, k, v): ...
# # PySNMP MIB module BDCOM-FLASH (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BDCOM-FLASH # Produced by pysmi-0.3.4 at Wed May 1 11:36:39 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, 0...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, constraints_intersection, constraints_union, value_range_constraint, single_value_constraint) ...
# https://www.codewars.com/kata/human-readable-duration-format def format_duration(seconds): if not seconds: return "now" units = [ ("year", 365 * 24 * 60 * 60), ("day", 24 * 60 * 60), ("hour", 60 * 60), ("minute", 60), ("second", 1) ] parts = [] ...
def format_duration(seconds): if not seconds: return 'now' units = [('year', 365 * 24 * 60 * 60), ('day', 24 * 60 * 60), ('hour', 60 * 60), ('minute', 60), ('second', 1)] parts = [] for (unit, divisor) in units: (quantity, seconds) = divmod(seconds, divisor) if quantity: ...
class RotationMatrix(object): def __init__(self, M, N, entries): self.M, self.N = M, N self.entries = dict(entries) self.tier_index = self._create_tier_index() def __str__(self): string = "" for i in range(self.M): for j in range(self.N): ...
class Rotationmatrix(object): def __init__(self, M, N, entries): (self.M, self.N) = (M, N) self.entries = dict(entries) self.tier_index = self._create_tier_index() def __str__(self): string = '' for i in range(self.M): for j in range(self.N): ...
__version__ = "0.0.10" __description__ = "Python client for interfacing with NTCore" __license__ = "Apache 2.0" __maintainer__ = "NTCore" __maintainer_email__ = "info@nantutech.com" __title__ = "ntcore" __url__ = "https://www.nantu.io/"
__version__ = '0.0.10' __description__ = 'Python client for interfacing with NTCore' __license__ = 'Apache 2.0' __maintainer__ = 'NTCore' __maintainer_email__ = 'info@nantutech.com' __title__ = 'ntcore' __url__ = 'https://www.nantu.io/'
def get_the_2nd_lower( stu_list ): min_grade = min( stu_list, key = lambda x: x[1])[1] #print( min_grade ) stu_list_without_lowest = [ s for s in stu_list if s[1] != min_grade] # sort with student's name of ascending order stu_list_without_lowest.sort( key = lambda x:x[0]) # get second lowe...
def get_the_2nd_lower(stu_list): min_grade = min(stu_list, key=lambda x: x[1])[1] stu_list_without_lowest = [s for s in stu_list if s[1] != min_grade] stu_list_without_lowest.sort(key=lambda x: x[0]) second_lower = min(stu_list_without_lowest, key=lambda x: x[1])[1] for s in stu_list_without_lowest:...
''' Given a non-empty string s and an integer k, rearrange the string such that the same characters are at least distance k from each other. All input strings are given in lowercase letters. If it is not possible to rearrange the string, return an empty string "". Example 1: Input: s = "aabbcc", k = 3 Output: "abcab...
""" Given a non-empty string s and an integer k, rearrange the string such that the same characters are at least distance k from each other. All input strings are given in lowercase letters. If it is not possible to rearrange the string, return an empty string "". Example 1: Input: s = "aabbcc", k = 3 Output: "abcab...
class HttpListenerPrefixCollection(object,ICollection[str],IEnumerable[str],IEnumerable): """ Represents the collection used to store Uniform Resource Identifier (URI) prefixes for System.Net.HttpListener objects. """ def Add(self,uriPrefix): """ Add(self: HttpListenerPrefixCollection,uriPrefix: str) Add...
class Httplistenerprefixcollection(object, ICollection[str], IEnumerable[str], IEnumerable): """ Represents the collection used to store Uniform Resource Identifier (URI) prefixes for System.Net.HttpListener objects. """ def add(self, uriPrefix): """ Add(self: HttpListenerPrefixCollection,uriPrefix: ...
""" Events app for the CDH webapp. Provides event types, locations, and events """ default_app_config = "cdhweb.events.apps.EventsConfig"
""" Events app for the CDH webapp. Provides event types, locations, and events """ default_app_config = 'cdhweb.events.apps.EventsConfig'
def padovan(n): res=[1,1,1] for i in range(n-2): res.append(res[-2]+res[-3]) return res[n]
def padovan(n): res = [1, 1, 1] for i in range(n - 2): res.append(res[-2] + res[-3]) return res[n]
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # Recursive DFS class Solution: def maxDepth(self, root: TreeNode) -> int: if root == None: return 0 else: left_height = se...
class Treenode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def max_depth(self, root: TreeNode) -> int: if root == None: return 0 else: left_height = self.maxDepth(root.left) right_height = ...
# Copyright (c) 2020, Vercer Ltd. Rights set out in LICENCE.txt class StatementAlreadyPreparedException(Exception): pass class StatementNotPreparedException(Exception): pass class PreparedQueryNotSupported(Exception): pass class CannotAlterPreparedStatementQuerySet(Exception): pass class Prepa...
class Statementalreadypreparedexception(Exception): pass class Statementnotpreparedexception(Exception): pass class Preparedquerynotsupported(Exception): pass class Cannotalterpreparedstatementqueryset(Exception): pass class Preparedstatementnotyetexecuted(Exception): pass class Statementnotreg...
__version__ = ( '1.2' ".3" ) __custom__ = 42
__version__ = '1.2.3' __custom__ = 42
TITLE = "Jumpy Boi" # screen dims WIDTH = 1280 HEIGHT = 760 # frames per second FPS = 60 # colors WHITE = (255, 255, 255) BLACK = (0,0,0) REDDISH = (240,55,66) SKY_BLUE = (143, 185, 252) BROWN = (153, 140, 113) GRAY = (110, 160, 149) DARK_BLUE = (0, 23, 176) FONT_NAME = 'arial' SPRITESHEET = "spritesheet_jumper.png" # ...
title = 'Jumpy Boi' width = 1280 height = 760 fps = 60 white = (255, 255, 255) black = (0, 0, 0) reddish = (240, 55, 66) sky_blue = (143, 185, 252) brown = (153, 140, 113) gray = (110, 160, 149) dark_blue = (0, 23, 176) font_name = 'arial' spritesheet = 'spritesheet_jumper.png' hs_file = 'highscore.txt' player_acc = 0....
""" Stride.py Author: Matthew Yu, Array Lead (2020). Contact: matthewjkyu@gmail.com Created: 11/19/20 Last Modified: 02/27/21 Description: Implementation of the Stride class. """ # Library Imports. # Custom Imports. class Stride: """ The Stride class provides the base API for derived classes to calcula...
""" Stride.py Author: Matthew Yu, Array Lead (2020). Contact: matthewjkyu@gmail.com Created: 11/19/20 Last Modified: 02/27/21 Description: Implementation of the Stride class. """ class Stride: """ The Stride class provides the base API for derived classes to calculate the stride (change of VREF) for vario...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright (C) 2021-2022 F4PGA Authors. # # Use of this source code is governed by a ISC-style # license that can be found in the LICENSE file or at # https://opensource.org/licenses/ISC # # SPDX-License-Identifier: ISC # -- General configuration ---------------------...
extensions = [] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = 'fpga-interchange-tests' copyright = '2020, Various' author = 'Various' version = '0.1' release = '0.1' language = None exclude_patterns = [] pygments_style = 'default' todo_include_todos = False html_show_sourcelink =...
mail = "To Tax authortiy, Last year earnings of our consultants are given as below (in GBP)\n \ Sirish Dhulipala: 4000 for Jan, 4100 for Feb, 4200 For March, 3900 for April, 4000 May, 4100 June, 4000 July, 4000 August, 4000 September, 4000 October, 4000 November, 4000 December \n \ Anand Reddy: 18000 for first half an...
mail = 'To Tax authortiy, Last year earnings of our consultants are given as below (in GBP)\n Sirish Dhulipala: 4000 for Jan, 4100 for Feb, 4200 For March, 3900 for April, 4000 May, 4100 June, 4000 July, 4000 August, 4000 September, 4000 October, 4000 November, 4000 December \n Anand Reddy: 18000 for first half and 200...
''' 2^(15) = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^(1000)? ''' n = 0 for _ in list(map(int, list(str(2**1000)))): n += _ print(n)
""" 2^(15) = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^(1000)? """ n = 0 for _ in list(map(int, list(str(2 ** 1000)))): n += _ print(n)
SAMTRYGG_JSON_API_URL = 'https://www.samtrygg.se/RentalObject/SearchResult' SAMTRYGG_DATASTORE_FILEPATH = '/datastore/samtrygg_data.json' SAMTRYGG_PROCESSED_DATASTORE_FILEPATH = '/datastore/processed_samtrygg_data.json' SAMTRYGG_PROCESSED_UNSEEN_DATASTORE_FILEPATH = '/datastore/processed_unseen_samtrygg_data.json'
samtrygg_json_api_url = 'https://www.samtrygg.se/RentalObject/SearchResult' samtrygg_datastore_filepath = '/datastore/samtrygg_data.json' samtrygg_processed_datastore_filepath = '/datastore/processed_samtrygg_data.json' samtrygg_processed_unseen_datastore_filepath = '/datastore/processed_unseen_samtrygg_data.json'
colors = { "Light": { "BackgroundColor": [1, 0, 1, .2], "TabColor": [1, 0, 1, .3], "ThemeColor": [1, 0, 1, 1], "BottomStatusColor": [.9, 0.9, 1, .8], "PrimaryTextColor": [0, 0, 0, 1], "SecondaryTextColor": [0, 0, 0, .5], "SelectorHoverColor": [.7, .7, .7, .5],...
colors = {'Light': {'BackgroundColor': [1, 0, 1, 0.2], 'TabColor': [1, 0, 1, 0.3], 'ThemeColor': [1, 0, 1, 1], 'BottomStatusColor': [0.9, 0.9, 1, 0.8], 'PrimaryTextColor': [0, 0, 0, 1], 'SecondaryTextColor': [0, 0, 0, 0.5], 'SelectorHoverColor': [0.7, 0.7, 0.7, 0.5], 'SelectorActiveColor': [1, 0, 1, 1], 'SelectorNormal...
# https://leetcode.com/problems/sort-colors/ # Related Topics: Array, Two Pointers, Sort # Difficulty: Medium # Initial thoughts: # Since we are dealing with a small and predefined set of possiblities (3 colors in this case) # we can loop once over the array, creating a frequency table for the 3 colors and then fi...
class Solution: def sort_colors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ count = [0] * 3 for el in nums: count[el] += 1 c = 0 for i in range(len(count)): for j in range(count[i]): ...
while True: line = input().split(' ') n = int(line[0]) n2 = int(line[1]) if n == n2 and n == 0: break num = line[1].replace(line[0], '') print(int(num) if num != '' else 0)
while True: line = input().split(' ') n = int(line[0]) n2 = int(line[1]) if n == n2 and n == 0: break num = line[1].replace(line[0], '') print(int(num) if num != '' else 0)
"""initialize paths, checkpoints etc""" # initialize screenshot path (default: "sh.png", for testing e.g. "assets/test/t1.jpeg") screenshot_path = "sh.png" # initialize checkpoint template file, located in "./assets/scene/" (default: "checkpoint") checkpoint = "checkpoint3" # initialize battle mode ("default_mode", ...
"""initialize paths, checkpoints etc""" screenshot_path = 'sh.png' checkpoint = 'checkpoint3' script_mode = 'arts_mode' recovery_times = 0 run_time = 1
def sort_twisted37(arr): return sorted(arr, key=lambda x: convert(x)) def convert(n): if "3" not in str(n) and "7" not in str(n): return n neg_flag=True if n<0 else False n=abs(n) total=0 for i in str(n): if i=="3": total=total*10+7 elif i=="7": to...
def sort_twisted37(arr): return sorted(arr, key=lambda x: convert(x)) def convert(n): if '3' not in str(n) and '7' not in str(n): return n neg_flag = True if n < 0 else False n = abs(n) total = 0 for i in str(n): if i == '3': total = total * 10 + 7 elif i == ...
## # DATA_ENCODING: # # In order to transmit data in a serialized format, string objects need to be encoded. Otherwise, # it is unclear how the characters are translated into raw bytes on the wire. This value should be # consistent with the encoding used on the flight software that is being communicated with. # # Tradi...
data_encoding = 'ascii'
# Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. # (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). # Find the minimum element. # You may assume no duplicate exists in the array. class Solution(object): def findMin(self, nums): """ O(logn) ...
class Solution(object): def find_min(self, nums): """ O(logn) O(1) :type nums: List[int] :rtype: int """ left = 0 right = len(nums) - 1 while left < right and nums[left] > nums[right]: middle = left + (right - left) / 2 ...
""" @no 35 @name Search Insert Position """ class Solution: def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if len(nums) == 0: return 0 else: for i in range(len(nums)): i...
""" @no 35 @name Search Insert Position """ class Solution: def search_insert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if len(nums) == 0: return 0 else: for i in range(len(nums)): ...
#bear in mind, this is log(n) def binary_search(arr, target): return binary_search_func(arr, 0, len(arr) - 1, target) def binary_search_func(arr, start_index, end_index, target): if start_index > end_index: return -1 mid_index = (start_index + end_index) // 2 if arr[mid_index] == target: ...
def binary_search(arr, target): return binary_search_func(arr, 0, len(arr) - 1, target) def binary_search_func(arr, start_index, end_index, target): if start_index > end_index: return -1 mid_index = (start_index + end_index) // 2 if arr[mid_index] == target: return mid_index elif ar...
try: age = int(input("Enter age:")) if age >= 18: print("You can vote") elif age > 0 and age <= 17: print("Too young to vote") else: print("You are a time traveller") except: print("Please enter age as integer")
try: age = int(input('Enter age:')) if age >= 18: print('You can vote') elif age > 0 and age <= 17: print('Too young to vote') else: print('You are a time traveller') except: print('Please enter age as integer')
class Solution: def equalPartition(self, N, arr): # Find the sum of the array summ = sum(arr) # If the sum is odd, then return false if summ % 2 != 0 : return 0 # This is the number we need to obtain during the computation required = summ // 2 ...
class Solution: def equal_partition(self, N, arr): summ = sum(arr) if summ % 2 != 0: return 0 required = summ // 2 table = [[False for _ in range(N + 1)] for _ in range(required + 1)] for i in range(N + 1): table[0][i] = True for i in range(1,...
class SignatureNoeud: def __init__(self,attributs, degre, degres_noeuds_adjacents,attributs_arretes): self.attributs = attributs self.degre = degre self.degres_noeuds_adjacents = degres_noeuds_adjacents self.attributs_arretes = attributs_arretes
class Signaturenoeud: def __init__(self, attributs, degre, degres_noeuds_adjacents, attributs_arretes): self.attributs = attributs self.degre = degre self.degres_noeuds_adjacents = degres_noeuds_adjacents self.attributs_arretes = attributs_arretes
class QueueException(Exception): pass class Empty(QueueException): pass class Full(QueueException): pass
class Queueexception(Exception): pass class Empty(QueueException): pass class Full(QueueException): pass
GITHUB_IPS_ONLY = False ENFORCE_SECRET = "" RETURN_SCRIPTS_INFO = True PORT = 8000
github_ips_only = False enforce_secret = '' return_scripts_info = True port = 8000
def number(): while True: try: num1 = int(input("Enter a number: ")) num2 = int(input("Enter a number: ")) break except ValueError: print("One of the values entered is not an integer, try again") while num1 < 1 or num2 < 1: print("One of the numbers isnt a positive int...
def number(): while True: try: num1 = int(input('Enter a number: ')) num2 = int(input('Enter a number: ')) break except ValueError: print('One of the values entered is not an integer, try again') while num1 < 1 or num2 < 1: print('One of th...
class GaApiError(Exception): """Base exception for API errors.""" class GaInvalidArgumentError(GaApiError): """Exception for errors on the report definition.""" class GaAuthenticationError(GaApiError): """Exception for UNAUTHENTICATED && PERMISSION_DENIED errors.""" class GaRateLimitError(GaApiError): ...
class Gaapierror(Exception): """Base exception for API errors.""" class Gainvalidargumenterror(GaApiError): """Exception for errors on the report definition.""" class Gaauthenticationerror(GaApiError): """Exception for UNAUTHENTICATED && PERMISSION_DENIED errors.""" class Garatelimiterror(GaApiError): ...
class IDError(Exception): pass class Service: def __init__(self, google_service_object, id = None): self.service = google_service_object self.id = id @property def id(self): if self.__id is None: raise IDError("Service id is uninitialized, use .initialize_env(...)")...
class Iderror(Exception): pass class Service: def __init__(self, google_service_object, id=None): self.service = google_service_object self.id = id @property def id(self): if self.__id is None: raise id_error('Service id is uninitialized, use .initialize_env(...)')...