content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
""" borg.algorithms =============== This package is intended for hash and checksum functions. """
""" borg.algorithms =============== This package is intended for hash and checksum functions. """
""" Working with Binary Search Trees (BSTs). The height of a binary search tree is the number of edges between the tree's root and its furthest leaf. You are given a pointer, root, pointing to the root of a binary search tree. Complete the getHeight function provided in your editor so that it returns the height of...
""" Working with Binary Search Trees (BSTs). The height of a binary search tree is the number of edges between the tree's root and its furthest leaf. You are given a pointer, root, pointing to the root of a binary search tree. Complete the getHeight function provided in your editor so that it returns the height of...
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. class ContentType: O365_CONNECTOR_CARD = "application/vnd.microsoft.teams.card.o365connector" FILE_CONSENT_CARD = "application/vnd.microsoft.teams.card.file.consent" FILE_DOWNLOAD_INFO = "application/vnd.microsof...
class Contenttype: o365_connector_card = 'application/vnd.microsoft.teams.card.o365connector' file_consent_card = 'application/vnd.microsoft.teams.card.file.consent' file_download_info = 'application/vnd.microsoft.teams.file.download.info' file_info_card = 'application/vnd.microsoft.teams.card.file.info...
class Log: lines = [] def __init__(self): self.lines = [] def add(self, line): self.lines.append(line) def flush(self): for line in self.lines: print(line) self.lines = [] battle_log = Log() general_log = Log()
class Log: lines = [] def __init__(self): self.lines = [] def add(self, line): self.lines.append(line) def flush(self): for line in self.lines: print(line) self.lines = [] battle_log = log() general_log = log()
num1 = 111 num2 = 222 num3 = 333333 num3 = 333 num4 = 4444
num1 = 111 num2 = 222 num3 = 333333 num3 = 333 num4 = 4444
"""This module contains a collection of functions related to flood data. """ #ml2015 def stations_level_over_threshold(stations,tol): """For Task 2B - returns a list of tuples The tuples contain a station and then a relative water level the relative water level must be greater than tol returned list s...
"""This module contains a collection of functions related to flood data. """ def stations_level_over_threshold(stations, tol): """For Task 2B - returns a list of tuples The tuples contain a station and then a relative water level the relative water level must be greater than tol returned list should b...
class MaterialPropertyMap: def __init__(self): self._lowCutoffs = [] self._highCutoffs = [] self._properties = [] def error_check(self, cutoff, conductivity): if not isinstance(cutoff, tuple) or len(cutoff) != 2: raise Exception("Cutoff has to be a tuple(int,int) spe...
class Materialpropertymap: def __init__(self): self._lowCutoffs = [] self._highCutoffs = [] self._properties = [] def error_check(self, cutoff, conductivity): if not isinstance(cutoff, tuple) or len(cutoff) != 2: raise exception('Cutoff has to be a tuple(int,int) sp...
class EncodingApiCommunicator(object): def __init__(self, inner): self.inner = inner def call(self, path, command, arguments=None, queries=None, additional_queries=()): path = path.encode() command = command.encode() arguments = self.transform_dictionary(argum...
class Encodingapicommunicator(object): def __init__(self, inner): self.inner = inner def call(self, path, command, arguments=None, queries=None, additional_queries=()): path = path.encode() command = command.encode() arguments = self.transform_dictionary(arguments or {}) ...
class Person: def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name self.age = 0 def full_name(self): return self.first_name + " " + self.last_name def record_info(self): return self.last_name + ", " + self.first_name perso...
class Person: def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name self.age = 0 def full_name(self): return self.first_name + ' ' + self.last_name def record_info(self): return self.last_name + ', ' + self.first_name person = p...
class Node: def __init__(self, data) -> None: self.data = data self.nextNode = None class LinkedList: def __init__(self): self.head = None self.numOfNodes = 0 def insert_new(self, data): self.numOfNodes += 1 new_node = Node(data) if not self.head: ...
class Node: def __init__(self, data) -> None: self.data = data self.nextNode = None class Linkedlist: def __init__(self): self.head = None self.numOfNodes = 0 def insert_new(self, data): self.numOfNodes += 1 new_node = node(data) if not self.head: ...
adventures = [ {"id": 1, "name": "Test Location"}, {"id": 12, "name": "The Sewer"}, {"id": 15, "name": "The Spooky Forest"}, {"id": 16, "name": "The Haiku Dungeon"}, {"id": 17, "name": "The Hidden Temple"}, {"id": 18, "name": "Degrassi Knoll"}, {"id": 19, "name": "The Limerick Dungeon"}, ...
adventures = [{'id': 1, 'name': 'Test Location'}, {'id': 12, 'name': 'The Sewer'}, {'id': 15, 'name': 'The Spooky Forest'}, {'id': 16, 'name': 'The Haiku Dungeon'}, {'id': 17, 'name': 'The Hidden Temple'}, {'id': 18, 'name': 'Degrassi Knoll'}, {'id': 19, 'name': 'The Limerick Dungeon'}, {'id': 20, 'name': 'The "Fun" Ho...
class Solution: def amendSentence(self, s): # code here ans = "" string = "" for i in range(len(s)): if 97 <= ord(s[i]) <= 122: string += s[i] else: if string: ans += string ans += "...
class Solution: def amend_sentence(self, s): ans = '' string = '' for i in range(len(s)): if 97 <= ord(s[i]) <= 122: string += s[i] else: if string: ans += string ans += ' ' strin...
# Copyright (c) 2021 Qualcomm Technologies, Inc. # All Rights Reserved. def _tb_advance_global_step(module): if hasattr(module, 'global_step'): module.global_step += 1 return module def _tb_advance_token_counters(module, tensor, verbose=False): token_count = getattr(module, 'tb_token_count', Non...
def _tb_advance_global_step(module): if hasattr(module, 'global_step'): module.global_step += 1 return module def _tb_advance_token_counters(module, tensor, verbose=False): token_count = getattr(module, 'tb_token_count', None) if token_count is not None: t = tensor.size(1) if to...
def getMapCommon(): common = """SYMBOLSET "./etc/symbols.sym" FONTSET "./etc/fonts/fonts.list" IMAGETYPE "png" """ return common def getPng(): output = """OUTPUTFORMAT NAME "png" DRIVER "AGG/PNG" MIMETYPE "image/png" IMAGEMODE RGB EXTE...
def get_map_common(): common = 'SYMBOLSET "./etc/symbols.sym"\n FONTSET "./etc/fonts/fonts.list"\n IMAGETYPE "png"\n ' return common def get_png(): output = 'OUTPUTFORMAT\n NAME "png"\n DRIVER "AGG/PNG"\n MIMETYPE "image/png"\n IMAGEMODE RGB\n ...
# -*- coding: utf-8 -*- """SDP Tango Master Release info.""" __subsystem__ = 'TangoControl' __service_name__ = 'SDPMaster' __version_info__ = (0, 1, 0) __version__ = '.'.join(map(str, __version_info__)) __service_id__ = ':'.join(map(str, (__subsystem__, __service_name__, ...
"""SDP Tango Master Release info.""" __subsystem__ = 'TangoControl' __service_name__ = 'SDPMaster' __version_info__ = (0, 1, 0) __version__ = '.'.join(map(str, __version_info__)) __service_id__ = ':'.join(map(str, (__subsystem__, __service_name__, __version__))) __all__ = ['__subsystem__', '__service_name__', '__versio...
# -*- coding: utf-8 -*- """ Created on Fri Sep 10 15:18:19 2021 @author: qizhe """ class Solution: def climbStairs(self, n: int) -> int: if n <= 1: return n pre = 1 cur = 2 for _ in range(2,n): cur, pre = cur + pre, cur return cur if __name__ == '...
""" Created on Fri Sep 10 15:18:19 2021 @author: qizhe """ class Solution: def climb_stairs(self, n: int) -> int: if n <= 1: return n pre = 1 cur = 2 for _ in range(2, n): (cur, pre) = (cur + pre, cur) return cur if __name__ == '__main__': solu ...
class ExpressionReader: priorityComparision = ['='] andOrComparision = ['OR'] operations = [] operations.extend(priorityComparision) operations.extend(andOrComparision) def read(expression): lst = ExpressionReader.__split(expression) #lst = ExpressionReader.__parsePriorityExpre...
class Expressionreader: priority_comparision = ['='] and_or_comparision = ['OR'] operations = [] operations.extend(priorityComparision) operations.extend(andOrComparision) def read(expression): lst = ExpressionReader.__split(expression) return lst def __split(expression): ...
'''A large FizzBuzz as an output using small FizzBuzz numbers.(FizzBuzz=FizBuz for better alignment and make sure your output terminal covers the entire length of the screen to avoid automatic newlines)''' # Author: @AmanMatrix def iCheck(i): if i%15==0: i='FizBuz' elif i%3==0: i='Fizz' eli...
"""A large FizzBuzz as an output using small FizzBuzz numbers.(FizzBuzz=FizBuz for better alignment and make sure your output terminal covers the entire length of the screen to avoid automatic newlines)""" def i_check(i): if i % 15 == 0: i = 'FizBuz' elif i % 3 == 0: i = 'Fizz' elif i % 5 ...
i = 1.0 print(i) print("Hello world!") print(type(i)) a = "Hello" print(type(a)) # print(a+i) <-Error! a += "world!" print(a) print("this is string: {}, {}".format(3, "ala bala")) print("pi = %f" % 3.14)
i = 1.0 print(i) print('Hello world!') print(type(i)) a = 'Hello' print(type(a)) a += 'world!' print(a) print('this is string: {}, {}'.format(3, 'ala bala')) print('pi = %f' % 3.14)
MACHINE_A = 'MachineA' MACHINE_B = 'MachineB' INIT = 'Init' E_STOP = 'stop' E_INCREASE = 'increase' E_DECREASE = 'decrease'
machine_a = 'MachineA' machine_b = 'MachineB' init = 'Init' e_stop = 'stop' e_increase = 'increase' e_decrease = 'decrease'
#============================================================================= ## Automatic Repository Version Generation Utility ## Author: Zhenyu Wu ## Revision 1: Apr 28. 2016 - Initial Implementation #============================================================================= __all__ = [ 'VersionLint' ]
__all__ = ['VersionLint']
def fun(f): #string # Some functions need zero or more # arguements then we have to use # *args & **kwargs def wrapper(*args, **kwargs): print("Start") #print(string) # to return the values that are passed values = f(*args, **kwargs) print("End") return va...
def fun(f): def wrapper(*args, **kwargs): print('Start') values = f(*args, **kwargs) print('End') return values return wrapper @fun def fun2(x): print('Funtion 2') return x @fun def fun3(): print('Function 3') a = fun2('a') print() print(A) print() fun3()
symbols = [ 'TSLA', 'GOOG', 'FB', 'NFLX', 'PFE', 'KO', 'AAPL', 'MSFT', 'DIS', 'UBER', 'AMZN', 'TWTR', 'SBUX', 'F', 'XOM', 'GFINBURO.MX', 'BIMBOA.MX', 'GFNORTEO.MX', 'TLEVISACPO.MX', 'AZTECACPO.MX', 'ALSEA.MX', 'ORBIA.MX', 'POSA...
symbols = ['TSLA', 'GOOG', 'FB', 'NFLX', 'PFE', 'KO', 'AAPL', 'MSFT', 'DIS', 'UBER', 'AMZN', 'TWTR', 'SBUX', 'F', 'XOM', 'GFINBURO.MX', 'BIMBOA.MX', 'GFNORTEO.MX', 'TLEVISACPO.MX', 'AZTECACPO.MX', 'ALSEA.MX', 'ORBIA.MX', 'POSADASA.MX', 'VOLARA.MX', 'LIVEPOLC-1.MX', 'AEROMEX.MX', 'WALMEX.MX', 'PE&OLES.MX', 'BBVA.MX', 'G...
# ADD BINARY LEETCODE SOLUTION: # creating a class. class Solution(object): # creating a function to solve the problem. def addBinary(self, a, b): # using the 'bin' function to convert each integer into its binary format. sum = bin(int(a, 2) + int(b, 2)) # returning the va...
class Solution(object): def add_binary(self, a, b): sum = bin(int(a, 2) + int(b, 2)) return sum[2:]
mywords = ['Krishna', 'Rameshwar Dass', 'Usha', 'Ramesh'] for w in mywords: print(w, end='') #Krishna Rameshwar Dass Usha Ramesh
mywords = ['Krishna', 'Rameshwar Dass', 'Usha', 'Ramesh'] for w in mywords: print(w, end='')
#!/usr/bin/env python3 SQL92_reserved = [ "ABSOLUTE", "ACTION", "ADD", "ALL", "ALLOCATE", "ALTER", "AND", "ANY", "ARE", "AS", "ASC", "ASSERTION", "AT", "AUTHORIZATION", "AVG", "BEGIN", "BETWEEN", "BIT", "BIT_LENGTH", "BOTH", "BY", "CASCADE", "CASCADED", "CASE", "CAST", "CATALOG", "CHAR", "CHARACTER", "CHAR...
sql92_reserved = ['ABSOLUTE', 'ACTION', 'ADD', 'ALL', 'ALLOCATE', 'ALTER', 'AND', 'ANY', 'ARE', 'AS', 'ASC', 'ASSERTION', 'AT', 'AUTHORIZATION', 'AVG', 'BEGIN', 'BETWEEN', 'BIT', 'BIT_LENGTH', 'BOTH', 'BY', 'CASCADE', 'CASCADED', 'CASE', 'CAST', 'CATALOG', 'CHAR', 'CHARACTER', 'CHAR_LENGTH', 'CHARACTER_LENGTH', 'CHECK'...
def can_build(env, platform): return True def configure(env): pass def is_enabled(): # Disabled by default being experimental at the moment. # Enable manually with `module_gdscript_transpiler_enabled=yes` option. return False
def can_build(env, platform): return True def configure(env): pass def is_enabled(): return False
class PERIOD: DAILY = "daily" WEEKLY = "weekly" MONTHLY = "monthly" # Converting BYTES to KB, MB, GB BYTES_TO_KBYTES = 1024 BYTES_TO_MBYTES = 1048576 BYTES_TO_GBYTES = 1073741824
class Period: daily = 'daily' weekly = 'weekly' monthly = 'monthly' bytes_to_kbytes = 1024 bytes_to_mbytes = 1048576 bytes_to_gbytes = 1073741824
""" Job initialization. """ class Job(): """ Performs general statistics over the crowdsourcing jobs. """ @staticmethod def aggregate(units, judgments, config): """ Aggregates information about the total number of units, total number of judgments, total number of workers th...
""" Job initialization. """ class Job: """ Performs general statistics over the crowdsourcing jobs. """ @staticmethod def aggregate(units, judgments, config): """ Aggregates information about the total number of units, total number of judgments, total number of workers that...
class MyClass: '''This is the docstring for this class''' def __init__(self): # setup per-instance variables self.x = 1 self.y = 2 self.z = 3 class MySecondClass: '''This is the docstring for this second class''' def __init__(self): # setup per-instance varia...
class Myclass: """This is the docstring for this class""" def __init__(self): self.x = 1 self.y = 2 self.z = 3 class Mysecondclass: """This is the docstring for this second class""" def __init__(self): self.p = 1 self.d = 2 self.q = 3
# coding: utf8 class InvalidUnitToDXAException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class Unit(object): @classmethod def to_dxa(cls, val): if len(val) < 2: return 0 else: unit = ...
class Invalidunittodxaexception(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class Unit(object): @classmethod def to_dxa(cls, val): if len(val) < 2: return 0 else: unit = val[-2:] ...
input = """ c num blocks = 1 c num vars = 150 c minblockids[0] = 1 c maxblockids[0] = 150 p cnf 150 617 90 -20 8 0 -111 -68 -13 0 8 -150 -9 0 -66 63 -93 0 -135 40 81 0 106 -127 134 0 -54 123 45 0 24 -77 59 0 -82 48 71 0 12 75 87 0 127 -29 88 0 -120 -33 60 0 -126 -102 31 0 134 9 -150 0 62 -56 -83 0 92 27 75 0 -133 -52 5...
input = '\nc num blocks = 1\nc num vars = 150\nc minblockids[0] = 1\nc maxblockids[0] = 150\np cnf 150 617\n90 -20 8 0\n-111 -68 -13 0\n8 -150 -9 0\n-66 63 -93 0\n-135 40 81 0\n106 -127 134 0\n-54 123 45 0\n24 -77 59 0\n-82 48 71 0\n12 75 87 0\n127 -29 88 0\n-120 -33 60 0\n-126 -102 31 0\n134 9 -150 0\n62 -56 -83 0\n92...
def count(word, letter): count = 0 for i in word: if i == letter: count = count + 1 return count word = input('Enter a word:') letter = input('Enter a letter to count in word:') print("There are {} {}'s in your word".format(count(word,letter), letter))
def count(word, letter): count = 0 for i in word: if i == letter: count = count + 1 return count word = input('Enter a word:') letter = input('Enter a letter to count in word:') print("There are {} {}'s in your word".format(count(word, letter), letter))
class Square: def __init__(self, side): self.side = side def perimeter(self): return self.side * 4 def area(self): return self.side ** 2 pass class Rectangle: def __init__(self, width, height): self.width, self.height = width, height def perimeter(self): ...
class Square: def __init__(self, side): self.side = side def perimeter(self): return self.side * 4 def area(self): return self.side ** 2 pass class Rectangle: def __init__(self, width, height): (self.width, self.height) = (width, height) def perimeter(self):...
def first_function(values): ''' (list of int) -> NoneType ''' for i in range(len(values)): if values[i] % 2 == 1: values[i] += 1 def second_function(value): ''' (int) -> int ''' if value % 2 == 1: value += 1 return value def snippet_1(): a = [1, 2,...
def first_function(values): """ (list of int) -> NoneType """ for i in range(len(values)): if values[i] % 2 == 1: values[i] += 1 def second_function(value): """ (int) -> int """ if value % 2 == 1: value += 1 return value def snippet_1(): a = [1, 2, 3] b ...
# -*- coding: utf-8 -*- vagrant = 'vagrant' def up(): return '{} up'.format(vagrant) def ssh(): return '{} ssh'.format(vagrant) def suspend(): return '{} suspend'.format(vagrant) def status(): return '{} status'.format(vagrant) def halt(): return '{} halt'.format(vagrant) def destroy(fo...
vagrant = 'vagrant' def up(): return '{} up'.format(vagrant) def ssh(): return '{} ssh'.format(vagrant) def suspend(): return '{} suspend'.format(vagrant) def status(): return '{} status'.format(vagrant) def halt(): return '{} halt'.format(vagrant) def destroy(force=False): options = '' ...
def split_block (string:str, seps:(str, str)) -> str: _, content = string.split (seps[0]) block, _ = content.split (seps[1]) return block def is_not_empty (value): return value != '' def contens_colons (value:str) -> bool: return value.count(":") == 0 content = "" with open ("examples/add.asm") ...
def split_block(string: str, seps: (str, str)) -> str: (_, content) = string.split(seps[0]) (block, _) = content.split(seps[1]) return block def is_not_empty(value): return value != '' def contens_colons(value: str) -> bool: return value.count(':') == 0 content = '' with open('examples/add.asm') a...
class Solution: def sumOfDistancesInTree(self, N, edges): """ :type N: int :type edges: List[List[int]] :rtype: List[int] """ graph = collections.defaultdict(list) for u, v in edges: graph[u].append(v) graph[v].append(u) sums = ...
class Solution: def sum_of_distances_in_tree(self, N, edges): """ :type N: int :type edges: List[List[int]] :rtype: List[int] """ graph = collections.defaultdict(list) for (u, v) in edges: graph[u].append(v) graph[v].append(u) ...
class Solution: # @return an integer def threeSumClosest(self, num, target): num.sort() res = sum(num[:3]) if res > target: diff = res-target elif res < target: diff = target-res else: return res n = len(num) for i in x...
class Solution: def three_sum_closest(self, num, target): num.sort() res = sum(num[:3]) if res > target: diff = res - target elif res < target: diff = target - res else: return res n = len(num) for i in xrange(n): ...
# -*- encoding:utf-8 -*- """Autogenerated file, do not edit. Submit translations on Transifex.""" MESSAGES = { "%d min remaining to read": "%dminutas de lectura remanente", "(active)": "(active)", "Also available in:": "Anque disponibile in:", "Archive": "Archivo", "Atom feed": "Fluxo Atom", "A...
"""Autogenerated file, do not edit. Submit translations on Transifex.""" messages = {'%d min remaining to read': '%dminutas de lectura remanente', '(active)': '(active)', 'Also available in:': 'Anque disponibile in:', 'Archive': 'Archivo', 'Atom feed': 'Fluxo Atom', 'Authors': 'Authores', 'Categories': 'Categorias', 'C...
''' Prompt: Given two strings, s1 and s2, write code to check if s2 is a rotation of s1. (e.g., "waterbottle" is a rotation of "erbottlewat"). Follow up: What if you could use one call of a helper method isSubstring? ''' # Time: O(n), Space: O(n) def isStringRotation(s1, s2): if len(s1) != len(s2): return False...
""" Prompt: Given two strings, s1 and s2, write code to check if s2 is a rotation of s1. (e.g., "waterbottle" is a rotation of "erbottlewat"). Follow up: What if you could use one call of a helper method isSubstring? """ def is_string_rotation(s1, s2): if len(s1) != len(s2): return False str_length = ...
# Instantiate Cache information n = 10 cache = [None] * (n + 1) def fib_dyn(n): # Base Case if n == 0 or n == 1: return n # Check cache if cache[n] != None: return cache[n] # Keep setting cache cache[n] = fib_dyn(n-1) + fib_dyn(n-2) ret...
n = 10 cache = [None] * (n + 1) def fib_dyn(n): if n == 0 or n == 1: return n if cache[n] != None: return cache[n] cache[n] = fib_dyn(n - 1) + fib_dyn(n - 2) return cache[n] fib_dyn(10)
""" The ``refstate`` module ========================= Provides integral models for boundary layer computations Available functions ------------------- """ class refstate: def __init__(self, **kwargs): self._dict = kwargs #def Reynolds(self):
""" The ``refstate`` module ========================= Provides integral models for boundary layer computations Available functions ------------------- """ class Refstate: def __init__(self, **kwargs): self._dict = kwargs
# -*- coding: utf-8 -*- # TODO: datetime support ### ### DO NOT CHANGE THIS FILE ### ### The code is auto generated, your change will be overwritten by ### code generating. ### DefinitionsNewrun = {'required': ['name'], 'type': 'object', 'properties': {'count': {'type': 'boolean'}, 'prePro': {'type': 'boolean'}, ...
definitions_newrun = {'required': ['name'], 'type': 'object', 'properties': {'count': {'type': 'boolean'}, 'prePro': {'type': 'boolean'}, 'fqRegex': {'type': 'string'}, 'star': {'type': 'boolean'}, 'name': {'type': 'string'}, 'fastqc': {'type': 'boolean'}, 'genomeInddex': {'type': 'string'}, 'gtfFile': {'type': 'string...
class Callback(object): def __init__(self, fire_rate=1.0, fire_interval=None): self.FireRate = fire_rate self.NextFire = self.FireInterval = fire_interval self.FireLevel = 0.0 self.FireCount = 0 def __call__(self, event, *params, **args): self.FireCount += 1...
class Callback(object): def __init__(self, fire_rate=1.0, fire_interval=None): self.FireRate = fire_rate self.NextFire = self.FireInterval = fire_interval self.FireLevel = 0.0 self.FireCount = 0 def __call__(self, event, *params, **args): self.FireCount += 1 sel...
class A(Exception): def __init__(s, err, *args): s.err = err s.d = 2323 @property def message(s): return 'kawabunga' def __str__(s): return s.message class B(A): pass try: raise A('hh', 89) except B as e: print(1)
class A(Exception): def __init__(s, err, *args): s.err = err s.d = 2323 @property def message(s): return 'kawabunga' def __str__(s): return s.message class B(A): pass try: raise a('hh', 89) except B as e: print(1)
"""Classifier calibration techniques. https://arxiv.org/pdf/1902.06977.pdf https://arxiv.org/abs/1706.04599 """
"""Classifier calibration techniques. https://arxiv.org/pdf/1902.06977.pdf https://arxiv.org/abs/1706.04599 """
string = input() for i in range(len(string)): emoticon = '' if string[i] == ':': emoticon += string[i] + string[i + 1] print(emoticon)
string = input() for i in range(len(string)): emoticon = '' if string[i] == ':': emoticon += string[i] + string[i + 1] print(emoticon)
# -*- encoding: utf-8 -*- ####################################################################################################################### # DESCRIPTION: ####################################################################################################################### # TODO #############################...
class Cnf: def __init__(self): self.clauses = [] self.variables = [] self.map = {} def add(self, clause): for term in clause.terms: name = term.name if not name in self.map: self.map[name] = len(self.variables) self.variab...
"""7. Reverse Integer https://leetcode.com/problems/reverse-integer/ Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (s...
"""7. Reverse Integer https://leetcode.com/problems/reverse-integer/ Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (s...
""" Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could ...
""" Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could ...
''' For a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating in sequence. If word is not a substring of sequence, word's maximum k-repeating value is 0. ...
""" For a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating in sequence. If word is not a substring of sequence, word's maximum k-repeating value is 0. ...
altPulo, qntdCano = map(int, input().split()) canos = list(map(int, input().split())) atual = canos.pop(0) for cano in canos: if max([cano, atual]) - min([cano, atual]) > altPulo: print('GAME OVER') quit() atual = cano print('YOU WIN')
(alt_pulo, qntd_cano) = map(int, input().split()) canos = list(map(int, input().split())) atual = canos.pop(0) for cano in canos: if max([cano, atual]) - min([cano, atual]) > altPulo: print('GAME OVER') quit() atual = cano print('YOU WIN')
# this graph to check the algorithm graph={ 'S':['B','D','A'], 'A':['C'], 'B':['D'], 'C':['G','D'], 'S':['G'], } #function of BFS def BFS(graph,start,goal): Visited=[] queue=[[start]] while queue: path=queue.pop(0) node=path[-1] if node in Visited: ...
graph = {'S': ['B', 'D', 'A'], 'A': ['C'], 'B': ['D'], 'C': ['G', 'D'], 'S': ['G']} def bfs(graph, start, goal): visited = [] queue = [[start]] while queue: path = queue.pop(0) node = path[-1] if node in Visited: continue Visited.append(node) if node == g...
""" 1184. Distance Between Bus Stops Easy A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n. The bus goes along both directions i.e. clockwise and counterclockwise. Re...
""" 1184. Distance Between Bus Stops Easy A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n. The bus goes along both directions i.e. clockwise and counterclockwise. Re...
class Solution: def solve(self, nums): sameIndexAfterSortingCount = 0 sortedNums = sorted(nums) for i in range(len(nums)): if sortedNums[i] == nums[i]: sameIndexAfterSortingCount += 1 return sameIndexAfterSortingCount
class Solution: def solve(self, nums): same_index_after_sorting_count = 0 sorted_nums = sorted(nums) for i in range(len(nums)): if sortedNums[i] == nums[i]: same_index_after_sorting_count += 1 return sameIndexAfterSortingCount
S = 'shrubbery' L = list(S) print('L', L)
s = 'shrubbery' l = list(S) print('L', L)
def get_binary_nmubmer(decimal_number): assert isinstance(decimal_number, int) return bin(decimal_number) print(get_binary_nmubmer(10.5))
def get_binary_nmubmer(decimal_number): assert isinstance(decimal_number, int) return bin(decimal_number) print(get_binary_nmubmer(10.5))
def is_kadomatsu(a): if a[0] == a[1] or a[1] == a[2] or a[0] == a[2]: return False return min(a) == a[1] or max(a) == a[1] a = list(map(int, input().split())) b = list(map(int, input().split())) for i in range(3): for j in range(3): a[i], b[j] = b[j], a[i] if is_kadomatsu(a) and i...
def is_kadomatsu(a): if a[0] == a[1] or a[1] == a[2] or a[0] == a[2]: return False return min(a) == a[1] or max(a) == a[1] a = list(map(int, input().split())) b = list(map(int, input().split())) for i in range(3): for j in range(3): (a[i], b[j]) = (b[j], a[i]) if is_kadomatsu(a) and ...
class Tesla: # WRITE YOUR CODE HERE def __init__(self, model: str, color: str, autopilot: bool = False, seats_count: int = 5, is_locked: bool = True, battery_charge: float = 99.9, efficiency: float = 0.3): self.__model = model self.__color = color self.__autopilot = autopilot sel...
class Tesla: def __init__(self, model: str, color: str, autopilot: bool=False, seats_count: int=5, is_locked: bool=True, battery_charge: float=99.9, efficiency: float=0.3): self.__model = model self.__color = color self.__autopilot = autopilot self.__battery_charge = battery_charge ...
def sum(*args): total_sum = 0 for number in args: total_sum += number return total_sum result = sum(1, 3, 4, 5, 8, 9, 16) print({ 'result': result })
def sum(*args): total_sum = 0 for number in args: total_sum += number return total_sum result = sum(1, 3, 4, 5, 8, 9, 16) print({'result': result})
class VangError(Exception): def __init__(self, msg=None, key=None): self.msg = msg or {} self.key = key class InitError(Exception): pass
class Vangerror(Exception): def __init__(self, msg=None, key=None): self.msg = msg or {} self.key = key class Initerror(Exception): pass
BOS_TOKEN = '[unused98]' EOS_TOKEN = '[unused99]' CLS_TOKEN = '[CLS]' SPACE_TOKEN = '[unused1]' UNK_TOKEN = '[UNK]' SPECIAL_TOKENS = [BOS_TOKEN, EOS_TOKEN, CLS_TOKEN, SPACE_TOKEN, UNK_TOKEN] TRAIN = 'train' EVAL = 'eval' PREDICT = 'infer' MODAL_LIST = ['image', 'others']
bos_token = '[unused98]' eos_token = '[unused99]' cls_token = '[CLS]' space_token = '[unused1]' unk_token = '[UNK]' special_tokens = [BOS_TOKEN, EOS_TOKEN, CLS_TOKEN, SPACE_TOKEN, UNK_TOKEN] train = 'train' eval = 'eval' predict = 'infer' modal_list = ['image', 'others']
class Solution: def reverseStr(self, s, k): """ :type s: str :type k: int :rtype: str """ ans = [] i = 0 while i < len(s): di = min(len(s) - i, k) ans.append(s[i:i + di][::-1]) i += di di = min(len(s) - i...
class Solution: def reverse_str(self, s, k): """ :type s: str :type k: int :rtype: str """ ans = [] i = 0 while i < len(s): di = min(len(s) - i, k) ans.append(s[i:i + di][::-1]) i += di di = min(len(s) -...
def saveHigh(whatyouwant): file = open('HighPriorityIssues.txt', 'a') file.write(formatError(whatyouwant)) file.close() def saveMedium(whatyouwant): file = open('MediumPriorityIssues.txt', 'a') file.write(formatError(whatyouwant)) file.close() def saveLow(whatyouwant): file = open('LowPriorityIssues.txt', 'a...
def save_high(whatyouwant): file = open('HighPriorityIssues.txt', 'a') file.write(format_error(whatyouwant)) file.close() def save_medium(whatyouwant): file = open('MediumPriorityIssues.txt', 'a') file.write(format_error(whatyouwant)) file.close() def save_low(whatyouwant): file = open('Lo...
#!/usr/bin/python3 def add(*matrices): def check(data): if data == 1: return True else: raise ValueError return [[sum(slice) for slice in zip(*row) if check(len(set(map(len, row))))] for row in zip(*matrices) if check(len(set(map(len, matrices))))]
def add(*matrices): def check(data): if data == 1: return True else: raise ValueError return [[sum(slice) for slice in zip(*row) if check(len(set(map(len, row))))] for row in zip(*matrices) if check(len(set(map(len, matrices))))]
""" :py:mod:`pypara` is a Python library for - encoding currencies and monetary value objects, - performing monetary arithmetic and conversions, and - running rudimentary accounting operations. Furthermore, there are some type convenience for general use. The source code is organised in sub-packages and sub-modules....
""" :py:mod:`pypara` is a Python library for - encoding currencies and monetary value objects, - performing monetary arithmetic and conversions, and - running rudimentary accounting operations. Furthermore, there are some type convenience for general use. The source code is organised in sub-packages and sub-modules....
# By Websten from forums # # Given your birthday and the current date, calculate your age in days. # Account for leap days. # # Assume that the birthday and current date are correct dates (and no # time travel). # def daysBetweenDates(year1, month1, day1, year2, month2, day2): daysOfMonths = [ 31, ...
def days_between_dates(year1, month1, day1, year2, month2, day2): days_of_months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0] if is_leap(year1): daysOfMonths[1] = 29 else: daysOfMonths[1] = 28 if year1 == year2: return daysOfMonths[month1 - 1] - day1 + sum(daysOfMonths[m...
class HWriter(object): def __init__(self): self.__bIsNewLine = True # are we at a new line position? self.__bHasContent = False # do we already have content in this line? self.__allParts = [] self.__prefix = "" self.__nIndent = 0 # def incrementIndent(self): self.__nIndent += 1 if self.__nInde...
class Hwriter(object): def __init__(self): self.__bIsNewLine = True self.__bHasContent = False self.__allParts = [] self.__prefix = '' self.__nIndent = 0 def increment_indent(self): self.__nIndent += 1 if self.__nIndent > len(self.__prefix): ...
class Symbol: def __init__(self, name): self.name = name def __hash__(self): return hash(self.name) def __eq__(self, other): return self.name == other.name class SymbolTable: def __init__(self): self._symbol_table = dict() def put_symbol(self, symbol): se...
class Symbol: def __init__(self, name): self.name = name def __hash__(self): return hash(self.name) def __eq__(self, other): return self.name == other.name class Symboltable: def __init__(self): self._symbol_table = dict() def put_symbol(self, symbol): s...
""" Chovin Carlson - House by the Waves: https://www.youtube.com/watch?v=nkU8r5QKN3Y How to: - Run the statements line by line (alt+enter), go to the next one whenever you feel like - The "#### > run block <" blocks should be executed together (ctrl+enter) - If you want to fast-forward through the ...
""" Chovin Carlson - House by the Waves: https://www.youtube.com/watch?v=nkU8r5QKN3Y How to: - Run the statements line by line (alt+enter), go to the next one whenever you feel like - The "#### > run block <" blocks should be executed together (ctrl+enter) - If you want to fast-forward through the ...
#Max retorna o maior numero de um iteravel ou o maior de 2 ou mais elementos #Min retorna o menor numero de um iteravel ou o menor de 2 ou mais elementos lista=[9,5,2,1,4,5,3,6,21,5,4,55,0] print(max(lista)) print(max(8,9,5,7,4,5,6)) dicionario={'a':0,'b':1,'f':51,'g':12,'q':5,'u':3,'d':2} print(max(dicionario)) prin...
lista = [9, 5, 2, 1, 4, 5, 3, 6, 21, 5, 4, 55, 0] print(max(lista)) print(max(8, 9, 5, 7, 4, 5, 6)) dicionario = {'a': 0, 'b': 1, 'f': 51, 'g': 12, 'q': 5, 'u': 3, 'd': 2} print(max(dicionario)) print(max(dicionario.values())) print(min(lista)) print(min(8, 9, 5, 7, 4, 5, 6)) dicionario1 = {'a': 0, 'b': 1, 'f': 51, 'g'...
# Input your Wi-Fi credentials here, if applicable, and rename to "secrets.py" ssid = '' wpa = ''
ssid = '' wpa = ''
# To use this bot you need to set up the bot in here, # You need to decide the prefix you want to use, # and you need your Token and Application ID from # the discord page where you manage your apps and bots. # You need your User ID which you can get from the # context menu on your name in discord under Copy ID. # if y...
bot_prefix = 'YOUR_BOT_PREFIX_HERE' token = 'YOUR_TOKEN_HERE' application_id = 'YOUR_APPLICATION_ID' owners = [123456789, 987654321] data_gov_api_key = 'DEMO_KEY' openweather_api_key = 'YOUR_API_KEY_HERE' wolframalpha_api_key = 'YOUR_API_KEY_HERE' exchangerate_api_key = 'YOUR_API_KEY_HERE' googlegeo_api_key = 'YOUR_API...
# Constants VERSION = '2.0' STATUS_GREY = 'lair-grey' STATUS_BLUE = 'lair-blue' STATUS_GREEN = 'lair-greeen' STATUS_ORANGE = 'lair-orange' STATUS_RED = 'lair-red' STATUS_MAP = [STATUS_GREY, STATUS_BLUE, STATUS_GREEN, STATUS_ORANGE, STATUS_RED] PROTOCOL_TCP = 'tcp' PROTOCOL_UDP = 'udp' PROTOCOL_ICMP = 'icmp' PRODUCT_UN...
version = '2.0' status_grey = 'lair-grey' status_blue = 'lair-blue' status_green = 'lair-greeen' status_orange = 'lair-orange' status_red = 'lair-red' status_map = [STATUS_GREY, STATUS_BLUE, STATUS_GREEN, STATUS_ORANGE, STATUS_RED] protocol_tcp = 'tcp' protocol_udp = 'udp' protocol_icmp = 'icmp' product_unknown = 'unkn...
#!/usr/bin/env python3 # https://codeforces.com/problemset/problem/996/A total = int(input()) bills = [100,20,10,5,1] nob = 0 for b in bills: nob += total//b total = total%b if total == 0: break print(nob)
total = int(input()) bills = [100, 20, 10, 5, 1] nob = 0 for b in bills: nob += total // b total = total % b if total == 0: break print(nob)
# -*- coding: utf-8 -*- """ Created on Fri Oct 2 11:25:48 2020 @author: Tarun Jaiswal """ ''' a=int(input("A= ")) b=int(input("B= ")) c=int(input("C= ")) d=int(input("D= ")) max=a variablename="a= " if b>max: variablename="b= " max=b if c>max: variablename="c= " max=c if d>max: variablename="d= "...
""" Created on Fri Oct 2 11:25:48 2020 @author: Tarun Jaiswal """ '\na=int(input("A= "))\nb=int(input("B= "))\nc=int(input("C= "))\nd=int(input("D= "))\nmax=a\nvariablename="a= "\nif b>max:\n variablename="b= "\n max=b\nif c>max:\n variablename="c= "\n max=c\nif d>max:\n variablename="d= "\n max=d\n...
# Copyright (c) 2020 Anastasiia Birillo class VkCity: def __init__(self, data: dict) -> None: self.id = data['id'] self.title = data.get('title') def __str__(self): return f"[{', '.join(map(lambda key: f'{key}={self.__dict__[key]}', self.__dict__))}]" class VkUser: def __init__(s...
class Vkcity: def __init__(self, data: dict) -> None: self.id = data['id'] self.title = data.get('title') def __str__(self): return f"[{', '.join(map(lambda key: f'{key}={self.__dict__[key]}', self.__dict__))}]" class Vkuser: def __init__(self, data: dict) -> None: self.i...
GENDER_VALUES = (('M', 'Male'), ('F', 'Female'), ('TG', 'Transgender')) MARITAL_STATUS_VALUES = (('M', 'Married'), ('S', 'Single'), ('U', 'Unknown')) CATEGORY_VALUES = (('BR', 'Bramhachari'), ('FTT', 'Full Time Teacher'), ...
gender_values = (('M', 'Male'), ('F', 'Female'), ('TG', 'Transgender')) marital_status_values = (('M', 'Married'), ('S', 'Single'), ('U', 'Unknown')) category_values = (('BR', 'Bramhachari'), ('FTT', 'Full Time Teacher'), ('PTT', 'Part Time Teacher'), ('FTV', 'Full Time Volunteer'), ('VOL', 'Volunteer'), ('STAFF', 'Sta...
"""Brain Games. This is my Python course level 1 project. Nothing special, it's just a bundle of mini-games with common CLI. """
"""Brain Games. This is my Python course level 1 project. Nothing special, it's just a bundle of mini-games with common CLI. """
input = """ 8 2 2 3 0 0 1 4 2 1 3 2 1 4 2 2 2 3 6 0 1 0 4 3 0 4 c 3 b 2 a 0 B+ 0 B- 1 0 1 """ output = """ COST 0@1 """
input = '\n8 2 2 3 0 0\n1 4 2 1 3 2\n1 4 2 2 2 3\n6 0 1 0 4 3\n0\n4 c\n3 b\n2 a\n0\nB+\n0\nB-\n1\n0\n1\n' output = '\nCOST 0@1\n'
""" LeetCode Problem: 215. Kth Largest Element in an Array Link: https://leetcode.com/problems/kth-largest-element-in-an-array/ Language: Python Written by: Mostofa Adib Shakib """ class Solution(object): def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rty...
""" LeetCode Problem: 215. Kth Largest Element in an Array Link: https://leetcode.com/problems/kth-largest-element-in-an-array/ Language: Python Written by: Mostofa Adib Shakib """ class Solution(object): def find_kth_largest(self, nums, k): """ :type nums: List[int] :type k: int :...
def solution(S): # write your code in Python 3.6 if not S: return 1 stack = [] for s in S: if s == '(': stack.append(s) else: if not stack: return 0 else: stack.pop() if stack: return 0 return 1
def solution(S): if not S: return 1 stack = [] for s in S: if s == '(': stack.append(s) elif not stack: return 0 else: stack.pop() if stack: return 0 return 1
class DistributionDiscriminator: def __init__(self, dataset=None, extractor=None, criterion=None, **kwargs): super().__init__(**kwargs) self.dataset = dataset self.extractor = extractor self.criterion = criterion def judge(self, samples): return self.extractor.extract(samples) def compare(self, fe...
class Distributiondiscriminator: def __init__(self, dataset=None, extractor=None, criterion=None, **kwargs): super().__init__(**kwargs) self.dataset = dataset self.extractor = extractor self.criterion = criterion def judge(self, samples): return self.extractor.extract(s...
class Solution: def stack(self, s: str) -> list: st = [] for x in s: if x == '#': if len(st) != 0: st.pop() continue st.append(x) return st def backspaceCompare(self, S: str, T: str) -> bool: s = self.st...
class Solution: def stack(self, s: str) -> list: st = [] for x in s: if x == '#': if len(st) != 0: st.pop() continue st.append(x) return st def backspace_compare(self, S: str, T: str) -> bool: s = self....
connections = {} connections["Joj"] = [] connections["Emily"] = ["Joj","Jeph","Jeff"] connections["Jeph"] = ["Joj","Geoff"] connections["Jeff"] = ["Joj","Judge"] connections["Geoff"] = ["Joj","Jebb"] connections["Jebb"] = ["Joj","Emily"] connections["Judge"] = ["Joj","Judy"] connections["Jodge"] = ["Joj","Jebb","Stepha...
connections = {} connections['Joj'] = [] connections['Emily'] = ['Joj', 'Jeph', 'Jeff'] connections['Jeph'] = ['Joj', 'Geoff'] connections['Jeff'] = ['Joj', 'Judge'] connections['Geoff'] = ['Joj', 'Jebb'] connections['Jebb'] = ['Joj', 'Emily'] connections['Judge'] = ['Joj', 'Judy'] connections['Jodge'] = ['Joj', 'Jebb'...
class Constants: def __init__(self): pass SIMPLE_CONFIG_DIR = "/etc/simple_grid" GIT_PKG_NAME = "git" DOCKER_PKG_NAME = "docker" BOLT_PKG_NAME = "bolt"
class Constants: def __init__(self): pass simple_config_dir = '/etc/simple_grid' git_pkg_name = 'git' docker_pkg_name = 'docker' bolt_pkg_name = 'bolt'
class Solution: def longestPrefix(self, s: str) -> str: pi = [0]*len(s) for i in range(1, len(s)): k = pi[i-1] while k > 0 and s[i] != s[k]: k = pi[k-1] if s[i] == s[k]: k += 1 pi[i] = k print('pi is...
class Solution: def longest_prefix(self, s: str) -> str: pi = [0] * len(s) for i in range(1, len(s)): k = pi[i - 1] while k > 0 and s[i] != s[k]: k = pi[k - 1] if s[i] == s[k]: k += 1 pi[i] = k print('pi is: ', ...
def _update_doc_distribution( X, exp_topic_word_distr, doc_topic_prior, max_doc_update_iter, mean_change_tol, cal_sstats, random_state, ): is_sparse_x = sp.issparse(X) n_samples, n_features = X.shape n_topics = exp_topic_word_distr.shape[0] if random_state: doc_topic...
def _update_doc_distribution(X, exp_topic_word_distr, doc_topic_prior, max_doc_update_iter, mean_change_tol, cal_sstats, random_state): is_sparse_x = sp.issparse(X) (n_samples, n_features) = X.shape n_topics = exp_topic_word_distr.shape[0] if random_state: doc_topic_distr = random_state.gamma(10...
def read_convert(input: str) -> list: dict_list = [] input = input.split("__::__") for lines in input: line_dict = {} line = lines.split("__$$__") for l in line: dict_value = l.split("__=__") key = dict_value[0] if len(dict_value) == 1: ...
def read_convert(input: str) -> list: dict_list = [] input = input.split('__::__') for lines in input: line_dict = {} line = lines.split('__$$__') for l in line: dict_value = l.split('__=__') key = dict_value[0] if len(dict_value) == 1: ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param {TreeNode} root # @return {integer[]} def preorderTraversal(self, root): self.preorder = [] self.trave...
class Solution: def preorder_traversal(self, root): self.preorder = [] self.traverse(root) return self.preorder def traverse(self, root): if root: self.preorder.append(root.val) self.traverse(root.left) self.traverse(root.right)
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"websites_url": "01-training-data.ipynb", "m": "01-training-data.ipynb", "piece_dirs": "01-training-data.ipynb", "assert_coord": "01-training-data.ipynb", "Board": "01-trai...
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'websites_url': '01-training-data.ipynb', 'm': '01-training-data.ipynb', 'piece_dirs': '01-training-data.ipynb', 'assert_coord': '01-training-data.ipynb', 'Board': '01-training-data.ipynb', 'Boards': '01-training-data.ipynb', 'boards': '01-training-...
n = int(input()) i = 5 while i > 0: root = 1 while root ** i < n: root = root + 1 if root ** i == n: print(root, i) i = i - 1
n = int(input()) i = 5 while i > 0: root = 1 while root ** i < n: root = root + 1 if root ** i == n: print(root, i) i = i - 1
# -*- coding: utf-8 -*- # Authors: Y. Jia <ytjia.zju@gmail.com> """ Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. https://leetcode.com/problems/maximal-square/description/ """ class Solution(object): def maximalSquare(self, matrix): "...
""" Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. https://leetcode.com/problems/maximal-square/description/ """ class Solution(object): def maximal_square(self, matrix): """ :type matrix: List[List[str]] :rtype: int ...
a = [1, 2, 3, 4, 5] print(a[0] + 1) #length of list x = len(a) print(x) print(a[-1]) #splicing print(a[0:3]) print(a[0:]) b = "test" print(b[0:1])
a = [1, 2, 3, 4, 5] print(a[0] + 1) x = len(a) print(x) print(a[-1]) print(a[0:3]) print(a[0:]) b = 'test' print(b[0:1])
def extgcd(a, b): """solve ax + by = gcd(a, b) return x, y, gcd(a, b) used in NTL1E(AOJ) """ g = a if b == 0: x, y = 1, 0 else: x, y, g = extgcd(b, a % b) x, y = y, x - a // b * y return x, y, g
def extgcd(a, b): """solve ax + by = gcd(a, b) return x, y, gcd(a, b) used in NTL1E(AOJ) """ g = a if b == 0: (x, y) = (1, 0) else: (x, y, g) = extgcd(b, a % b) (x, y) = (y, x - a // b * y) return (x, y, g)
class Solution(object): def toGoatLatin(self, sentence): """ :type sentence: str :rtype: str """ count = 0 res = [] for w in sentence.split(): count += 1 if w[0].lower() in ['a', 'e', 'i', 'o', 'u']: res.appen...
class Solution(object): def to_goat_latin(self, sentence): """ :type sentence: str :rtype: str """ count = 0 res = [] for w in sentence.split(): count += 1 if w[0].lower() in ['a', 'e', 'i', 'o', 'u']: res.append(w + 'm...
class Solution: def subarraySum(self, nums: List[int], k: int) -> int: count = 0 prefix_sum = 0 dic = {0: 1} for i in range(len(nums)): prefix_sum += nums[i] if prefix_sum - k in dic: count += dic[prefix_sum - k] if prefix_sum ...
class Solution: def subarray_sum(self, nums: List[int], k: int) -> int: count = 0 prefix_sum = 0 dic = {0: 1} for i in range(len(nums)): prefix_sum += nums[i] if prefix_sum - k in dic: count += dic[prefix_sum - k] if prefix_sum in ...
""" https://leetcode.com/problems/detect-capital/ Given a word, you need to judge whether the usage of capitals in it is right or not. We define the usage of capitals in a word to be right when one of the following cases holds: All letters in this word are capitals, like "USA". All letters in this word are not capita...
""" https://leetcode.com/problems/detect-capital/ Given a word, you need to judge whether the usage of capitals in it is right or not. We define the usage of capitals in a word to be right when one of the following cases holds: All letters in this word are capitals, like "USA". All letters in this word are not capita...
n = int(input()) a = list(map(int,input().split())) q,w=0,0 for i in a: if i ==25:q+=1 elif i==50:q-=1;w+=1 else: if w>0:w-=1;q-=1 else:q-=3 if q<0 or w<0:n=0;break if n==0:print("NO") else:print("YES")
n = int(input()) a = list(map(int, input().split())) (q, w) = (0, 0) for i in a: if i == 25: q += 1 elif i == 50: q -= 1 w += 1 elif w > 0: w -= 1 q -= 1 else: q -= 3 if q < 0 or w < 0: n = 0 break if n == 0: print('NO') else: p...