content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class FileSystem: def __init__(self): self.fileSystem = {} self.endToken = '#' def createPath(self, path: str, value: int) -> bool: if path in {'', '/'}: return False if path.startswith('/'): tokens = path.split('/')[1:] currentNode = self.fi...
class Filesystem: def __init__(self): self.fileSystem = {} self.endToken = '#' def create_path(self, path: str, value: int) -> bool: if path in {'', '/'}: return False if path.startswith('/'): tokens = path.split('/')[1:] current_node = self....
print('-=-=-=-= DESAFIO 69 -=-=-=-=') print() pessoas = homens = mulheres = 0 while True: print('-'*30) print(' CADASTRE UMA PESSOA') print('-'*30) idade = int(input('Idade: ')) sexo = ' ' while sexo not in 'MF': sexo = str(input('Sexo: [M/F] ')).strip().upper()[0] if idade >= 1...
print('-=-=-=-= DESAFIO 69 -=-=-=-=') print() pessoas = homens = mulheres = 0 while True: print('-' * 30) print(' CADASTRE UMA PESSOA') print('-' * 30) idade = int(input('Idade: ')) sexo = ' ' while sexo not in 'MF': sexo = str(input('Sexo: [M/F] ')).strip().upper()[0] if idade >...
# Here are the tests belonging to e3sm suites. Format is # <test>.<grid>.<compset>. # suite_name -> (inherits_from, timelimit, [test [, mods[, machines]]]) # To elaborate, if no mods are needed, a string representing the testname is all that is needed. # If testmods are needed, a 2-ple must be provided (test, mods...
_tests = {'e3sm_land_developer': (None, '0:45:00', ('ERS.f19_f19.ICLM45', 'ERS.f19_f19.I1850CLM45CN', 'ERS.f09_g16.I1850CLM45CN', 'ERS.f19_f19.I20TRCLM45CN', 'SMS_Ld1.hcru_hcru.I1850CRUCLM45CN', ('ERS.f19_g16.I1850CNECACNTBC', 'clm-eca'), ('ERS.f19_g16.I1850CNECACTCBC', 'clm-eca'), ('SMS_Ly2_P1x1.1x1_smallvilleIA.ICLM4...
#!/usr/bin/env python # coding: utf-8 # In[ ]: print('<[100]> evalsupport module start') def deco_alpha(cls): print('<[200]> deco_alpha') def inner_1(self): print('<[300]> deci_alpha:inner_1') cls.method_y = inner_1 return cls class MetaAleph(type): print('<[400]> MetaAleph bo...
print('<[100]> evalsupport module start') def deco_alpha(cls): print('<[200]> deco_alpha') def inner_1(self): print('<[300]> deci_alpha:inner_1') cls.method_y = inner_1 return cls class Metaaleph(type): print('<[400]> MetaAleph body') def __init__(cls, name, bases, dic): prin...
# -*- coding: utf-8 -*- # Copyright 2019 Cohesity Inc. class PrivilegeIdEnum(object): """Implementation of the 'PrivilegeId' enum. Specifies unique id for a privilege. This number must be unique when creating a new privilege. Type for unique privilege Id values. All below enum values specify a va...
class Privilegeidenum(object): """Implementation of the 'PrivilegeId' enum. Specifies unique id for a privilege. This number must be unique when creating a new privilege. Type for unique privilege Id values. All below enum values specify a value for all uniquely defined privileges in Cohesity. ...
firstName = input() lastName = input() age = int(input()) town = input() print("You are %s %s, a %d-years old person from %s." % (firstName, lastName, age, town))
first_name = input() last_name = input() age = int(input()) town = input() print('You are %s %s, a %d-years old person from %s.' % (firstName, lastName, age, town))
# ===--- gyb_stdlib_support.py -----------------------*- coding: utf-8 -*-===// # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https://swift.org/LICENSE.t...
traversals = ['Forward', 'Bidirectional', 'RandomAccess'] def collection_for_traversal(traversal): if traversal == 'Forward': return 'Collection' elif traversal == 'Bidirectional': return 'BidirectionalCollection' elif traversal == 'RandomAccess': return 'RandomAccessCollection' ...
def _build_mimetype(resource_name, fmt="json"): return "application/vnd.reviewboard.org.%s+%s" % (resource_name, fmt) api_token_list_mimetype = _build_mimetype("api-tokens") api_token_item_mimetype = _build_mimetype("api-token") archived_item_mimetype = _build_mimetype("archived-review-request") change_list_mimetype =...
def _build_mimetype(resource_name, fmt='json'): return 'application/vnd.reviewboard.org.%s+%s' % (resource_name, fmt) api_token_list_mimetype = _build_mimetype('api-tokens') api_token_item_mimetype = _build_mimetype('api-token') archived_item_mimetype = _build_mimetype('archived-review-request') change_list_mimetyp...
num = int(input('Digite um numero inteiro:')) print('''Escolha uma das bases para conversao: [1] converter para BINARIO [2] converter para OCTAL [3] converter para HEXADECIMAL''') opcao = int(input('Escolha sua opcao:')) if opcao == 1: print(f'{num} convertido para BINARIO e igual a {bin(num)}') elif opcao == 2: ...
num = int(input('Digite um numero inteiro:')) print('Escolha uma das bases para conversao:\n[1] converter para BINARIO\n[2] converter para OCTAL\n[3] converter para HEXADECIMAL') opcao = int(input('Escolha sua opcao:')) if opcao == 1: print(f'{num} convertido para BINARIO e igual a {bin(num)}') elif opcao == 2: ...
class Eigenstates: def __init__(self, energies, array, extent, N, type): """Info about the eigenstates""" self.energies = energies self.array = array self.number = len(array) self.extent = extent self.N = N self.type = type
class Eigenstates: def __init__(self, energies, array, extent, N, type): """Info about the eigenstates""" self.energies = energies self.array = array self.number = len(array) self.extent = extent self.N = N self.type = type
f=input("enter no") beg=0 end=5 flag=0 while (beg<=end): mid=(end+beg)/2; if(list[mid]==f): print("found"); flag=1; break; elif(list[mid]<f): beg=beg+1; else: end=end-1; if(flag==0): print("not found");
f = input('enter no') beg = 0 end = 5 flag = 0 while beg <= end: mid = (end + beg) / 2 if list[mid] == f: print('found') flag = 1 break elif list[mid] < f: beg = beg + 1 else: end = end - 1 if flag == 0: print('not found')
""" mod2 """ def decorator(f): return f @decorator def func2(a, b): """ this is func2 """ return a, b @decorator class Class2(object): """ this is Class2 """
""" mod2 """ def decorator(f): return f @decorator def func2(a, b): """ this is func2 """ return (a, b) @decorator class Class2(object): """ this is Class2 """
def mergeOverlappingIntervals(array): if(len(array)<2): print(array) return array res = [] array.sort() print(array) prev = array[0] for i in range(1, len(array)): if(prev[1]>= array[i][0]): prev = [prev[0], max(prev[1], array[i][1])] else: ...
def merge_overlapping_intervals(array): if len(array) < 2: print(array) return array res = [] array.sort() print(array) prev = array[0] for i in range(1, len(array)): if prev[1] >= array[i][0]: prev = [prev[0], max(prev[1], array[i][1])] else: ...
DD_ORIGIN = "_dd_origin" AUTO_REJECT = 0 AUTO_KEEP = 1 USER_KEEP = 2 SAMPLE_RATE_METRIC_KEY = "_sample_rate" SAMPLING_PRIORITY_KEY = "_sampling_priority_v1" ENV_KEY = "env" VERSION_KEY = "version"
dd_origin = '_dd_origin' auto_reject = 0 auto_keep = 1 user_keep = 2 sample_rate_metric_key = '_sample_rate' sampling_priority_key = '_sampling_priority_v1' env_key = 'env' version_key = 'version'
class Angel: color = "white" feature = "wings" home = "Heaven" class Demon: color = "red" feature = "horns" home = "Hell" a_angel = Angel() a_demon = Demon() print(a_angel.color) print(a_angel.feature) print(a_angel.home) print(a_demon.color) print(a_demon.feature) print(a_demon.home)
class Angel: color = 'white' feature = 'wings' home = 'Heaven' class Demon: color = 'red' feature = 'horns' home = 'Hell' a_angel = angel() a_demon = demon() print(a_angel.color) print(a_angel.feature) print(a_angel.home) print(a_demon.color) print(a_demon.feature) print(a_demon.home)
#!/usr/bin/env python # -*- coding: utf-8 -*- M = int(input()) arr = [list(map(int, input().split())) for i in range(M)] ans = 0 f = [[0]*M for i in range(M)] def dfs(i, j): if i == M or i == -1 or j == M or j == -1: return f[i][j] = 1 if arr[i][j] == 0: return if i+1 != M and f[i+1][j...
m = int(input()) arr = [list(map(int, input().split())) for i in range(M)] ans = 0 f = [[0] * M for i in range(M)] def dfs(i, j): if i == M or i == -1 or j == M or (j == -1): return f[i][j] = 1 if arr[i][j] == 0: return if i + 1 != M and f[i + 1][j] == 0: dfs(i + 1, j) if i ...
class HashTable(): def __init__(self ,size = 1024): """initialization hash table""" self.max = size #length of list self.arr = [[] for i in range(self.max)] # or [None]*self.size\ we store key value pairs in each index [('Key',value),('Key',value)] def get_hash(self, key): """function to retur...
class Hashtable: def __init__(self, size=1024): """initialization hash table""" self.max = size self.arr = [[] for i in range(self.max)] def get_hash(self, key): """function to return the hash value using ASCII code""" h = 0 for char in key: h += ord...
SECRET_KEY = 'ratelimit' INSTALLED_APPS = ( 'ratelimit', ) RATELIMIT_USE_CACHE = 'default' CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'ratelimit-tests', }, 'connection-errors': { 'BACKEND': 'django.core.cache.backends.memcac...
secret_key = 'ratelimit' installed_apps = ('ratelimit',) ratelimit_use_cache = 'default' caches = {'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'ratelimit-tests'}, 'connection-errors': {'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': 'test-connection-...
web_server_ip = '0.0.0.0' web_server_port = 8080 checker_max_continuous_fail_count = 5 checker_period = 150 checker_judge_timeout = 5 checker_number = 50 fetcher_period = 60
web_server_ip = '0.0.0.0' web_server_port = 8080 checker_max_continuous_fail_count = 5 checker_period = 150 checker_judge_timeout = 5 checker_number = 50 fetcher_period = 60
lastback = False startback = 0 unprintable = [] for i in range(0x7f, 0x10001): c = chr(i) thisback = repr(c)[1] == "\\" if thisback != lastback: # print("{:08x}|{!r}: {}".format(i, c, thisback)) if thisback: startback = i else: end = i-1 if startback == end: unprintable.append("\\u{:04x}".format...
lastback = False startback = 0 unprintable = [] for i in range(127, 65537): c = chr(i) thisback = repr(c)[1] == '\\' if thisback != lastback: if thisback: startback = i else: end = i - 1 if startback == end: unprintable.append('\\u{:04x}'.f...
num, den = map(int, input().split(" ")) n = int(input()) p = num / den print(round(((1-p)**(n-1))*p, 3))
(num, den) = map(int, input().split(' ')) n = int(input()) p = num / den print(round((1 - p) ** (n - 1) * p, 3))
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param head: A ListNode @return: A ListNode """ def deleteDuplicates(self, head): if not head: return None cu...
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param head: A ListNode @return: A ListNode """ def delete_duplicates(self, head): if not head: return None ...
if 1: 2 elif 3: 4 elif 5: 6
if 1: 2 elif 3: 4 elif 5: 6
#!/usr/bin/env python """ Created by: Lee Bergstrand (2017) Description: The literature reference class. """ class LiteratureReference(object): """A class representing a literature reference supporting the existence of a genome property.""" def __init__(self, number, pubmed_id, title, authors, journal): ...
""" Created by: Lee Bergstrand (2017) Description: The literature reference class. """ class Literaturereference(object): """A class representing a literature reference supporting the existence of a genome property.""" def __init__(self, number, pubmed_id, title, authors, journal): """ Create...
#!/usr/bin/env python #-*- coding: utf-8 -*- UserAgents = [ "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)", "Mozil...
user_agents = ['Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)', 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)', 'Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337...
class DimensionSelection: """ Instances of this class to be passed to construct_mdx function """ SUBSET = 1 EXPRESSION = 2 ITERABLE = 3 def __init__(self, dimension_name, elements=None, subset=None, expression=None): self.dimension_name = dimension_name self.selection_type = se...
class Dimensionselection: """ Instances of this class to be passed to construct_mdx function """ subset = 1 expression = 2 iterable = 3 def __init__(self, dimension_name, elements=None, subset=None, expression=None): self.dimension_name = dimension_name self.selection_type = se...
print("Here is combine_strings test:") s1 = input("Please enter a string:") s2 = input("Please enter another string:") print(s1, s2)
print('Here is combine_strings test:') s1 = input('Please enter a string:') s2 = input('Please enter another string:') print(s1, s2)
def read_input(fname): lines = open(fname).readlines() algorithm = lines[0].strip() input_image = [line.strip() for line in lines[2:]] return algorithm, input_image def make_first_grid(input_image): grid = {} imin = 0 imax = len(input_image) jmin = 0 jmax = len(input_image[0]) ...
def read_input(fname): lines = open(fname).readlines() algorithm = lines[0].strip() input_image = [line.strip() for line in lines[2:]] return (algorithm, input_image) def make_first_grid(input_image): grid = {} imin = 0 imax = len(input_image) jmin = 0 jmax = len(input_image[0]) ...
arr = [3,5,6,7,1,4,2] def bubbleSort(arr): count = 0 for j in range(len(arr)-1): #print("\n\n", "-"*50, "Iteration", j) for i in range(len(arr)-1-j): count += 1 # print("\n","*"*80, "\nindex ", i, "value", arr[i]) #print("\n","*"*80, "\ncomparing", arr[i], ar...
arr = [3, 5, 6, 7, 1, 4, 2] def bubble_sort(arr): count = 0 for j in range(len(arr) - 1): for i in range(len(arr) - 1 - j): count += 1 if arr[i] > arr[i + 1]: (arr[i], arr[i + 1]) = (arr[i + 1], arr[i]) print('# of evaluations', count) return arr print(bu...
#!/usr/bin/env python NAME = 'AdNovum nevisProxy' def is_waf(self): # credit goes to an anonymous reporter return self.matchcookie('^Navajo.*?$')
name = 'AdNovum nevisProxy' def is_waf(self): return self.matchcookie('^Navajo.*?$')
# # PySNMP MIB module ALCATEL-IND1-DHCPV6-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALCATEL-IND1-DHCPV6-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:17:17 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 ...
(softent_ind1_ipv6,) = mibBuilder.importSymbols('ALCATEL-IND1-BASE', 'softentIND1Ipv6') (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, constr...
# # PHASE: write manifest # # DOCUMENT THIS # load( "@io_bazel_rules_scala//scala/private:common.bzl", "write_manifest", ) def phase_write_manifest(ctx, p): write_manifest(ctx)
load('@io_bazel_rules_scala//scala/private:common.bzl', 'write_manifest') def phase_write_manifest(ctx, p): write_manifest(ctx)
#!/usr/bin/env python ''' Seed_match.py: Check seed matching between miRNA and TargetRNA <Rules> WC => Watson-Crick match GU => G:U Wobble ------------------------------- seed_length = 8 ------------------------------- 8mer: p1-p8 WC match 8mer-1A: p1=A, p2-p8 WC match 7mer-m8: p2-p8 WC match 7mer-m1: p1...
""" Seed_match.py: Check seed matching between miRNA and TargetRNA <Rules> WC => Watson-Crick match GU => G:U Wobble ------------------------------- seed_length = 8 ------------------------------- 8mer: p1-p8 WC match 8mer-1A: p1=A, p2-p8 WC match 7mer-m8: p2-p8 WC match 7mer-m1: p1-p7 WC match 7mer-1A: p1=A, p2-p7 WC...
# python3 def prefix_function(string): '''prefixs[i] is the length of the longest border of the prefix string[0:i]''' len_str = len(string) prefixs = [None for _ in range(len_str)] prefixs[0] = 0 border = 0 for index in range(1, len_str): # decrease border size while borde...
def prefix_function(string): """prefixs[i] is the length of the longest border of the prefix string[0:i]""" len_str = len(string) prefixs = [None for _ in range(len_str)] prefixs[0] = 0 border = 0 for index in range(1, len_str): while border > 0 and string[index] != string[border]: ...
'''8.5 Open the file mbox-short.txt and read it line by line. When you find a line that starts with 'From ' like the following line: From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 You will parse the From line using split() and print out the second word in the line (i.e. the entire address of the person wh...
"""8.5 Open the file mbox-short.txt and read it line by line. When you find a line that starts with 'From ' like the following line: From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 You will parse the From line using split() and print out the second word in the line (i.e. the entire address of the person who se...
# -*- coding: utf-8 -*- """ Created on Fri Aug 27 12:37:17 2021 @author: Easin """ in1 = input() in1 = int(in1) for elements in range(in1): in2 = input() in2 = int(in2) a = input().split() list1 = [] for elem in range(len(a)): list1.append(int(a[elem])) list1.sort...
""" Created on Fri Aug 27 12:37:17 2021 @author: Easin """ in1 = input() in1 = int(in1) for elements in range(in1): in2 = input() in2 = int(in2) a = input().split() list1 = [] for elem in range(len(a)): list1.append(int(a[elem])) list1.sort() flag = True for val in range(len(lis...
# -*- coding: utf-8 -*- pytest_plugins = [ "fixtures.fixtures_app", "fixtures.fixtures_db", "fixtures.fixtures_auth", ]
pytest_plugins = ['fixtures.fixtures_app', 'fixtures.fixtures_db', 'fixtures.fixtures_auth']
_base_ = 'retinanet_pvtv2-b0_fpn_1x_coco.py' model = dict( backbone=dict( embed_dims=64, num_layers=[3, 6, 40, 3], mlp_ratios=(4, 4, 4, 4), init_cfg=dict(checkpoint='https://github.com/whai362/PVT/' 'releases/download/v2/pvt_v2_b5.pth')), neck=dict(in_channe...
_base_ = 'retinanet_pvtv2-b0_fpn_1x_coco.py' model = dict(backbone=dict(embed_dims=64, num_layers=[3, 6, 40, 3], mlp_ratios=(4, 4, 4, 4), init_cfg=dict(checkpoint='https://github.com/whai362/PVT/releases/download/v2/pvt_v2_b5.pth')), neck=dict(in_channels=[64, 128, 320, 512])) optimizer = dict(_delete_=True, type='Adam...
#!/usr/bin/env python """ https://leetcode.com/problems/roman-to-integer/description/ Created on 2018-11-07 @author: 'Jiezhi.G@gmail.com' Reference: """ romanDict = dict([('I', 1), ('V', 5), ('X', 10), ('L', 50), ('C', 100), ('D', 500), ('M', 1000)]) class Solution: def romanToInt(self, s): """ ...
""" https://leetcode.com/problems/roman-to-integer/description/ Created on 2018-11-07 @author: 'Jiezhi.G@gmail.com' Reference: """ roman_dict = dict([('I', 1), ('V', 5), ('X', 10), ('L', 50), ('C', 100), ('D', 500), ('M', 1000)]) class Solution: def roman_to_int(self, s): """ :type s: str ...
# 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 maxPathSum(self, root: Optional[TreeNode]) -> int: def get_max_gain(node): ...
class Solution: def max_path_sum(self, root: Optional[TreeNode]) -> int: def get_max_gain(node): if node is None: return 0 gain_on_left = max(get_max_gain(node.left), 0) gain_on_right = max(get_max_gain(node.right), 0) current_max_path = node...
""" ============ readthestuff ============ Yet another Google Reader alternative built on top of Python. """
""" ============ readthestuff ============ Yet another Google Reader alternative built on top of Python. """
def main(): x = raw_input("What's your name? ") a = int(raw_input("Inform an integer: ")) b = float(raw_input("Inform a float: ")) print("Your name is %s") % (x) print("Integer number: %i") % (a) print("Float number: %.2f") % (b) main()
def main(): x = raw_input("What's your name? ") a = int(raw_input('Inform an integer: ')) b = float(raw_input('Inform a float: ')) print('Your name is %s') % x print('Integer number: %i') % a print('Float number: %.2f') % b main()
class Solution(object): def simplifyPath(self, path): """ :type path: str :rtype: str """ # import os # return os.path.abspath(path) stack = [] for p in path.split("/"): if(p == ".."): if stack: stack.pop...
class Solution(object): def simplify_path(self, path): """ :type path: str :rtype: str """ stack = [] for p in path.split('/'): if p == '..': if stack: stack.pop() elif p and p != '.': stack....
def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Time, obj[3]: Coupon, obj[4]: Coupon_validity, obj[5]: Gender, obj[6]: Age, obj[7]: Maritalstatus, obj[8]: Children, obj[9]: Education, obj[10]: Occupation, obj[11]: Income, obj[12]: Bar, obj[13]: Coffeehouse, obj[14]: Restaurant20to50, obj[15]: Direct...
def find_decision(obj): if obj[8] <= 0: return 'True' elif obj[8] > 0: if obj[9] <= 0: if obj[10] > 1: return 'False' elif obj[10] <= 1: return 'True' else: return 'True' elif obj[9] > 0: retu...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Assembly Parser Author: n-vizion / info@stackevolve.com """ # todo - change from lists to set for speed and performance class ParseAsm: def __init__(self, asm_file): self.asm_file = asm_file # return code self.r_code = "" self.start = 0 self.asm = "" se...
""" Assembly Parser Author: n-vizion / info@stackevolve.com """ class Parseasm: def __init__(self, asm_file): self.asm_file = asm_file self.r_code = '' self.start = 0 self.asm = '' self.asm_lines = [] def get_total(self): try: self.f = open(f'{sel...
class PenguinTiles: def minMoves(self, tiles): rc, cc = len(tiles), len(tiles[0]) for i, r in enumerate(tiles): for j, c in enumerate(r): if c == '.': return (rc-1 != i) + (cc-1 != j) return 0
class Penguintiles: def min_moves(self, tiles): (rc, cc) = (len(tiles), len(tiles[0])) for (i, r) in enumerate(tiles): for (j, c) in enumerate(r): if c == '.': return (rc - 1 != i) + (cc - 1 != j) return 0
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reorderList(self, head): """ :type head: ListNode :rtype: void Do not return anything, modify head in-place instead. ...
class Solution(object): def reorder_list(self, head): """ :type head: ListNode :rtype: void Do not return anything, modify head in-place instead. """ if not head or not head.next: return depth = 0 temp = head while temp: temp =...
num1=7 num2=9 #add two numbers sum=float(num1) + float(num2) #display the sum print('the sum of {0} and {1} is {2}'.format(num1, num2, sum)) print ("hello") print ("hi") print (1+2+4-8-7+9+93-8) number1=98 number2=76 #add two numbers sum=float(number1) + (number2) #display the sum print ('sum of {0} and...
num1 = 7 num2 = 9 sum = float(num1) + float(num2) print('the sum of {0} and {1} is {2}'.format(num1, num2, sum)) print('hello') print('hi') print(1 + 2 + 4 - 8 - 7 + 9 + 93 - 8) number1 = 98 number2 = 76 sum = float(number1) + number2 print('sum of {0} and {1} is {2}'.format(number1, number2, sum)) print('uu') print('h...
''' Given arc, kui index, data dictionary, slots Runs PRIP algorithm and returns slots. ''' def PRIP(data_dict, kui_idx, arc, slot_sizes): print(slot_sizes) s_type = 0 item_placed = 0 slot_type_arr = [] CAS = [] num_slots = len(slot_sizes) total_slots = 0 slots = [] for i in range(...
""" Given arc, kui index, data dictionary, slots Runs PRIP algorithm and returns slots. """ def prip(data_dict, kui_idx, arc, slot_sizes): print(slot_sizes) s_type = 0 item_placed = 0 slot_type_arr = [] cas = [] num_slots = len(slot_sizes) total_slots = 0 slots = [] for i in range(0...
class VectorHashTestEnum: DATA_IN = 'Msg' DATA_LEN = 'Len' EXP = 'Exp'
class Vectorhashtestenum: data_in = 'Msg' data_len = 'Len' exp = 'Exp'
s = input("digite um valor em segundos: ") h = int(int(s)/3600) m = int((int(s)%3600)/60) s = int((int(s)%3600)%60) print (str(h)+":"+str(m)+":"+str(s))
s = input('digite um valor em segundos: ') h = int(int(s) / 3600) m = int(int(s) % 3600 / 60) s = int(int(s) % 3600 % 60) print(str(h) + ':' + str(m) + ':' + str(s))
def count_inversions(ints): """ count inversions with mergesort """ # base case n = len(ints) if n == 1: return 0, ints # count left and right half recursively nums_l, sort_l = count_inversions(ints[:n//2]) nums_r, sort_r = count_inversions(ints[n//2:]) # mersort and coun...
def count_inversions(ints): """ count inversions with mergesort """ n = len(ints) if n == 1: return (0, ints) (nums_l, sort_l) = count_inversions(ints[:n // 2]) (nums_r, sort_r) = count_inversions(ints[n // 2:]) nums_s = 0 sort = [] while sort_l and sort_r: if sor...
class Pin: def __init__(self, node, pin_type, channel, bit): self.node = node self.pin_type = pin_type self.channel = channel self.bit = bit async def read(self): if self.pin_type == 'input': channel_state = await self.node.inputs[self.channel].read() ...
class Pin: def __init__(self, node, pin_type, channel, bit): self.node = node self.pin_type = pin_type self.channel = channel self.bit = bit async def read(self): if self.pin_type == 'input': channel_state = await self.node.inputs[self.channel].read() ...
disk = {} disk['SR4'] = {'name': 'SR4', 'label': 'SR 4', 'distance': 134.8, 'incl': 22.0, 'PA': 18.0, 'dx': -0.060, 'dy': -0.509, 'rgap': [0.079], 'wg...
disk = {} disk['SR4'] = {'name': 'SR4', 'label': 'SR 4', 'distance': 134.8, 'incl': 22.0, 'PA': 18.0, 'dx': -0.06, 'dy': -0.509, 'rgap': [0.079], 'wgap': [0.01], 'dgap': [30], 'rout': 0.25, 'maxTb': 50, 'hyp-alpha': 1.3, 'hyp-wsmth': 0.1, 'hyp-Ncoll': 300, 'cmask': 'circle[[16h25m56.16s, -24.20.48.71], 0.7arcsec]', 'cs...
def solve(n, arr): ret: list[int] = [0] * 100 for i in range(0, n): ret[arr[i]] += 1 return ret if __name__ == "__main__": n = int(input().strip()) arr = list(map(int, input().rstrip().split())) result = solve(n, arr) print(" ".join(map(str, result)))
def solve(n, arr): ret: list[int] = [0] * 100 for i in range(0, n): ret[arr[i]] += 1 return ret if __name__ == '__main__': n = int(input().strip()) arr = list(map(int, input().rstrip().split())) result = solve(n, arr) print(' '.join(map(str, result)))
# 6. Write a simple function (area_circle) that returns the area # of a circle of a given radius. def area_circle(r): ''' Calculate the area of a circle given the radius r = radius (in some unstated unit of measurement) ''' return 3.1415926536 * (r ** 2) def main(): print('Test case') p...
def area_circle(r): """ Calculate the area of a circle given the radius r = radius (in some unstated unit of measurement) """ return 3.1415926536 * r ** 2 def main(): print('Test case') print('area_circle(5) is', area_circle(5)) if __name__ == '__main__': main()
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def distanceK(self, root, target, K): """ :type root: TreeNode :type target: TreeNode :type K: int ...
class Solution: def distance_k(self, root, target, K): """ :type root: TreeNode :type target: TreeNode :type K: int :rtype: List[int] """ tree = collections.defaultdict(list) def dfs(node): if node is not None: for child i...
# Classes and methods whitelist core = {'': ['absdiff', 'add', 'addWeighted', 'bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor', 'cartToPolar',\ 'compare', 'convertScaleAbs', 'copyMakeBorder', 'countNonZero', 'determinant', 'dft', 'divide', 'eigen', \ 'exp', 'flip', 'getOptimalDFTSize'...
core = {'': ['absdiff', 'add', 'addWeighted', 'bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor', 'cartToPolar', 'compare', 'convertScaleAbs', 'copyMakeBorder', 'countNonZero', 'determinant', 'dft', 'divide', 'eigen', 'exp', 'flip', 'getOptimalDFTSize', 'gemm', 'hconcat', 'inRange', 'invert', 'kmeans', 'log', 'm...
# Time: O(m * n) # Space: O(m + n) class Solution(object): # @return an integer def uniquePaths(self, m, n): if m < n: return self.uniquePaths(n, m) ways = [1] * n for i in xrange(1, m): for j in xrange(1, n): ways[j] += ways[j - 1] ret...
class Solution(object): def unique_paths(self, m, n): if m < n: return self.uniquePaths(n, m) ways = [1] * n for i in xrange(1, m): for j in xrange(1, n): ways[j] += ways[j - 1] return ways[n - 1]
# This program uses a loop to display a # table of numbers and their squares. print('This program displays a list of numbers') print('(starting at 1) and their squares.') end = int(input('How high should I go? ')) print() print('Number\tSquare') print('--------------') for number in range(1, end + 1): square = n...
print('This program displays a list of numbers') print('(starting at 1) and their squares.') end = int(input('How high should I go? ')) print() print('Number\tSquare') print('--------------') for number in range(1, end + 1): square = number ** 2 print(number, '\t', square)
#coding: utf-8 ''' mbinary ####################################################################### # File : fastPow.py # Author: mbinary # Mail: zhuheqin1@gmail.com # Blog: https://mbinary.xyz # Github: https://github.com/mbinary # Created Time: 2018-12-17 21:39 # Description: fast power ##############################...
""" mbinary ####################################################################### # File : fastPow.py # Author: mbinary # Mail: zhuheqin1@gmail.com # Blog: https://mbinary.xyz # Github: https://github.com/mbinary # Created Time: 2018-12-17 21:39 # Description: fast power #############################################...
class Iterator(object): """Base class of all dataset iterators. Iterator iterates over the dataset, yielding a minibatch at each iteration. Minibatch is a list of examples. Each implementation should implement an iterator protocol (e.g., the :meth:`__next__` method). Note that, even if the iterat...
class Iterator(object): """Base class of all dataset iterators. Iterator iterates over the dataset, yielding a minibatch at each iteration. Minibatch is a list of examples. Each implementation should implement an iterator protocol (e.g., the :meth:`__next__` method). Note that, even if the iterato...
def domain_name(url): for i in ['www.', '//']: if i in url: return url.split(i)[1][:url.split(i)[1].find('.')] return url[:url.find('.')]
def domain_name(url): for i in ['www.', '//']: if i in url: return url.split(i)[1][:url.split(i)[1].find('.')] return url[:url.find('.')]
# -*- coding: utf-8 -*- __author__ = 'R. M. Parrondo' __email__ = 'aroy@alum.mit.edu' __version__ = '0.1.0'
__author__ = 'R. M. Parrondo' __email__ = 'aroy@alum.mit.edu' __version__ = '0.1.0'
def init_app(app): app.config["SECRET_KEY"] = "passW0rd01" app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///foodelivery.db" app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False app.config["FLASK_ADMIN_SWATCH"] = "cerulean" app.config["DEBUG_TB_INTERCEPT_REDIRECTS"] = False if app.debug: ...
def init_app(app): app.config['SECRET_KEY'] = 'passW0rd01' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///foodelivery.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['FLASK_ADMIN_SWATCH'] = 'cerulean' app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False if app.debug: ...
class Solution: def integerBreak(self, n): """ :type n: int :rtype: int """ if n == 2: return 1 elif n == 3: return 2 elif n%3 == 0: return pow(3,n//3) elif n%3 == 1: return pow(3,n//3 -1)*4 elif ...
class Solution: def integer_break(self, n): """ :type n: int :rtype: int """ if n == 2: return 1 elif n == 3: return 2 elif n % 3 == 0: return pow(3, n // 3) elif n % 3 == 1: return pow(3, n // 3 - 1) * ...
# -*- coding: utf-8 -*- """ Created on Mon Jan 28 13:33:54 2019 Programa que permite contar las vocales dentro de una palabra @author: Luis Cobian """ palabra = input("Una palabra: ") palabra = palabra.lower(); a = palabra.count("a"); e = palabra.count("e"); i = palabra.count("i"); o = palabra.count("o"); u = palabr...
""" Created on Mon Jan 28 13:33:54 2019 Programa que permite contar las vocales dentro de una palabra @author: Luis Cobian """ palabra = input('Una palabra: ') palabra = palabra.lower() a = palabra.count('a') e = palabra.count('e') i = palabra.count('i') o = palabra.count('o') u = palabra.count('u') print('A: ', a) pr...
N, K = map(int, input().split()) tmp, answer = N, 1 while True: tmp = tmp // K if tmp == 0: break answer += 1 print(answer)
(n, k) = map(int, input().split()) (tmp, answer) = (N, 1) while True: tmp = tmp // K if tmp == 0: break answer += 1 print(answer)
# Create a tuple named zoo that contains your favorite animals. zoo = ("Armadillo", "Turtle", "Hedgehog", "Tree Frog") # Find one of your animals using the .index(value) method on the tuple. print(zoo.index("Hedgehog")) # Determine if an animal is in your tuple by using for value in tuple. if "Koala" in zoo: pri...
zoo = ('Armadillo', 'Turtle', 'Hedgehog', 'Tree Frog') print(zoo.index('Hedgehog')) if 'Koala' in zoo: print(zoo.index('Koala')) else: print('zoo does not contain this animal') (animal1, animal2, animal3, animal4) = zoo print(animal1) zoo_list = list(zoo) print(zoo_list) zoo_list.extend(['Koala', 'Bushbaby', 'G...
""" @author: Deniz Altinbuken, Emin Gun Sirer @note: Example jobmanager @copyright: See LICENSE """ class JobManager(): def __init__(self): self.jobs = [] def schedule(self, job): self.jobs.append(job) def deschedule(self, job): self.jobs.remove(job) def update(self, job, key,...
""" @author: Deniz Altinbuken, Emin Gun Sirer @note: Example jobmanager @copyright: See LICENSE """ class Jobmanager: def __init__(self): self.jobs = [] def schedule(self, job): self.jobs.append(job) def deschedule(self, job): self.jobs.remove(job) def update(self, job, key,...
# (C) Datadog, Inc. 2019-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) NODE_METRICS_MAP = { 'go_gc_duration_seconds': 'go.gc.duration.seconds', 'go_goroutines': 'go.goroutines', 'go_info': 'go.info', 'go_memstats_alloc_bytes': 'go.memstats.alloc.bytes', 'g...
node_metrics_map = {'go_gc_duration_seconds': 'go.gc.duration.seconds', 'go_goroutines': 'go.goroutines', 'go_info': 'go.info', 'go_memstats_alloc_bytes': 'go.memstats.alloc.bytes', 'go_memstats_alloc_bytes_total': 'go.memstats.alloc.bytes.total', 'go_memstats_buck_hash_sys_bytes': 'go.memstats.buck.hash.sys.bytes', 'g...
SECRET_KEY = "12345" DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}} INSTALLED_APPS = [ "django.contrib.auth", "django.contrib.contenttypes", "wagtail.users", "wagtail.admin", "wagtail.images", "wagtail.core", "tests.my_app", ] AUTH_PASSWORD_VALIDATOR...
secret_key = '12345' databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}} installed_apps = ['django.contrib.auth', 'django.contrib.contenttypes', 'wagtail.users', 'wagtail.admin', 'wagtail.images', 'wagtail.core', 'tests.my_app'] auth_password_validators = [{'NAME': 'django.contrib.auth...
""" This unit test checks that we get a RepyArgumentError when providing bad arguments to listenforconnection. """ #pragma repy def tryit(ip,port): try: listenforconnection(ip,port) log("Bad combination worked! IP:"+str(ip)+" Port: "+str(port),'\n') except: pass # Try some bad combos tryit(None, None)...
""" This unit test checks that we get a RepyArgumentError when providing bad arguments to listenforconnection. """ def tryit(ip, port): try: listenforconnection(ip, port) log('Bad combination worked! IP:' + str(ip) + ' Port: ' + str(port), '\n') except: pass tryit(None, None) tryit('abc...
f = open("sample.txt", mode="r", encoding="utf-8") f2 = open("sample3.txt", mode="w", encoding="utf-8") f2.write(f.read()) f2 = open("sample3.txt", mode="r", encoding="utf-8") print("Reading contents present inside sample3.txt:") print(f2.read())
f = open('sample.txt', mode='r', encoding='utf-8') f2 = open('sample3.txt', mode='w', encoding='utf-8') f2.write(f.read()) f2 = open('sample3.txt', mode='r', encoding='utf-8') print('Reading contents present inside sample3.txt:') print(f2.read())
"""This class implements a very thin layer to store metadata in a string.""" class SequenceString(str): def __new__(self, value, metadata=None): return str.__new__(self, value) def __init__(self, value, metadata=None): self.metadata = metadata or {} @staticmethod def from_record(reco...
"""This class implements a very thin layer to store metadata in a string.""" class Sequencestring(str): def __new__(self, value, metadata=None): return str.__new__(self, value) def __init__(self, value, metadata=None): self.metadata = metadata or {} @staticmethod def from_record(reco...
""" Contains methods for generating new input_0.py files This will help us do more "generations" of reactions """ # I couldn't find a way to access these from the reaction model itself # TODO: Access these from the models, instead of providing it explicitly temperature = 800 pressure = 1.0 def clean_prev(current_fil...
""" Contains methods for generating new input_0.py files This will help us do more "generations" of reactions """ temperature = 800 pressure = 1.0 def clean_prev(current_file): """ Intended to "clean" (remove) simpleReactor() from an input_0.py :param current_file: the file that was just used for a run ...
############################################################################### # Copyright Maciej Patro (maciej.patro@gmail.com) # MIT License ############################################################################### def input_data(parser): parser.add_argument('input', type=str, ...
def input_data(parser): parser.add_argument('input', type=str, nargs='*', help='CMake file to be formatted') def dump_config(parser): parser.add_argument('--dump-config', action='store_true', help='Dump to stdout current settings. Script tries to read settings from `.cmake-tidy.json` or provides default settin...
gray = {} gray[100] = "#f8f9fa" gray[200] = "#ecf0f1" gray[300] = "#dee2e6" gray[400] = "#ced4da" gray[500] = "#b4bcc2" gray[600] = "#95a5a6" gray[700] = "#7b8a8b" gray[800] = "#343a40" gray[900] = "#212529" blue = "#3d91f2" indigo = "#6610f2" purple = "#6f42c1" pink = "#e83e8c" red = "#e74c3c" orange = "#fd7e14" yell...
gray = {} gray[100] = '#f8f9fa' gray[200] = '#ecf0f1' gray[300] = '#dee2e6' gray[400] = '#ced4da' gray[500] = '#b4bcc2' gray[600] = '#95a5a6' gray[700] = '#7b8a8b' gray[800] = '#343a40' gray[900] = '#212529' blue = '#3d91f2' indigo = '#6610f2' purple = '#6f42c1' pink = '#e83e8c' red = '#e74c3c' orange = '#fd7e14' yello...
''' Provides helpers for working with bits and bytes. ''' # Provides a quick list of JDEC JEP106 designer IDs. JDEC_JEP106 = { 571: 'ARM (0x23B)' } def to_bit_list(entries, width=8, bitflip=False): ''' Convert interger list to a list of bits. ''' result = [] # TODO: Do this without string formatting...
""" Provides helpers for working with bits and bytes. """ jdec_jep106 = {571: 'ARM (0x23B)'} def to_bit_list(entries, width=8, bitflip=False): """ Convert interger list to a list of bits. """ result = [] fmt = '{{0:0{}b}}'.format(width) for entry in entries: for bit in list(fmt.format(entry)): ...
# ========================================================================= # # Copyright COS 397 # # 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/license...
""" This module sorts lists of integers... """ def bubble(arr): """ :param arr: an array to be sorted :returns: sorted array """ n = len(arr) for i in range(n - 1): for j in range(0, n - i - 1): if arr[j] > arr[j + 1]: (arr[j], arr[j + 1]) = (arr[j + 1], arr[...
""" This is a simple config file holding an array of packages for each subtype that exists """ # packages required for everything GENERAL_PACKAGES=["git"] # packages required to build the repository REPO_PACKAGES=["python-sphinx", "rust", "pacman-contrib", "i3lock-color-git", "dkms", "xorg-xset", "unzip", "asciidoc",...
""" This is a simple config file holding an array of packages for each subtype that exists """ general_packages = ['git'] repo_packages = ['python-sphinx', 'rust', 'pacman-contrib', 'i3lock-color-git', 'dkms', 'xorg-xset', 'unzip', 'asciidoc', 'docbook-xsl', 'pythonqt'] kernel_packages = ['asp', 'autoconf', 'automake',...
class Container: def __init__(self, container_id): self.container_id = container_id
class Container: def __init__(self, container_id): self.container_id = container_id
# Defaults peaks_QC, cut_spikes_QC, cut_spikes_holding_QC, cut_spikes_baselined_QC, parameters_QC = spikesQC( file_name, peaks, peaks_properties, cut_spikes, cut_spikes_holding, cut_spikes_baselined, filter_by = ['p', 'wh', 'pw', 'ph', 'pb', 'lb', 'rb'], QC_p_min = float('-inf'), QC_p_max = float('inf')...
(peaks_qc, cut_spikes_qc, cut_spikes_holding_qc, cut_spikes_baselined_qc, parameters_qc) = spikes_qc(file_name, peaks, peaks_properties, cut_spikes, cut_spikes_holding, cut_spikes_baselined, filter_by=['p', 'wh', 'pw', 'ph', 'pb', 'lb', 'rb'], QC_p_min=float('-inf'), QC_p_max=float('inf'), QC_wh_min=float('-inf'), QC_w...
i, j = ( 3, 9 ) print(i, j) for i, j in[(1, 2), (3, 4), (5, 6)]: print(i, j)
(i, j) = (3, 9) print(i, j) for (i, j) in [(1, 2), (3, 4), (5, 6)]: print(i, j)
"""Serveradmin - adminapi Copyright (c) 2021 InnoGames GmbH """ VERSION = (4, 3, 0)
"""Serveradmin - adminapi Copyright (c) 2021 InnoGames GmbH """ version = (4, 3, 0)
persn1 = "Taufiq" persn2 = "Naufal" persons = ["Taufiq", "Naufal", "Syamsul", "Yessy", "Ervan"] persons[0] # accessing data persons[0] = "Dedy" # changing list data # insert data berdasarkan index, lalu memberikan isi data untuk index tersebut persons.insert(2,"Tohari") print(persons) # menambahkan data pada list...
persn1 = 'Taufiq' persn2 = 'Naufal' persons = ['Taufiq', 'Naufal', 'Syamsul', 'Yessy', 'Ervan'] persons[0] persons[0] = 'Dedy' persons.insert(2, 'Tohari') print(persons) persons.append('Akbar') persons.remove('Yessy') persons.pop(0) numbers = list(range(20)) print(numbers) print(len(numbers)) print(numbers[0:10]) print...
# Copyright 2018 Databricks, Inc. VERSION = '1.7.1.dev0'
version = '1.7.1.dev0'
principle = 5000 interest_rate = 0.035 # interest = principle * interest_rate # principle = principle + interest #this is equivalent to below for i in range(5): principle += principle * interest_rate print(f'Principle: ${principle:0.2f}') # principle *= 1 + interest_rate #equivalent but less readable x = 8 # str...
principle = 5000 interest_rate = 0.035 for i in range(5): principle += principle * interest_rate print(f'Principle: ${principle:0.2f}') x = 8 string = f'-{x}-' cost = 0.75 print(f'it costs ${cost:0.2f}')
for _ in range(3): record = list(map(int, input().split())) opening = 3600 * record[0] + 60 * record[1] + record[2] closing = 3600 * record[3] + 60 * record[4] + record[5] office_hour = closing - opening print(office_hour // 3600, office_hour % 3600 // 60, office_hour % 60)
for _ in range(3): record = list(map(int, input().split())) opening = 3600 * record[0] + 60 * record[1] + record[2] closing = 3600 * record[3] + 60 * record[4] + record[5] office_hour = closing - opening print(office_hour // 3600, office_hour % 3600 // 60, office_hour % 60)
class ApiError(Exception): """ Follows the RFC 7807 standard https://tools.ietf.org/html/rfc7807 Example Usage: { "type": "https://example.com/probs/out-of-credit", "title": "You do not have enough credit.", "detail": "Your current balance is 30, but that costs 50.", ...
class Apierror(Exception): """ Follows the RFC 7807 standard https://tools.ietf.org/html/rfc7807 Example Usage: { "type": "https://example.com/probs/out-of-credit", "title": "You do not have enough credit.", "detail": "Your current balance is 30, but that costs 50.", ...
""" Copyright (c) 2015 Michael Bright and Bamboo HR LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed...
""" Copyright (c) 2015 Michael Bright and Bamboo HR LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed...
def _check_test_type(tt: str): if tt == "two-tailed" or tt == "left-tailed" or tt == "right-tailed": pass else: raise AttributeError( "Test type should be whether 'two-tailed' or 'left-tailed' or 'right-tailed'" ) def _check_others(*args): for cl in args: if cl ...
def _check_test_type(tt: str): if tt == 'two-tailed' or tt == 'left-tailed' or tt == 'right-tailed': pass else: raise attribute_error("Test type should be whether 'two-tailed' or 'left-tailed' or 'right-tailed'") def _check_others(*args): for cl in args: if cl < 1.0 and cl > 0.0: ...
# There are so many different approaches and so many different ways to implement each. I find it hard to decide, so here are several: -) # In all of them, I check one of these tree characterizations: # Has n - 1 edges and is acyclic. # Has n - 1 edges and is connected. # Solution 1 ... Union - Find # The test cases ...
def valid_tree(self, n, edges): parent = range(n) def find(x): return x if parent[x] == x else find(parent[x]) def union(xy): (x, y) = map(find, xy) parent[x] = y return x != y return len(edges) == n - 1 and all(map(union, edges)) def valid_tree(self, n, edges): pa...
def solver_function(L1: list, L2: list, C1: list, C2: list, C_max: int) -> QuantumCircuit: # the number of qubits representing answers index_qubits = len(L1) # the maximum possible total cost max_c = sum([max(l0, l1) for l0, l1 in zip(C1, C2)]) min_c = sum([min(l0, l1) for l0, ...
def solver_function(L1: list, L2: list, C1: list, C2: list, C_max: int) -> QuantumCircuit: index_qubits = len(L1) max_c = sum([max(l0, l1) for (l0, l1) in zip(C1, C2)]) min_c = sum([min(l0, l1) for (l0, l1) in zip(C1, C2)]) max_c -= min_c data_qubits = math.ceil(math.log(max_c, 2)) + 1 if not max_c ...
# tables.py class MortalityTable: """mortalitytable is a matrix, by age and duration.""" def __init__(self, csv_filename, name, select_period, pc_of_base=1): self.filename = csv_filename self.name = name self.select_period = select_period self.pc_of_base = pc_of_base...
class Mortalitytable: """mortalitytable is a matrix, by age and duration.""" def __init__(self, csv_filename, name, select_period, pc_of_base=1): self.filename = csv_filename self.name = name self.select_period = select_period self.pc_of_base = pc_of_base self.load_csv(s...
try: # Write normal code here. This block must include # code that falls into two groups: # 1. Code that may cause an exception to be raised # 2. Code that depends on the results from the code # in the first group pass except ZeroDivisionError as zero_div_err: # Code that the computer execut...
try: pass except ZeroDivisionError as zero_div_err: pass except ValueError as val_err: pass except (TypeError, KeyError, IndexError) as error: pass except Exception as excep: pass except: pass else: pass finally: pass "\nThe Python programming language requires us to order except blocks ...
num , need = map(int, input().split()) arr = list(map(int, input().split())) #sys.stdin.readline().strip() i = 0 j = 0 check = 0; sum = 0 while i <= len(arr): if(i != len(arr)): if sum < need: sum += arr[i] i += 1 elif sum > need: sum -= arr[j] ...
(num, need) = map(int, input().split()) arr = list(map(int, input().split())) i = 0 j = 0 check = 0 sum = 0 while i <= len(arr): if i != len(arr): if sum < need: sum += arr[i] i += 1 elif sum > need: sum -= arr[j] j += 1 elif sum > need: su...
""" Pieces """ EMPTY = (0, 0, 0) GARBAGE = (150, 150, 150) Z_PIECE = (0, 20, 255) S_PIECE = (10, 255, 100) O_PIECE = (20, 255, 255) T_PIECE = (255, 0, 127) J_PIECE = (255, 100, 0) L_PIECE = (30, 160, 220) I_PIECE = (220, 220, 0) UNKNOWN = (255, 255, 255)
""" Pieces """ empty = (0, 0, 0) garbage = (150, 150, 150) z_piece = (0, 20, 255) s_piece = (10, 255, 100) o_piece = (20, 255, 255) t_piece = (255, 0, 127) j_piece = (255, 100, 0) l_piece = (30, 160, 220) i_piece = (220, 220, 0) unknown = (255, 255, 255)
n = int(input()) for i in range(n): vet = list(map(float, input().split())) pa = int(vet[0]) pb = int(vet[1]) cresA = vet[2]/100 cresB = vet[3]/100 tempo = 0 while pa < pb: pa += int(pa * cresA) pb += int(pb * cresB) tempo += 1 if tempo > 100 or pa > pb: ...
n = int(input()) for i in range(n): vet = list(map(float, input().split())) pa = int(vet[0]) pb = int(vet[1]) cres_a = vet[2] / 100 cres_b = vet[3] / 100 tempo = 0 while pa < pb: pa += int(pa * cresA) pb += int(pb * cresB) tempo += 1 if tempo > 100 or pa > pb:...
class Repository: def __init__(self, user, name): self.user = user self.name = name @classmethod def fromList(cls, repositories): for user, name in repositories: yield cls(user, name) def __str__(self): return "{}/{}".format(self.user, self.name)
class Repository: def __init__(self, user, name): self.user = user self.name = name @classmethod def from_list(cls, repositories): for (user, name) in repositories: yield cls(user, name) def __str__(self): return '{}/{}'.format(self.user, self.name)