content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ pre = None i = 0 while i < len(nums): if pre is None: pre = nums[0] i += 1 elif nums[i] == pre: ...
class Solution(object): def remove_duplicates(self, nums): """ :type nums: List[int] :rtype: int """ pre = None i = 0 while i < len(nums): if pre is None: pre = nums[0] i += 1 elif nums[i] == pre: ...
"""[0 - ally ranks, 1 - enemy ranks, 2 - stun skill chance or blight damage, 3 - move distance]""" AttackSkills = { # highwayman 'wicked_slice': [[1, 2, 3], [1, 2]], 'opened_vein': [[1, 2, 3], [1, 2]], 'pistol_shot': [[2, 3, 4], [2, 3, 4]], 'duelist_advance': [[2, 3, 4], [1, 2, 3], None, 1], ...
"""[0 - ally ranks, 1 - enemy ranks, 2 - stun skill chance or blight damage, 3 - move distance]""" attack_skills = {'wicked_slice': [[1, 2, 3], [1, 2]], 'opened_vein': [[1, 2, 3], [1, 2]], 'pistol_shot': [[2, 3, 4], [2, 3, 4]], 'duelist_advance': [[2, 3, 4], [1, 2, 3], None, 1], 'point_blank_shot': [[1], [1], None, -1]...
class AbstractCredentialValidator(object): """An abstract CredentialValidator, when inherited it must validate self.user credentials agains self.action""" def __init__(self, action, user): self.action = action self.user = user def updatePDUWithUserDefaults(self, PDU): """Must u...
class Abstractcredentialvalidator(object): """An abstract CredentialValidator, when inherited it must validate self.user credentials agains self.action""" def __init__(self, action, user): self.action = action self.user = user def update_pdu_with_user_defaults(self, PDU): """Mu...
def add_elem(lst,ele): lst.append(ele) my_lst=[1,2,3] print(my_lst) add_elem(my_lst,5) print(my_lst)
def add_elem(lst, ele): lst.append(ele) my_lst = [1, 2, 3] print(my_lst) add_elem(my_lst, 5) print(my_lst)
print("Welcome to the GPA calculator") print("Please enter all your letter grades, one per line.") print("Enter a blank line to designate the end.") # map from letter grade to point value points = { 'A+': 4.0, 'A': 3.8, 'A-': 3.67, 'B+': 3.33, 'B': 3.0, 'B-': 2.67, 'C+': 2.33, 'C': 2.0,...
print('Welcome to the GPA calculator') print('Please enter all your letter grades, one per line.') print('Enter a blank line to designate the end.') points = {'A+': 4.0, 'A': 3.8, 'A-': 3.67, 'B+': 3.33, 'B': 3.0, 'B-': 2.67, 'C+': 2.33, 'C': 2.0, 'C-': 1.67, 'D': 1.0, 'F': 0.0} num_courses = 0 total_points = 0 done = ...
class Logger(object): def log(self, str): print("Log: {}".format(str)) def error(self, str): print("Error: {}".format(str)) def message(self, str): print("Message: {}".format(str))
class Logger(object): def log(self, str): print('Log: {}'.format(str)) def error(self, str): print('Error: {}'.format(str)) def message(self, str): print('Message: {}'.format(str))
FAIL_ON_ANY = 'any' FAIL_ON_NEW = 'new' # Identifies that a comment came from Lintly. This is used to aid in automatically # deleting old PR comments/reviews. This is valid Markdown that is hidden from # users in GitHub and GitLab. LINTLY_IDENTIFIER = '<!-- Automatically posted by Lintly -->'
fail_on_any = 'any' fail_on_new = 'new' lintly_identifier = '<!-- Automatically posted by Lintly -->'
# # PySNMP MIB module ADSL-LINE-EXT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADSL-LINE-EXT-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:13:46 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
(adsl_line_conf_profile_entry, adsl_atur_perf_data_entry, adsl_line_alarm_conf_profile_entry, adsl_line_entry, adsl_atur_interval_entry, adsl_atuc_perf_data_entry, adsl_atuc_interval_entry, adsl_mib) = mibBuilder.importSymbols('ADSL-LINE-MIB', 'adslLineConfProfileEntry', 'adslAturPerfDataEntry', 'adslLineAlarmConfProfi...
errors_find = { 'ServerError': { 'response': "Some thing went wrong. Please try after some time.", 'status': 500, }, 'BadRequest': { 'response': "Request must be valid", 'status': 400 }, } #Code to store error types based on status code.
errors_find = {'ServerError': {'response': 'Some thing went wrong. Please try after some time.', 'status': 500}, 'BadRequest': {'response': 'Request must be valid', 'status': 400}}
# fml_parsetab.py # This file is automatically generated. Do not edit. _tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'bofx eofx newline tab interpolant lce rce string\n\tstart \t: \tbofx\n\t\t\t|\tstart eofx\n\t\t\t|\tstart code\n\t\n\tcode \t: \tnewline \n\t\n\tcode \t: \ttab\n\t\n\tcode \t: \tstring\n\t...
_tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'bofx eofx newline tab interpolant lce rce string\n\tstart \t: \tbofx\n\t\t\t|\tstart eofx\n\t\t\t|\tstart code\n\t\n\tcode \t: \tnewline \n\t\n\tcode \t: \ttab\n\t\n\tcode \t: \tstring\n\t\n\tcode \t: \tlce\n\t\n\tcode \t: \trce\n\t\n\tcode \t: \tinterpolant\n\t...
RAW_SUBTOMOGRAMS = "volumes/raw" LABELED_SUBTOMOGRAMS = "volumes/labels/" PREDICTED_SEGMENTATION_SUBTOMOGRAMS = "volumes/predictions/" CLUSTERING_LABELS = "volumes/cluster_labels/" HDF_INTERNAL_PATH = "MDF/images/0/image"
raw_subtomograms = 'volumes/raw' labeled_subtomograms = 'volumes/labels/' predicted_segmentation_subtomograms = 'volumes/predictions/' clustering_labels = 'volumes/cluster_labels/' hdf_internal_path = 'MDF/images/0/image'
fp=open("list-11\\readme.txt","r") sentence=fp.read() words=sentence.split() d = dict() for c in words: if c not in d: d[c] = 1 else: d[c] += 1 #dictionary values a=d.values() b=max(a) for i in d: if(d[i]==b): print("frequent word:",i,";","count:",b)
fp = open('list-11\\readme.txt', 'r') sentence = fp.read() words = sentence.split() d = dict() for c in words: if c not in d: d[c] = 1 else: d[c] += 1 a = d.values() b = max(a) for i in d: if d[i] == b: print('frequent word:', i, ';', 'count:', b)
class fracao(object): def __init__(self, num, den): self.num = num self.den = den def somar_fracao(self, b): f = fracao(self.num*b.den + b.num*self.den, self.den*b.den) #f.num = #f.den = fracao.simplificar_fracao(f) return f def su...
class Fracao(object): def __init__(self, num, den): self.num = num self.den = den def somar_fracao(self, b): f = fracao(self.num * b.den + b.num * self.den, self.den * b.den) fracao.simplificar_fracao(f) return f def subtrair_fracao(self, b): pass def ...
#!/usr/bin/python3 def inherits_from(obj, a_class): if isinstance(obj, a_class) and type(obj) is not a_class: return True else: return False
def inherits_from(obj, a_class): if isinstance(obj, a_class) and type(obj) is not a_class: return True else: return False
# # A Rangoli Generator # # Author: Jeremy Pedersen # Date: 2019-02-18 # License: "the unlicense" (Google it) # # Define letters for use in rangoli alphabet = 'a b c d e f g h i j k l m n o p q r s t u v w x y z'.split() # Read in rangoli size size = int(input("Set size of rangoli: ")) # Calculate maximum linewidth ...
alphabet = 'a b c d e f g h i j k l m n o p q r s t u v w x y z'.split() size = int(input('Set size of rangoli: ')) max_width = size * 2 - 1 + (size - 1) * 2 for i in list(range(size - 1, 0, -1)) + list(range(0, size)): left = alphabet[1 + i:size] left.reverse() right = alphabet[0 + i:size] center = '-'...
calls = 0 def call(): global calls calls += 1 def reset(): global calls calls = 0
calls = 0 def call(): global calls calls += 1 def reset(): global calls calls = 0
def iterPower(base,exp): ans=1 while exp>0: ans=ans*base exp-=1 return ans
def iter_power(base, exp): ans = 1 while exp > 0: ans = ans * base exp -= 1 return ans
# Requer num e tipo = {"num": int, "tipo": int} select_atributos_criatura = lambda dados = {} : """ Select atributo1, atributo 2 FROM criaturas WHERE Num = :num AND tipo = :tipo ; """ select_all_ref_atributos = lambda dados = {} : """ SELECT Distinct ref FROM atributos """ # Requer tipo e r...
select_atributos_criatura = lambda dados={}: '\n Select atributo1, atributo 2 \n FROM criaturas \n WHERE Num = :num \n AND tipo = :tipo ;\n' select_all_ref_atributos = lambda dados={}: '\n SELECT Distinct ref \n FROM atributos\n' select_atributos_ref = lambda dados={}: '\n SELECT Atributos.nome \n ...
""" G2_RIGHTS. Module to parse traffic configuration file. """ class TraceParser: """Class definition for traffic config file parsing. Args: path (str): Path to input traffic config file. Attributes: jobs (list): List of jobs obtained from traffic config file. Each job corresponds to a ...
""" G2_RIGHTS. Module to parse traffic configuration file. """ class Traceparser: """Class definition for traffic config file parsing. Args: path (str): Path to input traffic config file. Attributes: jobs (list): List of jobs obtained from traffic config file. Each job corresponds to a ...
#Environment related constants ENV_PRODUCTION = 'PRODUCTION' #Staging is used for testing by replicating the same production remote env ENV_STAGING = 'STAGING' #Development local env ENV_DEVELOPMENT = 'DEV' #Automated tests local env ENV_TESTING = 'TEST' ENVIRONMENT_CHOICES = [ ENV_PRODUCTION, ENV_STAGING, ...
env_production = 'PRODUCTION' env_staging = 'STAGING' env_development = 'DEV' env_testing = 'TEST' environment_choices = [ENV_PRODUCTION, ENV_STAGING, ENV_DEVELOPMENT, ENV_TESTING] page_size = 20 email_regexp = "^[a-zA-Z0-9'._-]+@[a-zA-Z0-9._-]+.[a-zA-Z]{2,6}$" oauth2_scopes = 'https://www.googleapis.com/auth/userinfo....
""" Given an array of integers A, return the largest integer that only occurs once. If no integer occurs once, return -1. Example 1: Input: [5,7,3,9,4,9,8,3,1] Output: 8 Explanation: The maximum integer in the array is 9 but it is repeated. The number 8 occurs only once, so it's the answer. Example 2: Input: [9,9,...
""" Given an array of integers A, return the largest integer that only occurs once. If no integer occurs once, return -1. Example 1: Input: [5,7,3,9,4,9,8,3,1] Output: 8 Explanation: The maximum integer in the array is 9 but it is repeated. The number 8 occurs only once, so it's the answer. Example 2: Input: [9,9,...
# coding: utf-8 """ API config settings """ PRODUCTION = True DATABASES = { 'docker': { 'ENGINE': 'mongodb', 'NAME': 'leadbook', 'HOST': 'leadbookdb', 'PORT': 27017, 'TABLE': 'company' }, 'local': { 'ENGINE': 'mongodb', 'NAME': 'leadbook', 'H...
""" API config settings """ production = True databases = {'docker': {'ENGINE': 'mongodb', 'NAME': 'leadbook', 'HOST': 'leadbookdb', 'PORT': 27017, 'TABLE': 'company'}, 'local': {'ENGINE': 'mongodb', 'NAME': 'leadbook', 'HOST': 'localhost', 'PORT': 27017, 'TABLE': 'company'}} time_zone = 'Asia/Singapore' language_code ...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ if head is None or head.next is None: ...
class Solution: def delete_duplicates(self, head): """ :type head: ListNode :rtype: ListNode """ if head is None or head.next is None: return head (cur, last) = (head, None) dup = False while cur: if dup: nex = ...
name = input("Please enter your name:") age = int(input("Please enter your age:")) if type(name) == str: if type(age) == int: print(f"{name} you are {age} years old and you will be 100 after {100 - age} years") else: print("Please enter a valid number") else: print("please enter your name")...
name = input('Please enter your name:') age = int(input('Please enter your age:')) if type(name) == str: if type(age) == int: print(f'{name} you are {age} years old and you will be 100 after {100 - age} years') else: print('Please enter a valid number') else: print('please enter your name')
""" Test cases TODO. """
""" Test cases TODO. """
seq = [0, 1] def create_sequence(n): global seq if n == 0: return [] elif n == 1: return [0] else: seq = [0, 1] for i in range(2, n): seq.append(seq[-1] + seq[-2]) return seq def locate(x): if x in seq: return f"The number - {x} is at in...
seq = [0, 1] def create_sequence(n): global seq if n == 0: return [] elif n == 1: return [0] else: seq = [0, 1] for i in range(2, n): seq.append(seq[-1] + seq[-2]) return seq def locate(x): if x in seq: return f'The number - {x} is at ind...
d1 = dict() print(d1) # DI1 print(type(d1)) d2 = dict({1:'a',2:'b',3:'c'}) print(d2) # DI2 d3 = dict([(1,"python"),(2,"is"),(3,"awesome")]) print(d3) # DI3 d4 = dict(((1,"python"),(2,"is"),(3,"awesome"))) print(d4) # DI4 d5 = dict({(1,"python"),(2,"is"),(3,"awesome")}) print(d5) # DI5 d6 = dict({[1,"python"],[2,"...
d1 = dict() print(d1) print(type(d1)) d2 = dict({1: 'a', 2: 'b', 3: 'c'}) print(d2) d3 = dict([(1, 'python'), (2, 'is'), (3, 'awesome')]) print(d3) d4 = dict(((1, 'python'), (2, 'is'), (3, 'awesome'))) print(d4) d5 = dict({(1, 'python'), (2, 'is'), (3, 'awesome')}) print(d5) d6 = dict({[1, 'python'], [2, 'is'], [3, 'aw...
def parse_array(tokenstream): _ = tokenstream.pop_next() assert _ == "[" result = [] while True: token = tokenstream.pop_next() if token == "]": break result.append(token) return result def parse_varfunction(tokenstream, identifier, scene): identifier_type = tokenstream.pop_next()[1:-1] params...
def parse_array(tokenstream): _ = tokenstream.pop_next() assert _ == '[' result = [] while True: token = tokenstream.pop_next() if token == ']': break result.append(token) return result def parse_varfunction(tokenstream, identifier, scene): identifier_type = ...
class Solution: def lengthoflongestsubstring(self, s): sls = len(set(s)) slen = len(s) if slen < 1: return 0 else: max_len = 1 for i in range(slen): for j in range(i+max_len+1, i+sls+1): curr = s[i:j] curr_l...
class Solution: def lengthoflongestsubstring(self, s): sls = len(set(s)) slen = len(s) if slen < 1: return 0 else: max_len = 1 for i in range(slen): for j in range(i + max_len + 1, i + sls + 1): curr = s[i:j] ...
print("Input: ",end="") str = input() def rev(str): str = str.split(" ") stack = [] for i in str: stack.append(i) while len(stack) > 0: print(stack[-1], end = " ") del stack[-1] print("Output: ",end="") rev(str)
print('Input: ', end='') str = input() def rev(str): str = str.split(' ') stack = [] for i in str: stack.append(i) while len(stack) > 0: print(stack[-1], end=' ') del stack[-1] print('Output: ', end='') rev(str)
class Solution(object): def isScramble(self, s1, s2): """ :type s1: str :type s2: str :rtype: bool """ return True def test_is_scramble(): s = Solution() assert s.isScramble("great", "rgeat") is True assert s.isScramble("abcde", "caebd") is False
class Solution(object): def is_scramble(self, s1, s2): """ :type s1: str :type s2: str :rtype: bool """ return True def test_is_scramble(): s = solution() assert s.isScramble('great', 'rgeat') is True assert s.isScramble('abcde', 'caebd') is False
def compare_reverse_number(A, B): rev_A, rev_B = '', '' for i in range(len(A) - 1, -1, -1): rev_A += A[i] for j in range(len(B) - 1, -1, -1): rev_B += B[j] if rev_A > rev_B: return rev_A else: return rev_B def main(): A, B = input().split() answer = compare_r...
def compare_reverse_number(A, B): (rev_a, rev_b) = ('', '') for i in range(len(A) - 1, -1, -1): rev_a += A[i] for j in range(len(B) - 1, -1, -1): rev_b += B[j] if rev_A > rev_B: return rev_A else: return rev_B def main(): (a, b) = input().split() answer = com...
#!python def linear_search(array, item): """return the first index of item in array or None if item is not found""" # implement linear_search_iterative and linear_search_recursive below, then # change this to call your implementation to verify it passes all tests # return linear_search_iterative(array...
def linear_search(array, item): """return the first index of item in array or None if item is not found""" return linear_search_recursive(array, item) def linear_search_iterative(array, item): for (index, value) in enumerate(array): if item == value: return index return None def li...
TASK = "task" TASK_INSTANCE = "task_instance" X = "X" Y = "Y" MAHOZ = "MAHOZ" XY = f"{X}/{Y}"
task = 'task' task_instance = 'task_instance' x = 'X' y = 'Y' mahoz = 'MAHOZ' xy = f'{X}/{Y}'
class FlyweightMeta(type): """ Flyweight meta class as part of the Flyweight design pattern. - External Usage Documentation: U{https://github.com/tylerlaberge/PyPattyrn#flyweight-pattern} - External Flyweight Pattern documentation: U{https://en.wikipedia.org/wiki/Flyweight_pattern} """ def __ne...
class Flyweightmeta(type): """ Flyweight meta class as part of the Flyweight design pattern. - External Usage Documentation: U{https://github.com/tylerlaberge/PyPattyrn#flyweight-pattern} - External Flyweight Pattern documentation: U{https://en.wikipedia.org/wiki/Flyweight_pattern} """ def __n...
# # PySNMP MIB module RDN-CABLE-SPECTRUM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RDN-CABLE-SPECTRUM-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:54:33 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (d...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, single_value_constraint, value_size_constraint, constraints_union, constraints_intersection) ...
t=int(input("")) for i in range(0,t): a,b=tuple(map(int,input("").split(" "))) d=abs(a-b) print((int(d/10))if(d%10==0)else(int((d+9)/10)))
t = int(input('')) for i in range(0, t): (a, b) = tuple(map(int, input('').split(' '))) d = abs(a - b) print(int(d / 10) if d % 10 == 0 else int((d + 9) / 10))
def repeat(n): def decorator(func): def wrapper(*args, **kwargs): for _ in range(n): func(*args, **kwargs) return wrapper return decorator @repeat(4) def say_hi(): print("Hello") say_hi()
def repeat(n): def decorator(func): def wrapper(*args, **kwargs): for _ in range(n): func(*args, **kwargs) return wrapper return decorator @repeat(4) def say_hi(): print('Hello') say_hi()
if __name__ == "__main__": my_tuple = (1, 2, 3) print('my_tuple:', my_tuple) a, b, c = my_tuple print('a', a) print('b', b) print('c', c) print('my_tuple[0]:', my_tuple[0]) print('my_tuple[1]:', my_tuple[1]) print('my_tuple[1:3]:', my_tuple[1:3]) # my_tuple[0] = 1 # error , tup...
if __name__ == '__main__': my_tuple = (1, 2, 3) print('my_tuple:', my_tuple) (a, b, c) = my_tuple print('a', a) print('b', b) print('c', c) print('my_tuple[0]:', my_tuple[0]) print('my_tuple[1]:', my_tuple[1]) print('my_tuple[1:3]:', my_tuple[1:3])
""" Datos de entrada valor_normal-->van-->int Datos de salida valor_final-->vaf-->float """ #Entrada van=int(input("digite el valor normal de la compra: ")) #Caja negra vaf=((van-(van*0.15))) #Salidas print("El valor final de la compra es: ", vaf)
""" Datos de entrada valor_normal-->van-->int Datos de salida valor_final-->vaf-->float """ van = int(input('digite el valor normal de la compra: ')) vaf = van - van * 0.15 print('El valor final de la compra es: ', vaf)
#Bitonic sequence Dynamic programming # Java code https://github.com/mission-peace/interview/blob/master/src/com/interview/dynamic/BitonicSequence.java def bitonic_sequence( input ): lis = [1]*len(input) lds = [1]*len(input) for i in range(1, len(input)): for j in range(0, i): if input[...
def bitonic_sequence(input): lis = [1] * len(input) lds = [1] * len(input) for i in range(1, len(input)): for j in range(0, i): if input[i] > input[j]: lis[i] = max(lis[i], lis[j] + 1) for i in range(len(input) - 2, -1, -1): for j in range(len(input) - 1, i, -...
class API_Slack_Dialog(): def __init__(self): self.title = "" self.callback_id = "" self.submit_label = "Submit" self.state = "#3AA3E3" self.elements = [] self.notify_on_cancel = True # def add_button(self, name, text, value...
class Api_Slack_Dialog: def __init__(self): self.title = '' self.callback_id = '' self.submit_label = 'Submit' self.state = '#3AA3E3' self.elements = [] self.notify_on_cancel = True def add_element_text(self, label, name, value=None, optional=False, hint=None, p...
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: # Space complexity O(amount) # Time complexity O(amount * the number of coins) # Using Dynamic programinig with bottom-up strategy # First, allocate the storage dp = [amount + 1] * (amount + 1) ...
class Solution: def coin_change(self, coins: List[int], amount: int) -> int: dp = [amount + 1] * (amount + 1) dp[0] = 0 for num in range(amount + 1): for coin in coins: if num - coin >= 0: dp[num] = min(dp[num], dp[num - coin] + 1) if ...
class Solution: def myPow(self, x: float, n: int) -> float: return self.binary_exp_recursive(x, n) def binary_exp_recursive(self, x: float, n: int) -> float: exp = abs(n) ans = self.recurse(x, exp) return ans if n > 0 else 1 / ans def recurse(self, x: float, n: int) -> floa...
class Solution: def my_pow(self, x: float, n: int) -> float: return self.binary_exp_recursive(x, n) def binary_exp_recursive(self, x: float, n: int) -> float: exp = abs(n) ans = self.recurse(x, exp) return ans if n > 0 else 1 / ans def recurse(self, x: float, n: int) -> fl...
""" Problem: https://www.hackerrank.com/challenges/any-or-all/problem Max Score: 20 Difficulty: Easy Author: Ric Date: Nov 14, 2019 """ # Enter your code here. Read input from STDIN. Print output to STDOUT num_of_int = int(input()) list_of_int = list(map(int, input().split(" "))) print(all(i > 0 for i in list_of_int)...
""" Problem: https://www.hackerrank.com/challenges/any-or-all/problem Max Score: 20 Difficulty: Easy Author: Ric Date: Nov 14, 2019 """ num_of_int = int(input()) list_of_int = list(map(int, input().split(' '))) print(all((i > 0 for i in list_of_int)) and any((str(i) == str(i)[::-1] for i in list_of_int)))
lis = [1, 3, 15, 26, 30, 37, 45, 56, ] divisibles = list(filter(lambda x: (x % 15 == 0), lis)) print(divisibles)
lis = [1, 3, 15, 26, 30, 37, 45, 56] divisibles = list(filter(lambda x: x % 15 == 0, lis)) print(divisibles)
# A single line comment """ A multiline comment can be written by using three quotes in sequence, and then by ending with the same. """
""" A multiline comment can be written by using three quotes in sequence, and then by ending with the same. """
# 2. Number Definer # Write a program that reads a floating-point number and prints "zero" if the number is zero. # Otherwise, print "positive" or "negative". Add "small" if the absolute value of the number is less than 1, # or "large" if it exceeds 1 000 000. number = float(input()) if number == 0: print('zero')...
number = float(input()) if number == 0: print('zero') if number > 0: if number > 1000000: print('large positive') elif number < 1: print('small positive') else: print('positive') if number < 0: if abs(number) > 1000000: print('large negative') elif abs(number) < 1...
# -*- coding: utf-8 -*- DATE = 'Data' TEMPERATURE = 'Temperatura do Ar Media (degC)' MAX_TEMP = 'Temperatura do Ar Maxima (degC)' MIN_TEMP = 'Temperatura do Ar Minima (degC)' VARIATION_TEMP = 'Variacao da Temperatura do Ar (degC)' HUMIDITY = 'Umidade relativa Media (%)' MAX_HUMIDITY = 'Umidade relativa Maxima (%)' MIN_...
date = 'Data' temperature = 'Temperatura do Ar Media (degC)' max_temp = 'Temperatura do Ar Maxima (degC)' min_temp = 'Temperatura do Ar Minima (degC)' variation_temp = 'Variacao da Temperatura do Ar (degC)' humidity = 'Umidade relativa Media (%)' max_humidity = 'Umidade relativa Maxima (%)' min_humidity = 'Umidade rela...
def swap(A, i, j): temp = A[i] A[i] = A[j] A[j] = temp def selectionSort(A): for i in range(len(A) - 1): min = i for j in range(i + 1, len(A)): if A[j] < A[min]: min = j swap(A, min, i) if __name__ == '__main__': A = [3, 5, 8, 4, 1, ...
def swap(A, i, j): temp = A[i] A[i] = A[j] A[j] = temp def selection_sort(A): for i in range(len(A) - 1): min = i for j in range(i + 1, len(A)): if A[j] < A[min]: min = j swap(A, min, i) if __name__ == '__main__': a = [3, 5, 8, 4, 1, 9, -2] se...
# should_error # skip-if: '-x' in EXTRA_JIT_ARGS # Syntax error to have a continue outside a loop. def foo(): try: continue finally: pass
def foo(): try: continue finally: pass
"""Advanced example of a complex flow. TODO: copy our ETL example that we're currently using, simplify a bit. """
"""Advanced example of a complex flow. TODO: copy our ETL example that we're currently using, simplify a bit. """
TWOUVO_SEQ = 'ERCGEQGSNMECPNNLCCSQYGYCGMGGDYCGKGCQNGACWTSKRCGSQAGGATCTNNQCCSQYGYCGFGAEYCGAGCQGGPCRADIKCGSQAGGKLCPNNLCCSQWGFCGLGSEFCGGGCQSGACSTDKPCGKDAGGRVCTNNYCCSKWGSCGIGPGYCGAGCQSGGCDG' FIVEHXG_SEQ = 'MRYFFMAEPIRAMEGDLLGVEIITHFASSPARPLHPEFVISSWDNSQKRRFLLDLLRTIAAKHGWFLRHGLFCIVNIDRGMAQLVLQDKDIRALLHAMLFVELQVAEHFSCQDNVLVD...
twouvo_seq = 'ERCGEQGSNMECPNNLCCSQYGYCGMGGDYCGKGCQNGACWTSKRCGSQAGGATCTNNQCCSQYGYCGFGAEYCGAGCQGGPCRADIKCGSQAGGKLCPNNLCCSQWGFCGLGSEFCGGGCQSGACSTDKPCGKDAGGRVCTNNYCCSKWGSCGIGPGYCGAGCQSGGCDG' fivehxg_seq = 'MRYFFMAEPIRAMEGDLLGVEIITHFASSPARPLHPEFVISSWDNSQKRRFLLDLLRTIAAKHGWFLRHGLFCIVNIDRGMAQLVLQDKDIRALLHAMLFVELQVAEHFSCQDNVLVD...
class Solution: def fullJustify(self, words: List[str], maxWidth: int) -> List[str]: n = len(words) res = [] row = [words[0]] length = len(words[0]) # length including necessary space lenwd = len(words[0]) # length of words in this row numwd = 1 # number of words in t...
class Solution: def full_justify(self, words: List[str], maxWidth: int) -> List[str]: n = len(words) res = [] row = [words[0]] length = len(words[0]) lenwd = len(words[0]) numwd = 1 def postprocess(row, lenwd, numwd): res = '' if numw...
# Dungeon problem statement # the dungeon has a size of R x C and you start at cell 'S' and there's an exit at cell 'E'. # a cell full of rock is indicated by a '#' and empty cells are represented by a '.' # ------------C------------- # | S . . # . . . | # | . # . . . # . | # R . # . . . ...
m = [['S', '.', '.', '#', '.', '.', '.'], ['.', '#', '.', '.', '.', '#', '.'], ['.', '#', '.', '.', '.', '.', '.'], ['.', '.', '#', '#', '.', '.', '.'], ['#', '.', '#', 'E', '.', '#', '.']] r = len(m) c = len(m[0]) sr = 0 sc = 0 dr = [-1, +1, 0, 0] dc = [0, 0, +1, -1] rq = [] cq = [] visited = [[False for i in range(C)...
class Node: def __init__(self, data): self.data = data self.next = None class Stack: def __init__(self) -> None: self.root = None def push(self, value) -> None: if self.root is None: self.root = Node(value) else: root_node = self.root ...
class Node: def __init__(self, data): self.data = data self.next = None class Stack: def __init__(self) -> None: self.root = None def push(self, value) -> None: if self.root is None: self.root = node(value) else: root_node = self.root ...
class Solution: def removeDuplicates(self, nums: List[int]) -> int: n = 0 if len(nums) == 0: return 0 for i in range(1,len(nums)): if nums[n] < nums[i]: n += 1 nums[n] = nums[i] return n+1
class Solution: def remove_duplicates(self, nums: List[int]) -> int: n = 0 if len(nums) == 0: return 0 for i in range(1, len(nums)): if nums[n] < nums[i]: n += 1 nums[n] = nums[i] return n + 1
""" Integration tests of this component running live on an integration server """
""" Integration tests of this component running live on an integration server """
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( str ) : n = len ( str ) - 1 i = n while ( i > 0 and str [ i - 1 ] <= str [ i ] ) : i -= 1 i...
def f_gold(str): n = len(str) - 1 i = n while i > 0 and str[i - 1] <= str[i]: i -= 1 if i <= 0: return False j = i - 1 while j + 1 <= n and str[j + 1] <= str[i - 1]: j += 1 str = list(str) temp = str[i - 1] str[i - 1] = str[j] str[j] = temp str = ''.jo...
class CaseChangingStream(): def __init__(self, stream, upper): self._stream = stream self._upper = upper def __getattr__(self, name): return self._stream.__getattribute__(name) def LA(self, offset): c = self._stream.LA(offset) if c <= 0: return c return ord(chr(c).upper() if self._upper else chr(c)....
class Casechangingstream: def __init__(self, stream, upper): self._stream = stream self._upper = upper def __getattr__(self, name): return self._stream.__getattribute__(name) def la(self, offset): c = self._stream.LA(offset) if c <= 0: return c ...
fp = open("1.in", "r") drift = 0 for line in iter(fp.readline, ''): drift += int(line) print(drift) def findDup(): drift = 0 seen = set([0]) for _ in range(1000): fp = open("input1.txt", "r") for line in iter(fp.readline, ''): drift += int(line) if drift in s...
fp = open('1.in', 'r') drift = 0 for line in iter(fp.readline, ''): drift += int(line) print(drift) def find_dup(): drift = 0 seen = set([0]) for _ in range(1000): fp = open('input1.txt', 'r') for line in iter(fp.readline, ''): drift += int(line) if drift in seen...
class CryptoNews: """ class that represents a single piece of crypto news """ def __init__( self, url="", title="", text="", html="", year=0, author="", source="", ): self.url = url self.title = title self.text ...
class Cryptonews: """ class that represents a single piece of crypto news """ def __init__(self, url='', title='', text='', html='', year=0, author='', source=''): self.url = url self.title = title self.text = text self.html = html self.year = year self.a...
class Location: """ Location is an abstraction for representing a location in the World. An instance of the World can have multiple Event(s). Each event has a single Location. Public Variables: * x - x coordinate of the location * y - y coordinate of the location """ def __...
class Location: """ Location is an abstraction for representing a location in the World. An instance of the World can have multiple Event(s). Each event has a single Location. Public Variables: * x - x coordinate of the location * y - y coordinate of the location """ def _...
l1=[] ##Input number of elements in list n=int(input()) ##Input the elements in the list l1=list(map(int,input().split())) ## Create a new list l2 to store the index(from 1 to number of elements in list1) of elements of list 1 l2=[i for i in range(1,n+1)] ##Run a for loop from 1 till the length of list 1(l1) for i in ...
l1 = [] n = int(input()) l1 = list(map(int, input().split())) l2 = [i for i in range(1, n + 1)] for i in range(1, n + 1): x = l1.index(i) y = l2[x] print(l2[l1.index(y)])
# Original version was a simple for loop incrementing counts. Refactored to a generic function using list comprehension. def main(filepath): depths = [int(x) for x in open(filepath,'r').read().split('\n')] increases = lambda x,y: len([d for i,d in enumerate(x[1:]) if len(x[i+1:]) >= y and sum(x[i+1:i+y+1])...
def main(filepath): depths = [int(x) for x in open(filepath, 'r').read().split('\n')] increases = lambda x, y: len([d for (i, d) in enumerate(x[1:]) if len(x[i + 1:]) >= y and sum(x[i + 1:i + y + 1]) > sum(x[i:i + y])]) return (increases(depths, 1), increases(depths, 3)) print(main('01.txt'))
class Solution: def minRemoveToMakeValid(self, s: str) -> str: stack, indicesToRemove, result = [], set(), [] for i, c in enumerate(s): if c not in ['(', ')']: continue if c == '(': stack.append(i) elif not stack: in...
class Solution: def min_remove_to_make_valid(self, s: str) -> str: (stack, indices_to_remove, result) = ([], set(), []) for (i, c) in enumerate(s): if c not in ['(', ')']: continue if c == '(': stack.append(i) elif not stack: ...
MFCSAM = {'children': 3, 'cats': 7, 'samoyeds': 2, 'pomeranians': 3, 'akitas': 0, 'vizslas': 0, 'goldfish': 5, 'trees': 3, 'cars': 2, 'perfumes': 1} GREATER = ('cats', 'trees') FEWER = ('pomeranians', 'goldfish') sues = [] for row in open('input').read().splitlines(): sue_properties = {} for info in ...
mfcsam = {'children': 3, 'cats': 7, 'samoyeds': 2, 'pomeranians': 3, 'akitas': 0, 'vizslas': 0, 'goldfish': 5, 'trees': 3, 'cars': 2, 'perfumes': 1} greater = ('cats', 'trees') fewer = ('pomeranians', 'goldfish') sues = [] for row in open('input').read().splitlines(): sue_properties = {} for info in row.split('...
class Solution: def minDistance(self, word1: str, word2: str) -> int: dp = [ [0] * (len(word2)+1) for _ in range(len(word1)+1) ] for k in range(1, len(word2)+1): dp[0][k] = k for k in range(1, len(word1)+1): dp[k][0] = k for p in range(1, len(word1)+1): ...
class Solution: def min_distance(self, word1: str, word2: str) -> int: dp = [[0] * (len(word2) + 1) for _ in range(len(word1) + 1)] for k in range(1, len(word2) + 1): dp[0][k] = k for k in range(1, len(word1) + 1): dp[k][0] = k for p in range(1, len(word1) + ...
def sample(a: int, b: float, c: str) -> str: """ This is a sample :param a: this is a with two lines :param b: this is b :param c: this is c :return: this is a string conatining that """ pass
def sample(a: int, b: float, c: str) -> str: """ This is a sample :param a: this is a with two lines :param b: this is b :param c: this is c :return: this is a string conatining that """ pass
class Runner: def __init__(self, graph): self.graph = graph self.cache = {} def findValues(self, inputs): self.cache = {} for inputIndex in range(len(inputs)): self.cache[(inputIndex + 1, 0)] = inputs[inputIndex] if not self.__calculateValues(self.graph.nod...
class Runner: def __init__(self, graph): self.graph = graph self.cache = {} def find_values(self, inputs): self.cache = {} for input_index in range(len(inputs)): self.cache[inputIndex + 1, 0] = inputs[inputIndex] if not self.__calculateValues(self.graph.node...
# Copyright (c) Moshe Zadka # See LICENSE for details. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.napoleon', ] master_doc = 'index' project = 'Symplectic' copyright = '2017, Moshe Zadka' author = 'Moshe Zadka' version = '17.10' release = '17.10'
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.napoleon'] master_doc = 'index' project = 'Symplectic' copyright = '2017, Moshe Zadka' author = 'Moshe Zadka' version = '17.10' release = '17.10'
''' Created on 20 Jul 2015 @author: njohn ''' if __name__ == '__main__': pass
""" Created on 20 Jul 2015 @author: njohn """ if __name__ == '__main__': pass
# coding:utf-8 class Error(Exception): def __str__(self): return self.message class SessionExpiredError(Error): def __init__(self, message="Session has expired."): super(SessionExpiredError, self).__init__() self.message = message class SessionInvalidError(Error): def __init__(...
class Error(Exception): def __str__(self): return self.message class Sessionexpirederror(Error): def __init__(self, message='Session has expired.'): super(SessionExpiredError, self).__init__() self.message = message class Sessioninvaliderror(Error): def __init__(self, message='S...
# 1. Complete the function by filling in the missing parts. The color_translator # function receives the name of a color, then prints its hexadecimal value. # Currently, it only supports the three addictive primary colors (red, green, # blue), so it returns "unknown" for all other colors. def color_translator...
def color_translator(color): if color == 'red': hex_color = '#ff0000' elif color == 'green': hex_color = '#00ff00' elif color == 'blue': hex_color = '#0000ff' else: hex_color = 'unknown' return hex_color print(color_translator('blue')) print(color_translator('yellow')...
# Joshua Nelson Gomes (Joshua) # CIS 41A Spring 2020 # Take-Home Assignment I class Square: def __init__(self, side): self.side = side def getArea(self): return self.side * self.side class Cube(Square): def __init__(self, side): Square.__init__(self, side) def getVolume(self): return self.side * self.si...
class Square: def __init__(self, side): self.side = side def get_area(self): return self.side * self.side class Cube(Square): def __init__(self, side): Square.__init__(self, side) def get_volume(self): return self.side * self.side * self.side def calc_total(price, t...
# The subroutine inserts the vector passed as the secondargument into row j of the matrix. # It also inserts this vector into column j of the matrix. # Insertion involves copying the vector into the corresponding row and column. # If the value of j is out of range, the subroutine returns -1 and does not perform any ins...
def exercise(matrix, vector, N, j): if j < 0 or j > N: raise exception('j should be greater than 0 and smaller than N') i = 0 while i < len(matrix): element = vector[i] matrix[j][i] = element matrix[i][j] = element i += 1 for row in matrix: print(row) if _...
class HooksIter: def __init__(self, items=None): self.hooks = {} if items: for item in items: self.hooks[item] = item.hooks def __iter__(self): for hooks in self.hooks.values(): for event in hooks: for hook in event: ...
class Hooksiter: def __init__(self, items=None): self.hooks = {} if items: for item in items: self.hooks[item] = item.hooks def __iter__(self): for hooks in self.hooks.values(): for event in hooks: for hook in event: ...
# # Copyright (C) 2010-2017 Samuel Abels # The MIT License (MIT) # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy,...
""" Formatting logs into human readable reports. """ def _underline(text, line='-'): return [text, line * len(text)] def status(logger): """ Creates a one-line summary on the actions that were logged by the given Logger. :type logger: Logger :param logger: The logger that recorded what happe...
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2019, Micah Hunsberger (@mhunsber) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) DOCUMENTATION = r''' --- module: win_file_compression short_description: Alters the compression of files and directories on NTFS pa...
documentation = "\n---\nmodule: win_file_compression\nshort_description: Alters the compression of files and directories on NTFS partitions.\ndescription:\n - This module sets the compressed attribute for files and directories on a filesystem that supports it like NTFS.\n - NTFS compression can be used to save disk s...
class PopulationIsNotEvaluatedException(RuntimeError): pass class StopEvolution(Exception): pass
class Populationisnotevaluatedexception(RuntimeError): pass class Stopevolution(Exception): pass
class Rule: """Represents a single production rule of a grammar. Rules are usually written using some sort of BNF-like notation, for example, 'list ::= list item' would be a valid rule. A rule always has a single non-terminal symbol on the left and a list (possibly empty) of arbitrary symbols o...
class Rule: """Represents a single production rule of a grammar. Rules are usually written using some sort of BNF-like notation, for example, 'list ::= list item' would be a valid rule. A rule always has a single non-terminal symbol on the left and a list (possibly empty) of arbitrary symbols o...
#121 # Time: O(n) # Space: O(1) # Say you have an array for which the ith element is # the price of a given stock on day i. # If you were only permitted to complete at most one transaction # (ie, buy one and sell one share of the stock), # design an algorithm to find the maximum profit. # # Example 1: # Input: [...
class Arraysol: def best_time_sell_buy_i(self, prices): (min_price, max_profit) = (float('Inf'), 0) for price in prices: min_price = min(min_price, price) max_profit = max(max_profit, price - min_price) return max_profit
def partition(nums, low, high): pivot = nums[(low + high) // 2] i = low - 1 j = high + 1 while True: i += 1 while nums[i] < pivot: i += 1 j -= 1 while nums[j] > pivot: j -= 1 if i >= j: return j nums[i], nums[j] = nums...
def partition(nums, low, high): pivot = nums[(low + high) // 2] i = low - 1 j = high + 1 while True: i += 1 while nums[i] < pivot: i += 1 j -= 1 while nums[j] > pivot: j -= 1 if i >= j: return j (nums[i], nums[j]) = (num...
h, w = map(int, input().split()) ans = 0 if h == 1 or w == 1: ans = 1 else: if w % 2 == 0: ans += (w//2)*h else: if h % 2 == 0: ans += (h//2)*(w//2*2+1) else: ans += (h//2)*(w//2*2+1)+(w//2+1) print(max(1, ans))
(h, w) = map(int, input().split()) ans = 0 if h == 1 or w == 1: ans = 1 elif w % 2 == 0: ans += w // 2 * h elif h % 2 == 0: ans += h // 2 * (w // 2 * 2 + 1) else: ans += h // 2 * (w // 2 * 2 + 1) + (w // 2 + 1) print(max(1, ans))
class User: """ Contains additional user data """ def __init__(self, sid: str, nickname: str): self._sid = sid self._nickname = nickname self._rooms = [] def get_sid(self) -> str: """ Returns the user's unique SID """ return self._sid @property def nickname(...
class User: """ Contains additional user data """ def __init__(self, sid: str, nickname: str): self._sid = sid self._nickname = nickname self._rooms = [] def get_sid(self) -> str: """ Returns the user's unique SID """ return self._sid @property def nickname...
### test examples for the rast_client.py file def test_somefunction(): pass
def test_somefunction(): pass
include("common.py") beta_decarboxylation = ruleGMLString("""rule [ ruleID "Beta Decarboxylation" labelType "term" left [ edge [ source 4 target 7 label "-" ] edge [ source 7 target 9 label "-" ] edge [ source 9 target 10 label "-" ] ] context [ node [ id 1 label "*" ] edge [ source 1 target 2 label "-"...
include('common.py') beta_decarboxylation = rule_gml_string('rule [\n\truleID "Beta Decarboxylation"\n\tlabelType "term"\n\tleft [\n\t\tedge [ source 4 target 7 label "-" ]\n\t\tedge [ source 7 target 9 label "-" ]\n\t\tedge [ source 9 target 10 label "-" ]\n\t]\n\tcontext [\n\t\tnode [ id 1 label "*" ]\n\t\tedge [ sou...
def main(): #with open(filename, (open for reading 'r', #writing 'w' or reading and writing 'rw')) word = input("What's your word? Enter it here: ") print("Scrabble score: " + (str)(scrabble_value(word))); #everything past here the file is closed # scrabble_value("potato") #three options: # 1) write a program ...
def main(): word = input("What's your word? Enter it here: ") print('Scrabble score: ' + str(scrabble_value(word))) def scrabble_value(word): score = 0 scrabble_dict = {'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 1...
ALL_DRIVERS = ['chromedriver', 'geckodriver'] DEFAULT_DRIVERS = ['chromedriver', 'geckodriver'] CHROMEDRIVER_STORAGE_URL = 'https://chromedriver.storage.googleapis.com' CHROMEDRIVER_LATEST_FILE = 'https://chromedriver.storage.googleapis.com/LATEST_RELEASE' GECKODRIVER_LASTEST_URL = 'https://api.github.com/repos/mozi...
all_drivers = ['chromedriver', 'geckodriver'] default_drivers = ['chromedriver', 'geckodriver'] chromedriver_storage_url = 'https://chromedriver.storage.googleapis.com' chromedriver_latest_file = 'https://chromedriver.storage.googleapis.com/LATEST_RELEASE' geckodriver_lastest_url = 'https://api.github.com/repos/mozilla...
"""State testing. TODO: Create more comprehensive testing """ # from cadcad.space import Space def test_class_creation() -> None: """Test class creation."""
"""State testing. TODO: Create more comprehensive testing """ def test_class_creation() -> None: """Test class creation."""
#!/usr/local/bin/python3 """This program takes a user's input on Name and Breed of a dog, then prints a list of the dogs.""" class Dog: def __init__(self,name,breed): self.name = name self.breed = breed def __str__(self): return "{0}:{1}".format(self.name, self.breed) ...
"""This program takes a user's input on Name and Breed of a dog, then prints a list of the dogs.""" class Dog: def __init__(self, name, breed): self.name = name self.breed = breed def __str__(self): return '{0}:{1}'.format(self.name, self.breed) if __name__ == '__main__': dogs = [...
class restaurant: def __init__(self,restaurant_name,cuisine_type): """initialize restaurant name and cusine""" self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type self.number_served = 0 #setting default value for an attribute def describe_restaurant(self): print(se...
class Restaurant: def __init__(self, restaurant_name, cuisine_type): """initialize restaurant name and cusine""" self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type self.number_served = 0 def describe_restaurant(self): print(self.restaurant_name.titl...
# Ordering # Create a program that allows entry of 10 numbers and then sorts them into ascending or descending order, based on user input. def main(): isNumber = input('Do you want to enter numbers or a string: [N/S] ').upper() if isNumber == 'N': nums = [int(input('Enter a number: ')) for _ in range(10)] ...
def main(): is_number = input('Do you want to enter numbers or a string: [N/S] ').upper() if isNumber == 'N': nums = [int(input('Enter a number: ')) for _ in range(10)] order = input('Do you want to order in ascending or descending order [A/D]: ').upper() if order == 'A': num...
# This problem was recently asked by Twitter: # Implement a class for a stack that supports all the regular functions (push, pop) and # an additional function of max() which returns the maximum element in the stack (return None if the stack is empty) # Each method should run in constant time. class MaxStack: def ...
class Maxstack: def __init__(self): self.items = [] def push(self, val): self.items.append(val) def pop(self): return self.items.pop() def max(self): max_n = 0 if len(self.items) == 0: return None for i in self.items: if i >= ma...
coins = { "Khan's Concentrated Magic": 80000, "Luminous Cobalt Ingot": 800, "Bright Reef Piece": 140, "Great Ocean Dark Iron": 160, "Cobalt Ingot": 150, "Brilliant Rock Salt Ingot": 1600, "Seaweed Stalk": 600, "Enhanced Island Tree Coated Plywood": 80, "Pure Pearl Crystal": 550, "Cox Pirates' Artifact (Parley...
coins = {"Khan's Concentrated Magic": 80000, 'Luminous Cobalt Ingot': 800, 'Bright Reef Piece': 140, 'Great Ocean Dark Iron': 160, 'Cobalt Ingot': 150, 'Brilliant Rock Salt Ingot': 1600, 'Seaweed Stalk': 600, 'Enhanced Island Tree Coated Plywood': 80, 'Pure Pearl Crystal': 550, "Cox Pirates' Artifact (Parley Beginner)"...
class Command: def execute(self): raise NotImplementedError
class Command: def execute(self): raise NotImplementedError
# Use a Q to keep recent timestamps. Whenever ping is called, add t to Q and remove all the expired ones. Return len(Q) class RecentCounter: def __init__(self): self.Q = [] def ping(self, t: int) -> int: self.Q.append(t) while self.Q[0]<t-3000: self.Q.pop(0) ...
class Recentcounter: def __init__(self): self.Q = [] def ping(self, t: int) -> int: self.Q.append(t) while self.Q[0] < t - 3000: self.Q.pop(0) return len(self.Q)
class Html_Maker: @classmethod def read_text_file(cls, path: str): ret = '' with open(path, 'r') as f: while True: line = f.readline() if not line: break line = line.replace( '\t', '<span style="...
class Html_Maker: @classmethod def read_text_file(cls, path: str): ret = '' with open(path, 'r') as f: while True: line = f.readline() if not line: break line = line.replace('\t', '<span style="white-space:pre">\t</...
a = list(range(10)) print(a) b = list("Pablo Fajardo") print(b) empty = [] print(empty) nine = [0,1,2,3,4,5,6,7,8,9] print(nine) mixed = ['a',1,'b',2,'c',3,"Pablo",empty,True] print(mixed) #Add a single item to a list mixed.append("Fajardo") print(mixed) #Add item with index mixed.insert(2,"PALABRA") print(mixed...
a = list(range(10)) print(a) b = list('Pablo Fajardo') print(b) empty = [] print(empty) nine = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(nine) mixed = ['a', 1, 'b', 2, 'c', 3, 'Pablo', empty, True] print(mixed) mixed.append('Fajardo') print(mixed) mixed.insert(2, 'PALABRA') print(mixed) pies = ['cherry', 'cream', 'apple'] p...
# This is a useful data structure for implementing # a counter that counts the time. class DFSTimeCounter: def __init__(self): self.count = 0 def reset(self): self.count = 0 def increment(self): self.count = self.count + 1 def get(self): return self.count class Undir...
class Dfstimecounter: def __init__(self): self.count = 0 def reset(self): self.count = 0 def increment(self): self.count = self.count + 1 def get(self): return self.count class Undirectedgraph: def __init__(self, n): self.n = n self.adj_list = [s...