content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class Pattern(object): """ [summary] """ @staticmethod def default() -> str: """[summary] Returns: pattern (str): [{level}][{datetime}] - {transaction} - {project_name}.{class_name}.{function_name} - _message: traceback """ _message = "{message}" ...
class Pattern(object): """ [summary] """ @staticmethod def default() -> str: """[summary] Returns: pattern (str): [{level}][{datetime}] - {transaction} - {project_name}.{class_name}.{function_name} - _message: traceback """ _message = '{message}' ...
_first_index_in_every_row_list = list() def _build_first_index_in_every_row_list(): global _first_index_in_every_row_list _first_index_in_every_row_list.clear() _first_index_in_every_row_list.append(0) for delta in range(199, 1, -1): _first_index_in_every_row_list.append(_first_index_in_every_...
_first_index_in_every_row_list = list() def _build_first_index_in_every_row_list(): global _first_index_in_every_row_list _first_index_in_every_row_list.clear() _first_index_in_every_row_list.append(0) for delta in range(199, 1, -1): _first_index_in_every_row_list.append(_first_index_in_every_r...
# Function for finding if it possible # to obtain sorted array or not def fun(arr, n, k): v = [] # Iterate over all elements until K for i in range(k): # Store elements as multiples of K for j in range(i, n, k): v.append(arr[j]); # Sort the elements ...
def fun(arr, n, k): v = [] for i in range(k): for j in range(i, n, k): v.append(arr[j]) v.sort() x = 0 for j in range(i, n, k): arr[j] = v[x] x += 1 v = [] for i in range(n - 1): if arr[i] > arr[i + 1]: return Fa...
# -*- coding: utf-8 -*- """ Created on Tue Feb 19 20:59:13 2019 @author: sudar """ class url_feeder(object): def __init__(self, section): """initialize the feeder""" self.section = section def feeder(self): """We going to get the URL through each section over-view ...
""" Created on Tue Feb 19 20:59:13 2019 @author: sudar """ class Url_Feeder(object): def __init__(self, section): """initialize the feeder""" self.section = section def feeder(self): """We going to get the URL through each section over-view company information ...
# day_3/classes.py """ Classes are a way to encapsulate code. It is a way of keeping functions and data that represent something together and is a core concept to understand for object oreinted programing. """ class Person: def __init__(self, name: str, age: int) -> None: """ Initializes the pers...
""" Classes are a way to encapsulate code. It is a way of keeping functions and data that represent something together and is a core concept to understand for object oreinted programing. """ class Person: def __init__(self, name: str, age: int) -> None: """ Initializes the person class requires a ...
class Pessoa: menbros_superiores = 2 menbro_inferiores=2 def __init__(self,*familia,name=None,idade=17): self.name= name self.familia= list(familia) self.idade= idade def comprimentar(self): return 'hello my code' def despedisir(self): return 'diz tcha...
class Pessoa: menbros_superiores = 2 menbro_inferiores = 2 def __init__(self, *familia, name=None, idade=17): self.name = name self.familia = list(familia) self.idade = idade def comprimentar(self): return 'hello my code' def despedisir(self): return 'diz t...
# Given a non-negative number represented as an array of digits, # plus one to the number. # The digits are stored such that the most significant # digit is at the head of the list. def plusOne(digits): """ :type digits: List[int] :rtype: List[int] """ digits[-1] = digits[-1] + 1 res = [] ...
def plus_one(digits): """ :type digits: List[int] :rtype: List[int] """ digits[-1] = digits[-1] + 1 res = [] ten = 0 i = len(digits) - 1 while i >= 0 or ten == 1: sum = 0 if i >= 0: sum += digits[i] if ten: sum += 1 res.append(s...
# coding: utf-8 def is_bool(var): return isinstance(var, bool) if __name__ == '__main__': a = False b = 0 print(is_bool(a)) print(is_bool(b))
def is_bool(var): return isinstance(var, bool) if __name__ == '__main__': a = False b = 0 print(is_bool(a)) print(is_bool(b))
class Conta: def __init__(self, numero, nome, saldo=0): self._numero = numero self._nome = nome self._saldo = saldo def atualiza(self, taxa): self._saldo += self._saldo * taxa def deposita(self, valor): self._saldo += valor - 0.10 class ContaCorrente(Conta): ...
class Conta: def __init__(self, numero, nome, saldo=0): self._numero = numero self._nome = nome self._saldo = saldo def atualiza(self, taxa): self._saldo += self._saldo * taxa def deposita(self, valor): self._saldo += valor - 0.1 class Contacorrente(Conta): d...
# -*- coding: utf-8 -*- # Coded by Sungwook Kim # 2020-12-13 # IDE: Jupyter Notebook def Fact(a): res = 1 for i in range(a): res = res * (i + 1) return res T = int(input()) for i in range(T): r, n = map(int, input().split()) a = Fact(n) b = Fact(r) c = Fact(n-r) print(...
def fact(a): res = 1 for i in range(a): res = res * (i + 1) return res t = int(input()) for i in range(T): (r, n) = map(int, input().split()) a = fact(n) b = fact(r) c = fact(n - r) print(int(a / (c * b)))
# The base class for application-specific states. class SarifState(object): def __init__(self): self.parser = None self.ppass = 1 # Taking the easy way out. # We need something in case a descendent wants to trigger # on change to ppass. def set_ppass(self, ppass): self.ppas...
class Sarifstate(object): def __init__(self): self.parser = None self.ppass = 1 def set_ppass(self, ppass): self.ppass = ppass def get_ppass(self): return self.ppass def set_parser(self, parser): self.parser = parser def get_parser(self): return s...
# store the input from the user into age age = input("How old are you? ") # store the input from the user into height height = input(f"You're {age}? Nice. How tall are you? ") # store the input from the user into weight weight = input("How much do you weigh? ") # print the f-string with the age, height and weight prin...
age = input('How old are you? ') height = input(f"You're {age}? Nice. How tall are you? ") weight = input('How much do you weigh? ') print(f"So you're {age} old. {height} tall and {weight} heavy.")
def loss_layer(self, predicts, labels, scope='loss_layer'): with tf.variable_scope(scope): predict_classes = tf.reshape(predicts[:, :self.boundary1], [self.batch_size, self.cell_size, self.cell_size, self.num_class]) predict_scales = tf.reshape(predicts[:, self.b...
def loss_layer(self, predicts, labels, scope='loss_layer'): with tf.variable_scope(scope): predict_classes = tf.reshape(predicts[:, :self.boundary1], [self.batch_size, self.cell_size, self.cell_size, self.num_class]) predict_scales = tf.reshape(predicts[:, self.boundary1:self.boundary2], [self.batch...
# -*-- coding: utf-8 -* def discretize(self, Npoint=-1): """Returns the discretize version of the SurfRing Parameters ---------- self: SurfRing A SurfRing object Npoint : int Number of point on each line (Default value = -1 => use the line default discretization) Returns --...
def discretize(self, Npoint=-1): """Returns the discretize version of the SurfRing Parameters ---------- self: SurfRing A SurfRing object Npoint : int Number of point on each line (Default value = -1 => use the line default discretization) Returns ------- point_list : l...
# AKSHITH K # BUBBLE SORT IMPLEMENTED IN PYTHON RECURSIVELY. def bubblesort(arr, n): # checking if the array does not need to be sorted and has a length of 1. if n <= 1: return # creating a for-loop to iterate for the elements in the array. for i in range(0, n - 1): # c...
def bubblesort(arr, n): if n <= 1: return for i in range(0, n - 1): if arr[i] > arr[i + 1]: (arr[i], arr[i + 1]) = (arr[i + 1], arr[i]) return bubblesort(arr, n - 1) arr = [4, 9, 1, 3, 0, 2, 6, 8, 5, 7] n = len(arr) bubblesort(arr, n) print(arr)
## Problem 10.2 # write a program to read through the mbox-short.txt # and figure out the distribution by hour of the day for each of the messages. file_name = input("Enter file:") file_handle = open(file_name) hour_list = list() for line in file_handle: # pull the hour out from the 'From ' line # From stephe...
file_name = input('Enter file:') file_handle = open(file_name) hour_list = list() for line in file_handle: if line.startswith('From'): line_list = line.split() if len(line_list) > 2: hour = line_list[5][:2] hour_list.append(hour) hour_dict = dict() for key in hour_list: h...
# Copyright 2006 James Tauber and contributors # Copyright (C) 2009 Luke Kenneth Casson Leighton <lkcl@lkcl.net> # Copyright (C) 2010 Serge Tarkovski <serge.tarkovski@gmail.com> # Copyright (C) 2010 Rich Newpol (IE override) <rich.newpol@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # y...
def show(mousetarget, **kwargs): global mousecapturer target_element = mousetarget.getElement() if hasattr(target_element, 'setCapture'): mousecapturer = target_element DOM.setCapture(target_element) def hide(): global mousecapturer if hasattr(mousecapturer, 'releaseCapture'): ...
# WAP to show the use of if..elif..else season= input("Enter season : ") print(season) if season == 'spring': print('plant the garden!') elif season == 'summer': print('water the garden!') elif season == 'fall': print('harvest the garden!') elif season == 'winter': print('stay indoors!') e...
season = input('Enter season : ') print(season) if season == 'spring': print('plant the garden!') elif season == 'summer': print('water the garden!') elif season == 'fall': print('harvest the garden!') elif season == 'winter': print('stay indoors!') else: print('unrecognized season')
# # PySNMP MIB module HH3C-L2TP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-L2TP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:14:47 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_range_constraint, constraints_union, single_value_constraint, value_size_constraint) ...
kuukiondo = 70 shitsudo = 100 if kuukiondo >= 100: print("A") elif kuukiondo >= 92 and shitsudo > 75: print("B") elif kuukiondo > 88 and shitsudo >= 85: print("C") elif kuukiondo == 75 and shitsudo <= 65: print("D") else: print("E")
kuukiondo = 70 shitsudo = 100 if kuukiondo >= 100: print('A') elif kuukiondo >= 92 and shitsudo > 75: print('B') elif kuukiondo > 88 and shitsudo >= 85: print('C') elif kuukiondo == 75 and shitsudo <= 65: print('D') else: print('E')
class Solution1: def maxSubArray(self, nums: List[int]) -> int: total_max, total = -1e10, 0 for i in range( len(nums) ): if total > 0: total += nums[i] else: total = nums[i] if total > total_max: t...
class Solution1: def max_sub_array(self, nums: List[int]) -> int: (total_max, total) = (-10000000000.0, 0) for i in range(len(nums)): if total > 0: total += nums[i] else: total = nums[i] if total > total_max: total_...
""" ID: tony_hu1 PROG: sort3 LANG: PYTHON3 """ def check_swap(current_num): global unsorted global sorted global num global steps global area for i in range(num): if sorted[i] > current_num: return if sorted[i] == current_num: if unsorted[i] == current_nu...
""" ID: tony_hu1 PROG: sort3 LANG: PYTHON3 """ def check_swap(current_num): global unsorted global sorted global num global steps global area for i in range(num): if sorted[i] > current_num: return if sorted[i] == current_num: if unsorted[i] == current_nu...
################################################################################ # # # ____ _ # # | _ \ ___ __| |_ __ _ _ _ __ ___ ...
class Metadata_Dictionary_Type: key_flags: int = 0 key_health: int = 1 key_variant: int = 2 key_color: int = 3 key_nametag: int = 4 key_owner_eid: int = 5 key_target_eid: int = 6 key_air: int = 7 key_potion_color: int = 8 key_potion_ambient: int = 9 key_jump_duration: int = 1...
class Base(object): def __secret(self): print("don't tell") def public(self): self.__secret() class Derived(Base): def __secret(self): print("never ever") if __name__ == "__main__": print("Base class members:", dir(Base)) print("Derived class members:", dir(Derived)) ...
class Base(object): def __secret(self): print("don't tell") def public(self): self.__secret() class Derived(Base): def __secret(self): print('never ever') if __name__ == '__main__': print('Base class members:', dir(Base)) print('Derived class members:', dir(Derived)) ...
# Basic script to find primer candidates # Hits are 20bp in length, with 50-55% GC content, GC clamps in the 3' end, and no more than 3xGC at the clamp # Paste the target exon sequences from a FASTA sequence with no white spaces # Exon 1 is where forward primer candidates will be identified exon1 = "GCAGTGTCACTAG...
exon1 = 'GCAGTGTCACTAGGCCGGCTGGGGGCCCTGGGTACGCTGTAGACCAGACCGCGACAGGCCAGAACACGGGCGGCGGCTTCGGGCCGGGAGACCCGCGCAGCCCTCGGGGCATCTCAGTGCCTCACTCCCCACCCCCTCCCCCGGGTCGGGGGAGGCGGCGCGTCCGGCGGAGGGTTGAGGGGAGCGGGGCAGGCCTGGAGCGCCATGAGCAGCCCGGATGCGGGATACGCCAGTGACGACCAGAGCCAGACCCAGAGCGCGCTGCCCGCGGTGATGGCCGGGCTGGGCCCCTGCCCCTGGGCCGAGTCGCT...
# Objective # Today we're discussing scope. Check out the Tutorial tab for learning materials and an instructional video! # The absolute difference between two integers, # and , is written as . The maximum absolute difference between two integers in a set of positive integers, , is the largest absolute difference betw...
class Difference: def __init__(self, a): self.__elements = a def compute_difference(self): diff_array = [] for i in range(len(self.__elements) - 1): for j in range(i + 1, len(self.__elements)): diff = abs(self.__elements[j] - self.__elements[i]) ...
#another way of doing recursive palindrome def is_palindrome(s): ln = len(s) if s != '': if s[ln-1] == s[0]: return True and is_palindrome(s[1:ln-1]) return False return True assert is_palindrome('abab') == False assert is_palindrome('abba') == True assert is_palindrome('madam')...
def is_palindrome(s): ln = len(s) if s != '': if s[ln - 1] == s[0]: return True and is_palindrome(s[1:ln - 1]) return False return True assert is_palindrome('abab') == False assert is_palindrome('abba') == True assert is_palindrome('madam') == True assert is_palindrome('madame') ...
class Profile(object): @property def name(self): return self.__name @property def trustRoleArn(self): return self.__trustRoleArn @property def sourceProfile(self): return self.__sourceProfile @property def credentials(self): return self.__credentials ...
class Profile(object): @property def name(self): return self.__name @property def trust_role_arn(self): return self.__trustRoleArn @property def source_profile(self): return self.__sourceProfile @property def credentials(self): return self.__credential...
# f_name = 'ex1.txt' f_name = 'input.txt' all_ingredients = set() possible_allergens = dict() recipes = list() with open(f_name, 'r') as f: for i, line in enumerate(f.readlines()): # get a list of the ingredients and record the food recipe as a set of the # ingredients (recipes = [{'aaa', 'bbb'}, ...
f_name = 'input.txt' all_ingredients = set() possible_allergens = dict() recipes = list() with open(f_name, 'r') as f: for (i, line) in enumerate(f.readlines()): ingredients = line.split(' (')[0].strip().split() recipes.append(set(ingredients)) all_ingredients |= set(ingredients) all...
S = 0 T = 0 L = [] for i in range(11): L.append(list(map(int,input().split()))) L.sort(key = lambda t:(t[0],t[1])) for i in L: T+=i[0] S += T + i[1]*20 print(S)
s = 0 t = 0 l = [] for i in range(11): L.append(list(map(int, input().split()))) L.sort(key=lambda t: (t[0], t[1])) for i in L: t += i[0] s += T + i[1] * 20 print(S)
# Evaluacion de expresiones print(3+5) print(3+2*5) print((3+2)*5) print(2**3) print(4**0.5) print(10%3) print('abra' + 'cadabra') print('ja'*3) print(1+2) print(1.0+2.0) print(1.0+2) print(1/2) print(1//2) print(1.0//2.0) print('En el curso hay ' + str(30) + ' alumnos') print('100'+'1') print(int('100') +1) # Variabl...
print(3 + 5) print(3 + 2 * 5) print((3 + 2) * 5) print(2 ** 3) print(4 ** 0.5) print(10 % 3) print('abra' + 'cadabra') print('ja' * 3) print(1 + 2) print(1.0 + 2.0) print(1.0 + 2) print(1 / 2) print(1 // 2) print(1.0 // 2.0) print('En el curso hay ' + str(30) + ' alumnos') print('100' + '1') print(int('100') + 1) a = 8...
class GameStats(): """TRACK STATISTICS FOR FROM ANOTHER WORLD""" def __init__(self, ai_settings): """INITIALIZE STATISTICS""" self.ai_settings = ai_settings self.reset_stats() # START GAME IN AN INACTIVE STATE self.game_active = False def reset_stats(self): ...
class Gamestats: """TRACK STATISTICS FOR FROM ANOTHER WORLD""" def __init__(self, ai_settings): """INITIALIZE STATISTICS""" self.ai_settings = ai_settings self.reset_stats() self.game_active = False def reset_stats(self): """INITIALIZE STATISTICS THAT CAN CHANGE DUR...
a, b, c, d = 1, 2, 3, 4 print(a, b, c, d) a, b, c, d = d, c, b, a print(a, b, c, d)
(a, b, c, d) = (1, 2, 3, 4) print(a, b, c, d) (a, b, c, d) = (d, c, b, a) print(a, b, c, d)
def test_metadata(system_config) -> None: assert system_config.provider_code == "system" assert system_config._prefix == "TEST" def test_prefixize(system_config) -> None: assert system_config.prefixize("key1") == "TEST_KEY1" assert system_config.unprefixize("TEST_KEY1") == "key1" def test_get_variab...
def test_metadata(system_config) -> None: assert system_config.provider_code == 'system' assert system_config._prefix == 'TEST' def test_prefixize(system_config) -> None: assert system_config.prefixize('key1') == 'TEST_KEY1' assert system_config.unprefixize('TEST_KEY1') == 'key1' def test_get_variable...
def read_matrix(): rows_count = int(input()) matrix = [] for _ in range(rows_count): row = [int(r) for r in input().split(' ')] matrix.append(row) return matrix def get_primary_diagonal_sum(matrix): p_d_sum = 0 for i in range(len(matrix)): p_d_sum += matrix[i][i] ...
def read_matrix(): rows_count = int(input()) matrix = [] for _ in range(rows_count): row = [int(r) for r in input().split(' ')] matrix.append(row) return matrix def get_primary_diagonal_sum(matrix): p_d_sum = 0 for i in range(len(matrix)): p_d_sum += matrix[i][i] ret...
''' 1. The algorithm is a substitution cipher. It shifts each letter by a certain key. 2. Python Library Functions used : a) ord() : Converts a character to its equivalent ASCII value. b) chr() : Converts an ASCII value to its equivalent character. 3. What are 65 and 97? a) 65 is the ASCII value of 'A'. ...
""" 1. The algorithm is a substitution cipher. It shifts each letter by a certain key. 2. Python Library Functions used : a) ord() : Converts a character to its equivalent ASCII value. b) chr() : Converts an ASCII value to its equivalent character. 3. What are 65 and 97? a) 65 is the ASCII value of 'A'. ...
#!/usr/bin/env python3 #!/usr/bin/python3 dict1 = { 'a': 1, 'b': 2, } dict2 = { 'a': 0, 'b': 2, } if dict1 == dict2: print("FAIL") else: print("PASS") dict1 = { 'a': { 'c': 'bake' }, 'b': 2, } dict2 = { 'a': { 'c': 'shake' }, 'b': 2, } if dict1 == di...
dict1 = {'a': 1, 'b': 2} dict2 = {'a': 0, 'b': 2} if dict1 == dict2: print('FAIL') else: print('PASS') dict1 = {'a': {'c': 'bake'}, 'b': 2} dict2 = {'a': {'c': 'shake'}, 'b': 2} if dict1 == dict2: print('FAIL') else: print('PASS') dict1 = {'a': {'c': [0, 1]}, 'b': 2} dict2 = {'a': {'c': [0, 2]}, 'b': 2}...
## Grasshopper - Summation ## 8 kyu ## https://www.codewars.com/kata/55d24f55d7dd296eb9000030 def summation(num): return sum([i for i in range(num+1)])
def summation(num): return sum([i for i in range(num + 1)])
LEFT_ALIGNED = 0 RIGHT_ALIGNED = 1 CENTER_ALIGNED = 2 JUSTIFIED_ALIGNED = 3 NATURAL_ALIGNED = 4
left_aligned = 0 right_aligned = 1 center_aligned = 2 justified_aligned = 3 natural_aligned = 4
score_1 = float(input('Type your 1st score: ')) score_2 = float(input('Type your 2nd score: ')) average = (score_1 + score_2) / 2 print(f'Your average is {average}, therefore you...') print('Pass. Congrats.') if average > 6 \ else print('Fail. Study again, you\'ll get it. :)')
score_1 = float(input('Type your 1st score: ')) score_2 = float(input('Type your 2nd score: ')) average = (score_1 + score_2) / 2 print(f'Your average is {average}, therefore you...') print('Pass. Congrats.') if average > 6 else print("Fail. Study again, you'll get it. :)")
class NoDataError(Exception): def __init__(self, field, obj, module): message = "Missing field '" + field + "' in the object " + str(obj) + " needed in " + module super(NoDataError, self).__init__(message)
class Nodataerror(Exception): def __init__(self, field, obj, module): message = "Missing field '" + field + "' in the object " + str(obj) + ' needed in ' + module super(NoDataError, self).__init__(message)
""" Should specifically use: touchtechnology.common.backends.auth.UserSubclassBackend touchtechnology.common.backends.auth.EmailUserSubclassBackend """
""" Should specifically use: touchtechnology.common.backends.auth.UserSubclassBackend touchtechnology.common.backends.auth.EmailUserSubclassBackend """
""" ``mixin`` module. """ class ErrorsMixin(object): """Used primary by service layer to validate business rules. Requirements: - self.errors Example:: class MyService(ValidationMixin): def __init__(self, repository, errors, locale): # ... def authe...
""" ``mixin`` module. """ class Errorsmixin(object): """Used primary by service layer to validate business rules. Requirements: - self.errors Example:: class MyService(ValidationMixin): def __init__(self, repository, errors, locale): # ... def authen...
class Event(): def __init__(self, guild_id, event_type, target_id, target_name, actor, reason, timestamp, role_id=None, role_name=None, count=None, message_id=None): self.guild_id = guild_id self.event_type = event_type self.target_id = target_id self.target_name = target_name ...
class Event: def __init__(self, guild_id, event_type, target_id, target_name, actor, reason, timestamp, role_id=None, role_name=None, count=None, message_id=None): self.guild_id = guild_id self.event_type = event_type self.target_id = target_id self.target_name = target_name ...
nintendo_games = ['Zelda', 'Mario', 'Donkey Kong', 'Zelda'] nintendo_games.remove('Zelda') print(nintendo_games) if 'Wario' in nintendo_games: nintendo_games.remove('Wario')
nintendo_games = ['Zelda', 'Mario', 'Donkey Kong', 'Zelda'] nintendo_games.remove('Zelda') print(nintendo_games) if 'Wario' in nintendo_games: nintendo_games.remove('Wario')
class Test: def initialize(self): self.x = 42 t = Test() t.initialize() def calc(self, n): return self.x + n Test.calc = calc assert t.calc(4) == 46
class Test: def initialize(self): self.x = 42 t = test() t.initialize() def calc(self, n): return self.x + n Test.calc = calc assert t.calc(4) == 46
# Time: O(n) # Space: O(1) # # 123 # Say you have an array for which the ith element # is the price of a given stock on day i. # # Design an algorithm to find the maximum profit. # You may complete at most two transactions. # # Note: # You may not engage in multiple transactions at the same time # (ie, you must sell t...
try: xrange except NameError: xrange = range class Solution(object): def max_profit(self, prices): (hold1, hold2) = (float('-inf'), float('-inf')) (cash1, cash2) = (0, 0) for p in prices: hold1 = max(hold1, -p) cash1 = max(cash1, hold1 + p) hold2...
def firstDuplicateValue(array): for n in array: n = abs(n) if array[n - 1] < 0: return n array[n - 1] *= -1 return -1
def first_duplicate_value(array): for n in array: n = abs(n) if array[n - 1] < 0: return n array[n - 1] *= -1 return -1
#!/usr/bin/python # -*- coding: utf-8 -*- def read_gowalla_data(file_path): train_file = open(file_path, 'r') x_data = {} for i in open(file_path): line = train_file.readline() # line = line.strip('\n') if len(line) == 0: continue items = line.split("\t") ...
def read_gowalla_data(file_path): train_file = open(file_path, 'r') x_data = {} for i in open(file_path): line = train_file.readline() if len(line) == 0: continue items = line.split('\t') user_id = items[0] if len(user_id) == 0: continue ...
# Which environment frames do we need to keep during evaluation? # There is a set of active environments Values and frames in active environments consume memory # Memory that is used for other values and frames can be recycled # Active environments: # Environments for any functions calls currently being evaluated ...
def count_frames(f): def counted(*arg): counted.open_count += 1 if counted.max_count < counted.open_count: counted.max_count = counted.open_count result = f(*arg) counted.open_count -= 1 return result counted.open_count = 0 counted.max_count = 0 retur...
class Solution: def XXX(self, nums: List[int]) -> List[List[int]]: return [[nums[j] for j in range(len(nums)) if i&2**j] for i in range(2**len(nums))]
class Solution: def xxx(self, nums: List[int]) -> List[List[int]]: return [[nums[j] for j in range(len(nums)) if i & 2 ** j] for i in range(2 ** len(nums))]
def viralAdvertising(n): return if __name__ == '__main__': n = int(input()) viralAdvertising(n)
def viral_advertising(n): return if __name__ == '__main__': n = int(input()) viral_advertising(n)
# This is just a demo file print("Hello world") print("this is update to my previous code")
print('Hello world') print('this is update to my previous code')
n = int(input()) # n = 3 sum1 = 0 sum2 = 0 for i in range(1, n + 1): # print("i = ", i) if i % 2 == 0: sum1 += i else: sum2 += i if sum1 == 0: print(sum2) else: print(sum2 - sum1)
n = int(input()) sum1 = 0 sum2 = 0 for i in range(1, n + 1): if i % 2 == 0: sum1 += i else: sum2 += i if sum1 == 0: print(sum2) else: print(sum2 - sum1)
class Solution: # @return a tuple, (index1, index2) def twoSum(self, num, target): length = len(num) # use dict: value: index + 1 # since there is only one solution, the right value must not be duplicated dic = {} for i in xrange(0, length): val = num[i] ...
class Solution: def two_sum(self, num, target): length = len(num) dic = {} for i in xrange(0, length): val = num[i] if target - val in dic: return (dic[target - val], i + 1) dic[val] = i + 1
#Tree Size class Node: def __init__(self, data): self.data = data self.left = None self.right = None def sizeTree(node): if node is None: return 0 else: return (sizeTree(node.left) + 1 + sizeTree(node.right)) # Driver program to test above function root = Node(1) ro...
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def size_tree(node): if node is None: return 0 else: return size_tree(node.left) + 1 + size_tree(node.right) root = node(1) root.left = node(2) root.right = node(3) root.left.l...
''' One Away: There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away. Example: pale, ple -> true pales, pale -> true pale, bale -> true pale, bake -> false b...
""" One Away: There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away. Example: pale, ple -> true pales, pale -> true pale, bale -> true pale, bake -> false b...
max_n = 10**17 fibs = [ (1, 1), (2, 1), ] while fibs[-1][0] < max_n: fibs.append( (fibs[-1][0] + fibs[-2][0], fibs[-1][1] + fibs[-2][1]) ) print(fibs) counts = [ 1, 1 ] for i in range(2, len(fibs)): fib = fibs[i] counts.append(fib[1] + sum(counts[j] for j in range(i - 1))) ...
max_n = 10 ** 17 fibs = [(1, 1), (2, 1)] while fibs[-1][0] < max_n: fibs.append((fibs[-1][0] + fibs[-2][0], fibs[-1][1] + fibs[-2][1])) print(fibs) counts = [1, 1] for i in range(2, len(fibs)): fib = fibs[i] counts.append(fib[1] + sum((counts[j] for j in range(i - 1)))) print(counts) def count(n): smal...
class StateMachine: def __init__(self, initialState): self.currentState = initialState self.currentState.run() # Template method: def runAll(self, inputs): self.currentState = self.currentState.next_state(inputs) self.currentState.run()
class Statemachine: def __init__(self, initialState): self.currentState = initialState self.currentState.run() def run_all(self, inputs): self.currentState = self.currentState.next_state(inputs) self.currentState.run()
def palindrome(word : str) -> int: """ Given a string, calculates the amount of palindromes that exist within that string Parameters ---------- word : str String that may contain palindrome sub-strings Returns ------- int number of palindromes in string """ ...
def palindrome(word: str) -> int: """ Given a string, calculates the amount of palindromes that exist within that string Parameters ---------- word : str String that may contain palindrome sub-strings Returns ------- int number of palindromes in string """ word =...
numbers = [8, 6, 4, 1, 3, 7, 9, 5, 2] def pancake_sort(array): target_index = len(array)-1 while target_index > 0: max_value = array[target_index] max_index = target_index for number in range(0, target_index): if array[number] > max_value: max_value = array[number] max_index = num...
numbers = [8, 6, 4, 1, 3, 7, 9, 5, 2] def pancake_sort(array): target_index = len(array) - 1 while target_index > 0: max_value = array[target_index] max_index = target_index for number in range(0, target_index): if array[number] > max_value: max_value = array...
# Following are the basic concepts to get started with Python 3.7 """This is a sample Python multiline docstring""" # Display print("Let's get started with Python") print("Let's understand", end=" ") print("The Basic Concepts first") print("**********************************************************") # Variables # I...
"""This is a sample Python multiline docstring""" print("Let's get started with Python") print("Let's understand", end=' ') print('The Basic Concepts first') print('**********************************************************') my_age = 30 my_name = 'Sam' my_height = 1.72 print(type(myAge)) print(type(myName)) print(type...
print("Enter the name of the file along with it's extension:-") a=str(input()) if('.py' in a): print("The extension of the file is : python") else: print("The extension of the file is not python")
print("Enter the name of the file along with it's extension:-") a = str(input()) if '.py' in a: print('The extension of the file is : python') else: print('The extension of the file is not python')
# -*- coding: utf-8 -*- # (C) Wu Dong, 2018 # All rights reserved __author__ = 'Wu Dong <wudong@eastwu.cn>' __time__ = '2018/9/6 11:07'
__author__ = 'Wu Dong <wudong@eastwu.cn>' __time__ = '2018/9/6 11:07'
""" `EqualizeStrings <http://community.topcoder.com/stat?c=problem_statement&pm=10933>`__ """ def solution (s, t): out = "" for i in range(len(s)): x = s[i] y = t[i] diff = abs(ord(x) - ord(y)) if diff < 26 / 2: # values are close by, use minimum out += m...
""" `EqualizeStrings <http://community.topcoder.com/stat?c=problem_statement&pm=10933>`__ """ def solution(s, t): out = '' for i in range(len(s)): x = s[i] y = t[i] diff = abs(ord(x) - ord(y)) if diff < 26 / 2: out += min([x, y]) else: out += 'a' ...
# ABC167B - Easy Linear Programming def main(): # input A, B, C, K = map(int, input().split()) # compute kotae = A+(K-A)*0-(K-A-B) # output print(kotae) if __name__ == '__main__': main()
def main(): (a, b, c, k) = map(int, input().split()) kotae = A + (K - A) * 0 - (K - A - B) print(kotae) if __name__ == '__main__': main()
def lin(): print('-'*20) lin() def msg(m): lin() print(m) lin() msg('SISTEMA') def s(a,b): print(a+b) s(2,3) def cont(*num): for v in num: print(v,end=' ') print('\nfim') cont(2,3,7) def dobra(lst): pos = 0 while pos < len(lst): lst[pos] *= 2 pos += 1 valo...
def lin(): print('-' * 20) lin() def msg(m): lin() print(m) lin() msg('SISTEMA') def s(a, b): print(a + b) s(2, 3) def cont(*num): for v in num: print(v, end=' ') print('\nfim') cont(2, 3, 7) def dobra(lst): pos = 0 while pos < len(lst): lst[pos] *= 2 pos ...
inst = set() with open('tools/write_bytecode.py') as file: for line in file: if line.strip().startswith('#'): continue if '$' in line: instruction = line.split('$')[1].strip() print(instruction) inst.add(instruction.split()[0].strip().replace('32',...
inst = set() with open('tools/write_bytecode.py') as file: for line in file: if line.strip().startswith('#'): continue if '$' in line: instruction = line.split('$')[1].strip() print(instruction) inst.add(instruction.split()[0].strip().replace('32', '')...
input = """ q(X) :- p(f(X)). p(f(X)) :- r(X), q(X). q(a). r(a). """ output = """ q(X) :- p(f(X)). p(f(X)) :- r(X), q(X). q(a). r(a). """
input = '\nq(X) :- p(f(X)).\np(f(X)) :- r(X), q(X).\n\nq(a).\nr(a).\n' output = '\nq(X) :- p(f(X)).\np(f(X)) :- r(X), q(X).\n\nq(a).\nr(a).\n'
################################################################ # compareTools.py # # Defines how nodes and edges are compared. # Usable by other packages such as smallGraph # # Author: H. Mouchere, Oct. 2013 # Copyright (c) 2013-2014 Richard Zanibbi and Harold Mouchere ################################################...
def generate_list_err(ab, ba): list_err = [] if len(ab) == 0: ab = ['_'] if len(ba) == 0: ba = ['_'] for c1 in ab: for c2 in ba: listErr.append((c1, c2)) return listErr def default_metric(labelList1, labelList2): diff = set(labelList1) ^ set(labelList2) i...
"""Define the abstract class for similarity search service controllers""" class SearchService: """Search Service handles all controllers in the search service""" def __init__(self): pass def load_index(self): pass def load_labels(self): pass def similar_search_vectors(s...
"""Define the abstract class for similarity search service controllers""" class Searchservice: """Search Service handles all controllers in the search service""" def __init__(self): pass def load_index(self): pass def load_labels(self): pass def similar_search_vectors(se...
# -*- coding: utf-8 -*- def main(): n = int(input()) s = list() t = list() for i in range(n): si, ti = map(str, input().split()) s.append(si) t.append(int(ti)) x = input() index = s.index(x) print(sum(t[index + 1:])) if __name__ == '__main__': ...
def main(): n = int(input()) s = list() t = list() for i in range(n): (si, ti) = map(str, input().split()) s.append(si) t.append(int(ti)) x = input() index = s.index(x) print(sum(t[index + 1:])) if __name__ == '__main__': main()
### Alternating Characters - Solution def alternatingCharacters(): q = int(input()) while q: s = input() del_count = 0 for i in range(len(s)-1): if s[i] == s[i+1]: del_count += 1 print(del_count) q -= 1 alternatingCharacters()
def alternating_characters(): q = int(input()) while q: s = input() del_count = 0 for i in range(len(s) - 1): if s[i] == s[i + 1]: del_count += 1 print(del_count) q -= 1 alternating_characters()
class FileWarning(Exception): def __init__(self, file, message, *args, **kwargs): file.warn(message, *args, **kwargs) super().__init__(message % args) class FileError(Exception): def __init__(self, file, message, *args, **kwargs): file.error(message, *args, **kwargs) super()....
class Filewarning(Exception): def __init__(self, file, message, *args, **kwargs): file.warn(message, *args, **kwargs) super().__init__(message % args) class Fileerror(Exception): def __init__(self, file, message, *args, **kwargs): file.error(message, *args, **kwargs) super()._...
class RenderedView(object): def __init__(self, view_file: str, data): self.view_file = view_file self.data = data
class Renderedview(object): def __init__(self, view_file: str, data): self.view_file = view_file self.data = data
# PART 1 def game_of_cups(starting_sequence,num_of_moves,min_cup=None,max_cup=None): # create a "linked list" dict cups = { starting_sequence[i] : starting_sequence[i+1] for i in range(len(starting_sequence)-1) } cups[starting_sequence[-1]] = starting_sequence[0] # current_cup = ...
def game_of_cups(starting_sequence, num_of_moves, min_cup=None, max_cup=None): cups = {starting_sequence[i]: starting_sequence[i + 1] for i in range(len(starting_sequence) - 1)} cups[starting_sequence[-1]] = starting_sequence[0] current_cup = starting_sequence[0] max_cup = max_cup or max(starting_sequen...
txt = 'asdf;lkajsdf,as;lfkja' for i in txt: txt = txt[1:] if i == ",": break print(txt)
txt = 'asdf;lkajsdf,as;lfkja' for i in txt: txt = txt[1:] if i == ',': break print(txt)
class HashTable: def __init__(self): self.size = 11 self.slots = [None] * self.size self.data = [None] * self.size def put(self, key, data): hashvalue = self.hashfunction(key, len(self.slots)) if self.slots[hashvalue] == None: self.slots[hashvalue] = key ...
class Hashtable: def __init__(self): self.size = 11 self.slots = [None] * self.size self.data = [None] * self.size def put(self, key, data): hashvalue = self.hashfunction(key, len(self.slots)) if self.slots[hashvalue] == None: self.slots[hashvalue] = key ...
description = 'Email and SMS notifiers' group = 'lowlevel' devices = dict( email = device('nicos.devices.notifiers.Mailer', mailserver = 'mailhost.frm2.tum.de', sender = 'kws1@frm2.tum.de', copies = [ ('g.brandl@fz-juelich.de', 'all'), ('a.feoktystov@fz-juelich.de',...
description = 'Email and SMS notifiers' group = 'lowlevel' devices = dict(email=device('nicos.devices.notifiers.Mailer', mailserver='mailhost.frm2.tum.de', sender='kws1@frm2.tum.de', copies=[('g.brandl@fz-juelich.de', 'all'), ('a.feoktystov@fz-juelich.de', 'all'), ('h.frielinghaus@fz-juelich.de', 'all'), ('z.mahhouti@f...
print("Welcome to the rollercoaster!") height = int(input("What is your height in cm? ")) if height > 120: print("you can ride the rollercoaster!") age = int(input("What is your age? ")) if age <= 18: print("$7") else: print("$12") else: print("no")
print('Welcome to the rollercoaster!') height = int(input('What is your height in cm? ')) if height > 120: print('you can ride the rollercoaster!') age = int(input('What is your age? ')) if age <= 18: print('$7') else: print('$12') else: print('no')
# "Config.py" # - config file for ConfigGUI.py # This is Python, therefore this is a comment # NOTE: variable names cannot start with '__' ECGColumn = True HRColumn = False PeakColumn = True RRColumn = True SeparateECGFile = True TCP_Host = "localhost" TCP_Port = 1000 TCPtimeout = 3 TimeColumn = True UDPConnectTimeo...
ecg_column = True hr_column = False peak_column = True rr_column = True separate_ecg_file = True tcp__host = 'localhost' tcp__port = 1000 tc_ptimeout = 3 time_column = True udp_connect_timeout = 1 udp_receive_timeout = 5 udp__client_ip = 'localhost' udp__client_port = 1001 udp__server_ip = 'localhost' udp__server_port ...
class Dictionary(object): def __init__(self): self.my_dict = {} def look(self, key): return self.my_dict.get(key, "Can't find entry for {}".format(key)) def newentry(self, key, value): """ new_entry == PEP8 (forced by Codewars) """ self.my_dict[key] = value
class Dictionary(object): def __init__(self): self.my_dict = {} def look(self, key): return self.my_dict.get(key, "Can't find entry for {}".format(key)) def newentry(self, key, value): """ new_entry == PEP8 (forced by Codewars) """ self.my_dict[key] = value
hidden_dim = 128 dilation = [1,2,4,8,16,32,64,128,256,512] sample_rate = 16000 timestep = 6080 is_training = True use_mulaw = True batch_size = 1 num_epochs = 10000 save_dir = './logdir' test_data = 'test.wav'
hidden_dim = 128 dilation = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512] sample_rate = 16000 timestep = 6080 is_training = True use_mulaw = True batch_size = 1 num_epochs = 10000 save_dir = './logdir' test_data = 'test.wav'
# This file provides an object for version numbers. class Version: def __init__(self, major: int, minor: int=0, patch: int=0, tag: str=""): self.major = major self.minor = minor self.patch = patch self.tag = tag def __repr__(self): return "Version(" + str(self.major...
class Version: def __init__(self, major: int, minor: int=0, patch: int=0, tag: str=''): self.major = major self.minor = minor self.patch = patch self.tag = tag def __repr__(self): return 'Version(' + str(self.major) + ', ' + str(self.minor) + ', ' + str(self.patch) + ',...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: self.result = [] self.wft([root]) return self.resu...
class Solution: def level_order_bottom(self, root: TreeNode) -> List[List[int]]: self.result = [] self.wft([root]) return self.result def wft(self, nodes): new_nodes = [] values = [] for n in nodes: if n is not None: values.append(n.v...
class airQuality: def __init__(self, bus): self.iaq = 0 self.bus = bus self.address = 0x5A self.datablock = 9 self.data = 0 def read(self): data = self.bus.read_i2c_block_data(self.address, 0x00, self.datablock) #WIP # Convert the data #if...
class Airquality: def __init__(self, bus): self.iaq = 0 self.bus = bus self.address = 90 self.datablock = 9 self.data = 0 def read(self): data = self.bus.read_i2c_block_data(self.address, 0, self.datablock)
#You are given a list of n-1 integers and these integers are in the range of 1 to n. #There are no duplicates in the list. #One of the integers is missing in the list. Write an efficient code to find the missing integer ar=[ 1, 2, 4, 5, 6 ] def missing_(a): print("l",l) for i in range(1,l+2): if(i not in a): ...
ar = [1, 2, 4, 5, 6] def missing_(a): print('l', l) for i in range(1, l + 2): if i not in a: return i print(missing_(ar))
class Utils(): """ This is just methods stored as methods of a class. It still needs (allthough void) .inputs(), .output() and .build() and defines whatever else is handy. (It is nice, as in this case, to separate constants from methods.) """ def __init__(self): self.species = {'canines' : ['Doggy', 'Hyena'],...
class Utils: """ This is just methods stored as methods of a class. It still needs (allthough void) .inputs(), .output() and .build() and defines whatever else is handy. (It is nice, as in this case, to separate constants from methods.) """ def __init__(self): self.species = {'canines': ['Doggy', ...
print('Enter a text and when finished press Enter twice: ') text = '' while True: line = input() if line: text += line + '\n ' else: break def wc(text): n_words = len(text.split(' ')) - 1 n_lines = len(text.split('\n')) - 1 n_characters = len(text) - 2*n_lines ...
print('Enter a text and when finished press Enter twice: ') text = '' while True: line = input() if line: text += line + '\n ' else: break def wc(text): n_words = len(text.split(' ')) - 1 n_lines = len(text.split('\n')) - 1 n_characters = len(text) - 2 * n_lines print(f'Char...
def sample_anchors_pre(df, n_samples= 256, neg_ratio= 0.5): ''' Sample total of n samples across both BG and FG classes. If one of the classes have less samples than n/2, we will sample from majority class to make up for short. Args: df with column named labels_anchors, containing 1 for f...
def sample_anchors_pre(df, n_samples=256, neg_ratio=0.5): """ Sample total of n samples across both BG and FG classes. If one of the classes have less samples than n/2, we will sample from majority class to make up for short. Args: df with column named labels_anchors, containing 1 for foregrou...
ansOut = [] coin = [10, 50, 100, 500] while True: price = int(input()) if price == 0: break cash = list(map(int, input().split())) sumCash = sum(c * n for c, n in zip(coin, cash)) change = sumCash - price changeCoins = [(change % 50) // 10, (change % 100) // 50, (change % 500) // 100, ch...
ans_out = [] coin = [10, 50, 100, 500] while True: price = int(input()) if price == 0: break cash = list(map(int, input().split())) sum_cash = sum((c * n for (c, n) in zip(coin, cash))) change = sumCash - price change_coins = [change % 50 // 10, change % 100 // 50, change % 500 // 100, c...
def isBalanced(expr): if len(expr)%2!=0: return False opening=set('([{') match=set([ ('(',')'), ('[',']'), ('{','}') ]) stack=[] for char in expr: if char in opening: stack.append(char) else: if len(stack)==0: return False ...
def is_balanced(expr): if len(expr) % 2 != 0: return False opening = set('([{') match = set([('(', ')'), ('[', ']'), ('{', '}')]) stack = [] for char in expr: if char in opening: stack.append(char) else: if len(stack) == 0: return False...
class Solution: def mySqrt(self, x: int) -> int: left, right = 0, x while left <= right: mid = left + (right - left) // 2 square = mid ** 2 if square <= x: left = mid + 1 elif squ...
class Solution: def my_sqrt(self, x: int) -> int: (left, right) = (0, x) while left <= right: mid = left + (right - left) // 2 square = mid ** 2 if square <= x: left = mid + 1 elif square > x: right = mid - 1 re...
In [18]: my_list = [27, "11-13-2017", 84.98, 5] In [19]: store27 = salesReceipt._make(my_list) In [20]: print(store27) salesReceipt(storeID=27, saleDate='11-13-2017', saleAmount=84.98, totalGuests=5)
In[18]: my_list = [27, '11-13-2017', 84.98, 5] In[19]: store27 = salesReceipt._make(my_list) In[20]: print(store27) sales_receipt(storeID=27, saleDate='11-13-2017', saleAmount=84.98, totalGuests=5)
adj_list_moo = {4: [5], 6: [5], 5: [7], 7: []} def dfs_topsort(graph): # recursive dfs with L = [] # additional list for order of nodes color = { u : "white" for u in graph } found_cycle = [False] for u in graph: if color[u] == "white": dfs_visit(graph,...
adj_list_moo = {4: [5], 6: [5], 5: [7], 7: []} def dfs_topsort(graph): l = [] color = {u: 'white' for u in graph} found_cycle = [False] for u in graph: if color[u] == 'white': dfs_visit(graph, u, color, L, found_cycle) if found_cycle[0]: break if found_cycle[...
#!/usr/bin/env python3 flags = ['QCTF{e51f2dad87875d76fb081f2b467535ef}', 'QCTF{c89a4b8b181ea0e7666dc8bf93b34779}', 'QCTF{50b59ef5ba8ca7650323b96119507a98}', 'QCTF{fb1c1b7f76e5ca22411fcee3d024ff46}', 'QCTF{4909e8138219a1f5f166e6e06e057cbc}', 'QCTF{649d0b63d4bd82a9af7af03ba46838d3}', 'QCTF{af043650dc65acce4e001425bacb...
flags = ['QCTF{e51f2dad87875d76fb081f2b467535ef}', 'QCTF{c89a4b8b181ea0e7666dc8bf93b34779}', 'QCTF{50b59ef5ba8ca7650323b96119507a98}', 'QCTF{fb1c1b7f76e5ca22411fcee3d024ff46}', 'QCTF{4909e8138219a1f5f166e6e06e057cbc}', 'QCTF{649d0b63d4bd82a9af7af03ba46838d3}', 'QCTF{af043650dc65acce4e001425bacbd3f2}', 'QCTF{8e4225e08e6...
#!/usr/bin/python3.5 def fib(n: int): fibs = [1, 1] for _ in range(max(n-2, 0)): fibs.append(fibs[-1] + fibs[-2]) return fibs[n-1] print("%s" % fib(38))
def fib(n: int): fibs = [1, 1] for _ in range(max(n - 2, 0)): fibs.append(fibs[-1] + fibs[-2]) return fibs[n - 1] print('%s' % fib(38))
""" Sponge Knowledge Base Remote API """ class UpperCase(Action): def onConfigure(self): self.withArg(StringType("text").withLabel("Text to upper case")).withResult(StringType().withLabel("Upper case text")) def onCall(self, text): self.logger.info("Action {} called", self.meta.name) re...
""" Sponge Knowledge Base Remote API """ class Uppercase(Action): def on_configure(self): self.withArg(string_type('text').withLabel('Text to upper case')).withResult(string_type().withLabel('Upper case text')) def on_call(self, text): self.logger.info('Action {} called', self.meta.name) ...
def method1(str1: str, str2: str) -> int: def compare(str1, str2): for i in range(256): if str1[i] != str2[i]: return False return True def search(pat, txt): m = len(pat) n = len(txt) count_p = [0] * 256 count_t = [0] * 256 f...
def method1(str1: str, str2: str) -> int: def compare(str1, str2): for i in range(256): if str1[i] != str2[i]: return False return True def search(pat, txt): m = len(pat) n = len(txt) count_p = [0] * 256 count_t = [0] * 256 fo...
# coding=utf8 class Error(Exception): pass class TitleRequiredError(Error): pass class TextRequiredError(Error): pass class APITokenRequiredError(Error): pass class GetImageRequestError(Error): pass class ImageUploadHTTPError(Error): pass class FileTypeNotSupported(Error): pass...
class Error(Exception): pass class Titlerequirederror(Error): pass class Textrequirederror(Error): pass class Apitokenrequirederror(Error): pass class Getimagerequesterror(Error): pass class Imageuploadhttperror(Error): pass class Filetypenotsupported(Error): pass class Telegraphunkno...