content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def find_132(array): queue = [] minVal = array[0] for v in array[1:]: while queue and v >= queue[-1][0]: queue.pop() if queue and v < queue[-1][1]: return True queue.append((v, minVal)) minVal = min(minVal, v) return False print(find_132([1,0,1,-4...
def find_132(array): queue = [] min_val = array[0] for v in array[1:]: while queue and v >= queue[-1][0]: queue.pop() if queue and v < queue[-1][1]: return True queue.append((v, minVal)) min_val = min(minVal, v) return False print(find_132([1, 0, 1...
mail_data = [ { "sender": "Winnie Mandela", "email": "winniee.mandela@gmail.com", "read_status": "unread", "content": "Dear Sir/Madam,<br/> I am Winnie Mandela. I am the second wife of Nelson Mandela the former South African president. How are you today? I am in p...
mail_data = [{'sender': 'Winnie Mandela', 'email': 'winniee.mandela@gmail.com', 'read_status': 'unread', 'content': "Dear Sir/Madam,<br/> I am Winnie Mandela. I am the second wife of Nelson Mandela the former South African president. How are you today? I am in possession of US$45 million dollars. I need to transfer it ...
_TEST_DATA = """939 7,13,x,x,59,x,31,19""" with open("inputs/day13.txt") as f: lines = f.read().splitlines() # lines = _TEST_DATA.splitlines() time = int(lines[0]) bus_ids = [(i, int(bus)) for i, bus in enumerate(lines[1].split(",")) if bus != "x"] def part_a() -> int: closest = min(((i, a...
_test_data = '939\n7,13,x,x,59,x,31,19' with open('inputs/day13.txt') as f: lines = f.read().splitlines() time = int(lines[0]) bus_ids = [(i, int(bus)) for (i, bus) in enumerate(lines[1].split(',')) if bus != 'x'] def part_a() -> int: closest = min(((i, abs(time % i - i)) for (_, i) in bus_ids)...
BASS = "Bass" TENOR = "Tenor" ALTO = "Alto" SOPRANO = "Soprano" class Voice: """Represents the type of voice. Attributes ---------- note : int The note of the voice. """ def __init__(self, note): """Constructor method. Parameters ---------- note : int...
bass = 'Bass' tenor = 'Tenor' alto = 'Alto' soprano = 'Soprano' class Voice: """Represents the type of voice. Attributes ---------- note : int The note of the voice. """ def __init__(self, note): """Constructor method. Parameters ---------- note : int ...
class Router(object): """ A router to control all database operations on models in the auth application. """ def db_for_read(self, model, **hints): """ Attempts to read auth models go to rolodex. """ if model._meta.app_label == 'rolodex': return...
class Router(object): """ A router to control all database operations on models in the auth application. """ def db_for_read(self, model, **hints): """ Attempts to read auth models go to rolodex. """ if model._meta.app_label == 'rolodex': return 'rolodex_...
config = { 'HOST': '0.0.0.0', 'PORT': 4242 }
config = {'HOST': '0.0.0.0', 'PORT': 4242}
class Solution(object): def flipAndInvertImage(self, A): """ :type A: List[List[int]] :rtype: List[List[int]] """ return [[1-element for element in nested_array][::-1] for nested_array in A]
class Solution(object): def flip_and_invert_image(self, A): """ :type A: List[List[int]] :rtype: List[List[int]] """ return [[1 - element for element in nested_array][::-1] for nested_array in A]
def _longest_common_subsequence(s1: str, s2: str) -> int: """ Let m and n be the lengths of two strings. Build L[m+1][n+1] from the bottom up. Note: L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] Runtime: O(mn) Space Complexity: O(mn) """ m, n = len(s1), len(s2) L = [[0] ...
def _longest_common_subsequence(s1: str, s2: str) -> int: """ Let m and n be the lengths of two strings. Build L[m+1][n+1] from the bottom up. Note: L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] Runtime: O(mn) Space Complexity: O(mn) """ (m, n) = (len(s1), len(s2)) l = [...
class Leapx_org(): pass L_obj1 = Leapx_org() L_obj2 = Leapx_org() print (L_obj1) print (L_obj2)
class Leapx_Org: pass l_obj1 = leapx_org() l_obj2 = leapx_org() print(L_obj1) print(L_obj2)
# While loop - body is true, expresses condition # For loop is an iterator - executes each item in the sequence # While loop should have a statement that will result in true to close the loop secret = "swordfish" pw = '' while pw != secret: pw = input("what's the secret word ? ") # Continue (Testing condition ...
secret = 'swordfish' pw = '' while pw != secret: pw = input("what's the secret word ? ") secret = 'swordfish' pw = '' auth = False count = 0 max_attempt = 5 while pw != secret: count += 1 if count > max_attempt: break if count == 3: continue pw = input(f"{count}: what's the secret wo...
for __ in range(int(input())): N,A,B,C = map(int,input().split( )) if A+C >= N and B>=N: print("YES") else: print("NO")
for __ in range(int(input())): (n, a, b, c) = map(int, input().split()) if A + C >= N and B >= N: print('YES') else: print('NO')
class Solution: def computeArea(self, A: int, B: int, C: int, D: int, E: int, F: int, G: int, H: int) -> int: left = max(A, E) right = max(min(C, G), left) bottom = max(B, F) up = max(min(D, H), bottom) return (C - A)*(D - B) + (G - E)*(H - F) - (right - left)*(up - bottom)
class Solution: def compute_area(self, A: int, B: int, C: int, D: int, E: int, F: int, G: int, H: int) -> int: left = max(A, E) right = max(min(C, G), left) bottom = max(B, F) up = max(min(D, H), bottom) return (C - A) * (D - B) + (G - E) * (H - F) - (right - left) * (up - b...
### Kids With the Greatest Number of Candies - Solution class Solution: def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]: checkGreatest = [] maxNum = max(candies) for num in candies: if num+extraCandies >= maxNum: checkGreatest.appen...
class Solution: def kids_with_candies(self, candies: List[int], extraCandies: int) -> List[bool]: check_greatest = [] max_num = max(candies) for num in candies: if num + extraCandies >= maxNum: checkGreatest.append(True) else: checkGre...
class BetterDict(dict): def __getattr__(self, attr): if attr in self: return self.__dict_to_BetterDict(attr) raise AttributeError def __dict_to_BetterDict(self, attr): """Convert the passed attr to a BetterDict if the value is a dict Returns: The new value of the p...
class Betterdict(dict): def __getattr__(self, attr): if attr in self: return self.__dict_to_BetterDict(attr) raise AttributeError def __dict_to__better_dict(self, attr): """Convert the passed attr to a BetterDict if the value is a dict Returns: The new value of the...
''' Created on Oct 3, 2017 @author: Liza Dayoub ''' class IndexPatternDoesNotExist(Exception): """Raise when index pattern does not exist""" pass
""" Created on Oct 3, 2017 @author: Liza Dayoub """ class Indexpatterndoesnotexist(Exception): """Raise when index pattern does not exist""" pass
""" Developed by Alex Ermolaev (Abionics) Email: abionics.dev@gmail.com License: MIT """ __version__ = '1.0.0'
""" Developed by Alex Ermolaev (Abionics) Email: abionics.dev@gmail.com License: MIT """ __version__ = '1.0.0'
class VotingModule(): def verify(self, ABDverdict, SBDVerdict, staticVerdict): alert = False block = False verdict = "" #Case 1 if ABDverdict == False and SBDVerdict == False and staticVerdict == False: alert = False block = False verdict ...
class Votingmodule: def verify(self, ABDverdict, SBDVerdict, staticVerdict): alert = False block = False verdict = '' if ABDverdict == False and SBDVerdict == False and (staticVerdict == False): alert = False block = False verdict = '1' el...
#!/usr/bin/python3 # -*- coding: utf-8 -*- def get_curVersion(): """ get program version """ return "V1.0.2" if __name__ == "__main__": pass
def get_cur_version(): """ get program version """ return 'V1.0.2' if __name__ == '__main__': pass
( lambda directions, _: print(directions["forward"] * (directions["down"] - directions["up"])) )( commands := {"up": 0, "down": 0, "forward": 0}, [ commands.__setitem__( command, commands[command] + int(amount) ) for command, amount in list(map(str.split, open...
(lambda directions, _: print(directions['forward'] * (directions['down'] - directions['up'])))((commands := {'up': 0, 'down': 0, 'forward': 0}), [commands.__setitem__(command, commands[command] + int(amount)) for (command, amount) in list(map(str.split, open('input.txt').readlines()))])
def calculate_air_density(pressure, temperature): """ Calculates air density from ideal gas law. :param pressure: Air pressure in Pascals :param temp: Air temperature in Kelvins :return density: Air density in kg/m^2 """ R = 286.9 # specific gas constant for air [J/(kg*K)] ...
def calculate_air_density(pressure, temperature): """ Calculates air density from ideal gas law. :param pressure: Air pressure in Pascals :param temp: Air temperature in Kelvins :return density: Air density in kg/m^2 """ r = 286.9 density = pressure / (R * temperature) return de...
p_max = p_max - 30 ENVIRONMENT_MEMORY = 2 MAX_NUMBER_OF_AGENTS = 3 REWARD_PENALTY = 1.5 N_STATES_BINS = 100 MAX_STEPS = 12000 STEPS_PER_EPISODE = 50 REPLAY_INITIAL = int(1E3) ACTOR_LEARNING_RATE = 3E-5 CRITIC_LEARNING_RATE = 3E-4 HIDDEN_SIZE = 256 N_HIDDEN_LAYERS = 5 BATCH_SIZE = 128 REPLAY_MEMORY_SIZE = int(1E4) EXPLO...
p_max = p_max - 30 environment_memory = 2 max_number_of_agents = 3 reward_penalty = 1.5 n_states_bins = 100 max_steps = 12000 steps_per_episode = 50 replay_initial = int(1000.0) actor_learning_rate = 3e-05 critic_learning_rate = 0.0003 hidden_size = 256 n_hidden_layers = 5 batch_size = 128 replay_memory_size = int(1000...
class DimensionError(Exception): """ Thrown when there is an error in the dimensions of the dataset given, i.e. coords are not time, lat, lon only. """ pass class WrongTypeError(Exception): """ Thrown when wrong data type for data set is given. """ pass class FeatureNotInDataset(Exce...
class Dimensionerror(Exception): """ Thrown when there is an error in the dimensions of the dataset given, i.e. coords are not time, lat, lon only. """ pass class Wrongtypeerror(Exception): """ Thrown when wrong data type for data set is given. """ pass class Featurenotindataset(Exceptio...
# Author: Gaurav Pande # implement stack using queue # link: https://leetcode.com/problems/implement-stack-using-queues/description/ class MyStack(object): def __init__(self): """ Initialize your data structure here. """ self.queue = [] self.top_element = None def pus...
class Mystack(object): def __init__(self): """ Initialize your data structure here. """ self.queue = [] self.top_element = None def push(self, x): """ Push element x onto stack. :type x: int :rtype: void """ self.top_eleme...
def resetControls(): controls = cmds.ls(sl = True, type='transform') for selCtrl in controls: attrReset = cmds.listAttr(selCtrl, k=True, u=True) for resetObj in attrReset: byDefault=cmds.attributeQuery( resetObj, node = selCtrl, listDefault = True) try: ...
def reset_controls(): controls = cmds.ls(sl=True, type='transform') for sel_ctrl in controls: attr_reset = cmds.listAttr(selCtrl, k=True, u=True) for reset_obj in attrReset: by_default = cmds.attributeQuery(resetObj, node=selCtrl, listDefault=True) try: cm...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class ListNode: def __init__(self, x): self.val = x self.next = None def __str__(self): text = str() node = self while node != None: text += "%d->" %node.val node = node.next text += "None" ...
class Listnode: def __init__(self, x): self.val = x self.next = None def __str__(self): text = str() node = self while node != None: text += '%d->' % node.val node = node.next text += 'None' return text class Solution: def m...
"""Generated class for config_localnet.json""" class Object75D54154: """Generated schema class""" def __init__(self): self.id = None @staticmethod def from_dict(source): if not source: return None result = Object75D54154() result.id = source.get('id') return result @staticmethod...
"""Generated class for config_localnet.json""" class Object75D54154: """Generated schema class""" def __init__(self): self.id = None @staticmethod def from_dict(source): if not source: return None result = object75_d54154() result.id = source.get('id') ...
#In this program it will tell How many vowels are there in total userInput=""; print("Enter the name to calculate the number of volwels you wanted to know :"); UserInput=input(); count=0; for i in UserInput: if(i=='a' or i=='e' or i=='o' or i=='u'): count=count+1; print("The number of vowels entered in you...
user_input = '' print('Enter the name to calculate the number of volwels you wanted to know :') user_input = input() count = 0 for i in UserInput: if i == 'a' or i == 'e' or i == 'o' or (i == 'u'): count = count + 1 print('The number of vowels entered in your name are:\n' + str(count))
def verificar(lista, indice_score=2): for i in range(len(lista)): if i+1 == len(lista): return True if float(lista[i+1][indice_score]) - float(lista[i][indice_score]) < 0: return False if __name__ == '__main__': teste = [0, 1, 2, 3, 4] teste2 = [-1, -2, 4, 5, 7] ...
def verificar(lista, indice_score=2): for i in range(len(lista)): if i + 1 == len(lista): return True if float(lista[i + 1][indice_score]) - float(lista[i][indice_score]) < 0: return False if __name__ == '__main__': teste = [0, 1, 2, 3, 4] teste2 = [-1, -2, 4, 5, 7] ...
class Auth: def __init__(self, access_token: str, user_id: str) -> None: self.access_token = access_token self.user_id = user_id class AuthStorage: def __init__(self) -> None: self.data = dict() def saveAuth(self, client_id: str, access_token: str, user_id: str): a = Auth(...
class Auth: def __init__(self, access_token: str, user_id: str) -> None: self.access_token = access_token self.user_id = user_id class Authstorage: def __init__(self) -> None: self.data = dict() def save_auth(self, client_id: str, access_token: str, user_id: str): a = aut...
N = 1_000_000 a = list(range(N)) b = list(range(N)) # c = [0] * N # c = [a[i] + b[i] for i in range(N)] c = [x + y for x, y in zip(a, b)] s = sum(c) print(s)
n = 1000000 a = list(range(N)) b = list(range(N)) c = [x + y for (x, y) in zip(a, b)] s = sum(c) print(s)
""" Diccionarios en python! => tipo de estructuras de datos que te permite ordenar un conjunto no ordenado de pares clave valor! o en ingles key values """
""" Diccionarios en python! => tipo de estructuras de datos que te permite ordenar un conjunto no ordenado de pares clave valor! o en ingles key values """
class FailedToExtractGFF3Attributes(Exception): pass class FailedToOutputBEDFile(Exception): pass class FailedToOutputGFFFile(Exception): pass class InvalidIDSelectionInGFFFile(Exception): pass
class Failedtoextractgff3Attributes(Exception): pass class Failedtooutputbedfile(Exception): pass class Failedtooutputgfffile(Exception): pass class Invalididselectioningfffile(Exception): pass
""" Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area i...
""" Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area i...
class PhoneNumbers: """ 2600hz Kazoo PhoneNumbers API. :param rest_request: The request client to use. (optional, default: pykazoo.RestRequest()) :type rest_request: pykazoo.restrequest.RestRequest """ def __init__(self, rest_request): self.rest_request = rest_request ...
class Phonenumbers: """ 2600hz Kazoo PhoneNumbers API. :param rest_request: The request client to use. (optional, default: pykazoo.RestRequest()) :type rest_request: pykazoo.restrequest.RestRequest """ def __init__(self, rest_request): self.rest_request = rest_request ...
newton_init = [] val = int(input()) for i in range(val): x = int(input()) y = int(input()) newton_init.append([x,y]) print(newton_init)
newton_init = [] val = int(input()) for i in range(val): x = int(input()) y = int(input()) newton_init.append([x, y]) print(newton_init)
def bvh(filepath="", axis_forward='-Z', axis_up='Y', filter_glob="*.bvh", target='ARMATURE', global_scale=1.0, frame_start=1, use_fps_scale=False, update_scene_fps=False, update_scene_duration=False, use_cyclic=False, rotate_mode='NATIVE'): pass
def bvh(filepath='', axis_forward='-Z', axis_up='Y', filter_glob='*.bvh', target='ARMATURE', global_scale=1.0, frame_start=1, use_fps_scale=False, update_scene_fps=False, update_scene_duration=False, use_cyclic=False, rotate_mode='NATIVE'): pass
def remove_if_exists(mylist, item): """ Remove item from mylist if it exists, do nothing otherwise """ to_remove = [] for i in range(len(mylist)): if mylist[i] == item: to_remove.append(mylist[i]) for el in to_remove: mylist.remove(el) def remove_if_ex...
def remove_if_exists(mylist, item): """ Remove item from mylist if it exists, do nothing otherwise """ to_remove = [] for i in range(len(mylist)): if mylist[i] == item: to_remove.append(mylist[i]) for el in to_remove: mylist.remove(el) def remove_if_exists_copy(mylist, item)...
""" # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def maxDepth(self, root: 'Node') -> int: if not root: return 0 stack=[(root, 1)] while(stack): cur, l...
""" # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def max_depth(self, root: 'Node') -> int: if not root: return 0 stack = [(root, 1)] while stack: (cu...
# This shouldn't be treated as a pybind signature def reset(): """resets everything. Shouldn't be picked as a pybind signature."""
def reset(): """resets everything. Shouldn't be picked as a pybind signature."""
# # PySNMP MIB module OPTIX-SONET-TRAPS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OPTIX-SONET-TRAPS-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:26:13 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, constraints_intersection, single_value_constraint, value_range_constraint, constraints_union) ...
#WAP to accept a string from user and replace all occurrances of first character except for the first character. name = input("Please enter a string: ") replaceToken = input("Please enter token to replace: ") print (name) name2 = name[0] + name[1:].replace(name[0], replaceToken) print (name2)
name = input('Please enter a string: ') replace_token = input('Please enter token to replace: ') print(name) name2 = name[0] + name[1:].replace(name[0], replaceToken) print(name2)
#!/usr/bin/python3 class Unit: bydgoszcz = "040410661011" warszawa = "071412865011" krakow = "011212161011" lodz = "051011661011" wroclaw = "030210564011" poznan = "023016264011" gdansk = "042214361011" szczecin = "023216562011" lublin = "060611163011" bialystok = "062013761011...
class Unit: bydgoszcz = '040410661011' warszawa = '071412865011' krakow = '011212161011' lodz = '051011661011' wroclaw = '030210564011' poznan = '023016264011' gdansk = '042214361011' szczecin = '023216562011' lublin = '060611163011' bialystok = '062013761011' katowice = '012...
''' Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. Runtime: 56 ms ''' class Solution(object): def containsDuplicate(self, nums): """ :ty...
""" Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. Runtime: 56 ms """ class Solution(object): def contains_duplicate(self, nums): """ ...
# -*- coding: utf-8 -*- """ pylatex.utils ~~~~~~~ This module implements some simple functions with all kinds of functionality. :copyright: (c) 2014 by Jelte Fennema. :license: MIT, see License for more details. """ _latex_special_chars = { '&': r'\&', '%': r'\%', '$': r'\$', ...
""" pylatex.utils ~~~~~~~ This module implements some simple functions with all kinds of functionality. :copyright: (c) 2014 by Jelte Fennema. :license: MIT, see License for more details. """ _latex_special_chars = {'&': '\\&', '%': '\\%', '$': '\\$', '#': '\\#', '_': '\\_', '{': '\\{', '}': '...
VERSION = '0.0.1' DIR_KIND = { 'cache': {'search': '__pycache__', 'help': 'Delete the pycache folders'}, 'egg': {'search': 'egg-info', 'help': 'Delete the egg folders'}, } FILE_KIND = { 'pyc': {'search': '.pyc', 'help': 'Delete the pyc files'}, }
version = '0.0.1' dir_kind = {'cache': {'search': '__pycache__', 'help': 'Delete the pycache folders'}, 'egg': {'search': 'egg-info', 'help': 'Delete the egg folders'}} file_kind = {'pyc': {'search': '.pyc', 'help': 'Delete the pyc files'}}
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def addTwoNumbers(l1: ListNode, l2: ListNode) -> ListNode: tmp = 0 result = ListNode(0) dummy = result while l1 or l2: v = tmp if l1: v += l1.val ...
class Listnode: def __init__(self, x): self.val = x self.next = None def add_two_numbers(l1: ListNode, l2: ListNode) -> ListNode: tmp = 0 result = list_node(0) dummy = result while l1 or l2: v = tmp if l1: v += l1.val l1 = l1.next if ...
class ComplexPolynomialIterationData(object): iteration_values = None exploded_indexes = None remaining_indexes = None def __init__(self, iteration_values, exploded_indexes, remaining_indexes): self.iteration_values = iteration_values self.exploded_indexes = exploded_indexes se...
class Complexpolynomialiterationdata(object): iteration_values = None exploded_indexes = None remaining_indexes = None def __init__(self, iteration_values, exploded_indexes, remaining_indexes): self.iteration_values = iteration_values self.exploded_indexes = exploded_indexes sel...
begin = int(input()) ending = int(input()) point = int(input()) left = min(begin, ending) right = max(begin, ending) distance_left = abs(left - point) distance_right = abs(right - point) min_distance = min(distance_left, distance_right) if left <= point <= right: print("in") else: print("out") print(min_dis...
begin = int(input()) ending = int(input()) point = int(input()) left = min(begin, ending) right = max(begin, ending) distance_left = abs(left - point) distance_right = abs(right - point) min_distance = min(distance_left, distance_right) if left <= point <= right: print('in') else: print('out') print(min_distanc...
# Esercizio n. 5 # Visualizzare tutti i numeri dispari compresi fra 1 e 50. n_min = 1 n_max = 50 print("I numeri dispari compresi tra", n_min, "e", n_max, "sono:") n = n_min while n <= n_max: if n % 2 != 0: print(n, "\t") n = n + 1
n_min = 1 n_max = 50 print('I numeri dispari compresi tra', n_min, 'e', n_max, 'sono:') n = n_min while n <= n_max: if n % 2 != 0: print(n, '\t') n = n + 1
def cheer(n): 'return a string with a silly cheer based on n' if n <= 1: return "Hurrah!" else: return "Hip " + cheer(n - 1) x = cheer(5) print(x)
def cheer(n): """return a string with a silly cheer based on n""" if n <= 1: return 'Hurrah!' else: return 'Hip ' + cheer(n - 1) x = cheer(5) print(x)
"""Clase de For.""" names = ['Abraham', 'Cesar', 'Daniel', 'Daniel', 'Diego', 'Edgar'] for name in names: print(f'Student: {name}') else: print('No more names') string = 'Miguel' for char in string: if char != 'i': print(char) else: print('Out of the for') numbers = [] for number in range(0,21,2): num...
"""Clase de For.""" names = ['Abraham', 'Cesar', 'Daniel', 'Daniel', 'Diego', 'Edgar'] for name in names: print(f'Student: {name}') else: print('No more names') string = 'Miguel' for char in string: if char != 'i': print(char) else: print('Out of the for') numbers = [] for number in rang...
a = 12 print(f"a is {a}") print(f"Data Type of a is {type(a)}") b = 3.1415926 print(f"b is {b}") print(f"Data Type of b is {type(b)}") c = "message" print(f"c is {c}") print(f"Data Type of c is {type(c)}") d = True print(f"d is {d}") print(f"Data Type of d is {type(d)}") e = None print(f"e is {e}") print(f"Data Typ...
a = 12 print(f'a is {a}') print(f'Data Type of a is {type(a)}') b = 3.1415926 print(f'b is {b}') print(f'Data Type of b is {type(b)}') c = 'message' print(f'c is {c}') print(f'Data Type of c is {type(c)}') d = True print(f'd is {d}') print(f'Data Type of d is {type(d)}') e = None print(f'e is {e}') print(f'Data Type of...
def detectLoop(head): if head == None: return False start = head next_next_start = head.next if next_next_start == None: return False next_next_start = head.next.next while next_next_start != None: start = start.next next_next_start = next_next_...
def detect_loop(head): if head == None: return False start = head next_next_start = head.next if next_next_start == None: return False next_next_start = head.next.next while next_next_start != None: start = start.next next_next_start = next_next_start.next ...
# -*- coding: utf-8 -*- """ Created on Sat Feb 7 12:43:10 2015 @author: Christopher R. Carlson, crcarlson@gmail.com Helper functions for changing the display of IPython notebooks as of Feb 2015. """ def toggle_js(): """ Return javascript string which creates code-hiding behavior IPython code cell hidi...
""" Created on Sat Feb 7 12:43:10 2015 @author: Christopher R. Carlson, crcarlson@gmail.com Helper functions for changing the display of IPython notebooks as of Feb 2015. """ def toggle_js(): """ Return javascript string which creates code-hiding behavior IPython code cell hiding script inspired by t...
''' Problem 22 @author: Kevin Ji ''' def get_value_of_letter(letter): return ord(letter.upper()) - 64 def get_value_of_word(word): value = 0 for char in word: value += get_value_of_letter(char) return value # Parse the file, and place the names into a list file = open("problem_22_names.t...
""" Problem 22 @author: Kevin Ji """ def get_value_of_letter(letter): return ord(letter.upper()) - 64 def get_value_of_word(word): value = 0 for char in word: value += get_value_of_letter(char) return value file = open('problem_22_names.txt', 'r') names_text = file.read() names = sorted(names...
''' Design Patterns & Utilities =========================== commonstring segregatestring Borg Singleton Record Struct Borg and Singleton adapted from: * http://code.activestate.com/recipes/66531/ with clarifications from: * http://snippets.dzone.com/posts/show/651 It is hard to quantify which approach is better. ...
""" Design Patterns & Utilities =========================== commonstring segregatestring Borg Singleton Record Struct Borg and Singleton adapted from: * http://code.activestate.com/recipes/66531/ with clarifications from: * http://snippets.dzone.com/posts/show/651 It is hard to quantify which approach is better. ...
""" The Single Responsibility Principle A class should have one, and only one, reason to change. """ food_bowl = 10 class Cat: def __init__(self, name: str): self.name = name self.food_level = 30 self.cleanliness_level = 50 def meow(self): print("meow") def eat(self): ...
""" The Single Responsibility Principle A class should have one, and only one, reason to change. """ food_bowl = 10 class Cat: def __init__(self, name: str): self.name = name self.food_level = 30 self.cleanliness_level = 50 def meow(self): print('meow') def eat(self): ...
class Solution: def maxProfit(self, prices: List[int]) -> int: i = 0 profit = 0 flag = 0 while i<(len(prices)-1): if prices[i] < prices[i+1] and flag==0: profit -= prices[i] flag = 1 elif prices[i] > prices[i+1] and flag==1: ...
class Solution: def max_profit(self, prices: List[int]) -> int: i = 0 profit = 0 flag = 0 while i < len(prices) - 1: if prices[i] < prices[i + 1] and flag == 0: profit -= prices[i] flag = 1 elif prices[i] > prices[i + 1] and fl...
#List slicing my_list = [0,1,2,3,4,5,6,7,8,9] print("list = ",my_list) print("my_list[0:]",my_list[0:]) print("my_list[:]",my_list[:]) print("my_list[:-1]",my_list[:-1]) print("my_list[1:5]",my_list[1:5]) #list(start:end:step) print("my_list[1::3]",my_list[1::3]) print("my_list[-1:1:-1]",my_list[-1:1:-1]) sample_ur...
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print('list = ', my_list) print('my_list[0:]', my_list[0:]) print('my_list[:]', my_list[:]) print('my_list[:-1]', my_list[:-1]) print('my_list[1:5]', my_list[1:5]) print('my_list[1::3]', my_list[1::3]) print('my_list[-1:1:-1]', my_list[-1:1:-1]) sample_url = 'https://mydomain.co...
""" This script is used for course notes. Author: Erick Marin Date: 10/11/2020 """ # `format` method with curly brackets place holder firstname = "Manny" number = len(firstname) * 3 print("Hello {}, your lucky number is {}".format(firstname, number)) print("Your lucky number is {number}, {firstname}.".format( fi...
""" This script is used for course notes. Author: Erick Marin Date: 10/11/2020 """ firstname = 'Manny' number = len(firstname) * 3 print('Hello {}, your lucky number is {}'.format(firstname, number)) print('Your lucky number is {number}, {firstname}.'.format(firstname=firstname, number=len(firstname) * 3)) def studen...
# # @lc app=leetcode.cn id=253 lang=python3 # # [253] meeting-rooms-ii # None # @lc code=end
None
''' Assigning values to the grid The grid will look like this: 0,0 | 0,1 | 0,2 | 0,3 | 0,4 | 0,5 | 0,6 1,0 | 1,1 | 1,2 | 1,3 | 1,4 | 1,5 | 1,6 2,0 | 2,1 | 2,2 | 2,3 | 2,4 | 2,5 | 2,6 3,0 | 3,1 | 3,2 | 3,3 | 3,4 | 3,5 | 3,6 4,0 | 4,1 | 4,2 | 4,3 | 4,4 | 4,5 | 4,6 5,0 | 5,1 | 5,2 | 5,3 | 5,4 | 5,5 | 5,6 ''' N...
""" Assigning values to the grid The grid will look like this: 0,0 | 0,1 | 0,2 | 0,3 | 0,4 | 0,5 | 0,6 1,0 | 1,1 | 1,2 | 1,3 | 1,4 | 1,5 | 1,6 2,0 | 2,1 | 2,2 | 2,3 | 2,4 | 2,5 | 2,6 3,0 | 3,1 | 3,2 | 3,3 | 3,4 | 3,5 | 3,6 4,0 | 4,1 | 4,2 | 4,3 | 4,4 | 4,5 | 4,6 5,0 | 5,1 | 5,2 | 5,3 | 5,4 | 5,5 | 5,6 """ (...
__version__ = '0.1.2' def version_info(): return tuple([int(i) for i in __version__.split('.')])
__version__ = '0.1.2' def version_info(): return tuple([int(i) for i in __version__.split('.')])
class ObservationModel(object): def __init__(self): self._observation_matrix = dict() def __str__(self): str = '' for k, v in self._observation_matrix.items(): str += '{}:{}\n'.format(k, v) return str @property def observation_matrix(self): retur...
class Observationmodel(object): def __init__(self): self._observation_matrix = dict() def __str__(self): str = '' for (k, v) in self._observation_matrix.items(): str += '{}:{}\n'.format(k, v) return str @property def observation_matrix(self): return...
set1 = set() set1.add(1) set2 = {1, 2, 3} print(set1) print(set1 | set2) print(set1 & set2)
set1 = set() set1.add(1) set2 = {1, 2, 3} print(set1) print(set1 | set2) print(set1 & set2)
youtubePlaylists = [ "PLxAzjHbHvNcUvcajBsGW2VI6fyIWa4sVl", # ProbablePrime "PLjux6EKYfu0045V_-s5l9biu55fzbWFAO", # Deloious Jax "PLoAvz0_U4_3wuXXrl8IbyJIYZFdeIgyHm", # Frooxius "PLSa764cPPsV9saKq_9Sb_izfwgI9cY-8u", # CuriosVR.. coffee "PLWhfKbDgR4zD-o31sgHqesncjt49Jxou7", # AMoB tutorials "...
youtube_playlists = ['PLxAzjHbHvNcUvcajBsGW2VI6fyIWa4sVl', 'PLjux6EKYfu0045V_-s5l9biu55fzbWFAO', 'PLoAvz0_U4_3wuXXrl8IbyJIYZFdeIgyHm', 'PLSa764cPPsV9saKq_9Sb_izfwgI9cY-8u', 'PLWhfKbDgR4zD-o31sgHqesncjt49Jxou7', 'PLFYjCoKo3ivA67rj20lIsmUG2AQoavYHG', 'PLwitPMCdx0xu2KQ7vwoccaPUp-31qfdjK', 'PLSB-6Ok84ZR0Ow4ziNWuFLGTgf3M1JD...
def rotate(list, no_rotation): return list[no_rotation:] + list[:no_rotation] def message_processor(message): message = message.upper() message = message.replace(" ", "") return message def select_rotor(rotor_model): rotor_i_list = ['E','K','M','F','L','G','D','Q','V','Z','N','T','O','W','Y','...
def rotate(list, no_rotation): return list[no_rotation:] + list[:no_rotation] def message_processor(message): message = message.upper() message = message.replace(' ', '') return message def select_rotor(rotor_model): rotor_i_list = ['E', 'K', 'M', 'F', 'L', 'G', 'D', 'Q', 'V', 'Z', 'N', 'T', 'O', ...
x=int(input()) count=0 for i in range(1,x): if(x%i==0): count+=1 if(count!=2): print("yes") else: print("no")
x = int(input()) count = 0 for i in range(1, x): if x % i == 0: count += 1 if count != 2: print('yes') else: print('no')
print("Hello world!"); print("Hello everybody!"); print("Hello!") print("Hello my dear friend!") print("Glad to see you!")
print('Hello world!') print('Hello everybody!') print('Hello!') print('Hello my dear friend!') print('Glad to see you!')
# https://cses.fi/problemset/task/1092 n = int(input()) if n % 4 in [1, 2]: print('NO') exit() s1, s2 = '', '' if n % 4 == 0: x = n // 2 + 1 for i in range(1, x, 2): s1 += str(i) + ' ' + str(n - i + 1) + ' ' s2 += str(i + 1) + ' ' + str(n - i) + ' ' else: s1 = '1 2' s2 = '3' ...
n = int(input()) if n % 4 in [1, 2]: print('NO') exit() (s1, s2) = ('', '') if n % 4 == 0: x = n // 2 + 1 for i in range(1, x, 2): s1 += str(i) + ' ' + str(n - i + 1) + ' ' s2 += str(i + 1) + ' ' + str(n - i) + ' ' else: s1 = '1 2' s2 = '3' for i in range(4, n, 4): s1...
"""Constraint Exceptions.""" class MissingConstraintColumnError(Exception): """Error to use when constraint is provided a table with missing columns.""" class MultipleConstraintsErrors(Exception): """Error used to represent a list of constraint errors."""
"""Constraint Exceptions.""" class Missingconstraintcolumnerror(Exception): """Error to use when constraint is provided a table with missing columns.""" class Multipleconstraintserrors(Exception): """Error used to represent a list of constraint errors."""
def byte_to_signed_int(x): """ Returns a signed integer from the byte :param x: Byte """ if (x & 0x80) >> 7 == 1: return -((x-1) ^ 0xff) else: return x def int_to_signed_byte(x): """ Converts the signed integer to a 2s-complement byte. """ if x > 0: re...
def byte_to_signed_int(x): """ Returns a signed integer from the byte :param x: Byte """ if (x & 128) >> 7 == 1: return -(x - 1 ^ 255) else: return x def int_to_signed_byte(x): """ Converts the signed integer to a 2s-complement byte. """ if x > 0: return...
#### #### ## # Project PythonTools ## # Copyright (C) 2002 Andreas Heger All rights reserved ## # Author: Andreas Heger <heger@ebi.ac.uk> ## # $Id: IntervallsWeighted.py 2784 2009-09-10 11:41:14Z andreas $ ## ## #### #### """ IntervallsWeigted.py - working with weigted intervals ========================================...
""" IntervallsWeigted.py - working with weigted intervals ===================================================== Work with weighted invervalls. A weighted intervall is a tuple of the form (from,to,weight). Funktions in this module take an optional function parameter object fct, that will give the weight if two interva...
# -*- coding: utf-8 -*- """ Student Do: Grocery List. This script showcases basic operations of Python Lists to help Sally organize her grocery shopping list. """ # Create a list of groceries print("My list of groceries:") groceries = ["water", "butter", "eggs", "apples", "cinnamon", "sugar", "milk"] print(groceries)...
""" Student Do: Grocery List. This script showcases basic operations of Python Lists to help Sally organize her grocery shopping list. """ print('My list of groceries:') groceries = ['water', 'butter', 'eggs', 'apples', 'cinnamon', 'sugar', 'milk'] print(groceries) print() print('What are my first two items on the lis...
TEST = "test_input.txt" INPUT = "input.txt" def read_file(filename): return open(filename, "r").readlines() def process_task_1(data): return len(data) def process_task_2(data): return len(data) def test(): data = read_file(TEST) assert process_task_1(data) == 0 assert process_task_2(data...
test = 'test_input.txt' input = 'input.txt' def read_file(filename): return open(filename, 'r').readlines() def process_task_1(data): return len(data) def process_task_2(data): return len(data) def test(): data = read_file(TEST) assert process_task_1(data) == 0 assert process_task_2(data) ==...
"""Elementary Rules of Usage. --- layout: post source: Strunk & White source_url: ??? title: Elementary Rules of Usage date: 2014-06-10 12:31:19 categories: writing --- Strunk & White say: 1. Form the possessive singular of nouns by adding 's. 2. In a series of three or more terms with a conjunctio...
"""Elementary Rules of Usage. --- layout: post source: Strunk & White source_url: ??? title: Elementary Rules of Usage date: 2014-06-10 12:31:19 categories: writing --- Strunk & White say: 1. Form the possessive singular of nouns by adding 's. 2. In a series of three or more terms with a conjunctio...
#Enter a number and count its digits. n=int(input("Enter a no.:")) count=0 a=0 ans=0 while n!=0: n=n//10 count=count+1 print("Total no. of digits in the number=",count)
n = int(input('Enter a no.:')) count = 0 a = 0 ans = 0 while n != 0: n = n // 10 count = count + 1 print('Total no. of digits in the number=', count)
""" Config data for training and validation """ # Paths to datasets IMAGE_DATASETS = { # Training & Validation datasets "auckland_urban_2017_0.075m": { "s3_uri": "s3://linz-raster-data-store", "path": "aerial-imagery/auckland_urban_2017_0.075m", "file_type": "tif", }, "waikato...
""" Config data for training and validation """ image_datasets = {'auckland_urban_2017_0.075m': {'s3_uri': 's3://linz-raster-data-store', 'path': 'aerial-imagery/auckland_urban_2017_0.075m', 'file_type': 'tif'}, 'waikato_rural_2017-19_0.3m': {'s3_uri': 's3://linz-raster-data-store', 'path': 'aerial-imagery/waikato_ru...
""" File: caesar.py ------------------------------ This program demonstrates the idea of caesar cipher. Users will be asked to input a number to produce shifted ALPHABET as the cipher table. After that, any strings typed in will be encrypted. """ # This constant shows the original order of alphabetic sequence ALPHABE...
""" File: caesar.py ------------------------------ This program demonstrates the idea of caesar cipher. Users will be asked to input a number to produce shifted ALPHABET as the cipher table. After that, any strings typed in will be encrypted. """ alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def main(): """ The prog...
def tambah(angka1: float, angka2: float) -> float: """ hasil dari pertambahan antara angka1 dan angka2 >>> tambah(3.0, 2.0) 5.0 """ return angka1 + angka2 def kurang(angka1: float, angka2: float) -> float: """ hasil dari pengurangan antara angka1 dan angka2 >>> kurang(3.0, 2.0) ...
def tambah(angka1: float, angka2: float) -> float: """ hasil dari pertambahan antara angka1 dan angka2 >>> tambah(3.0, 2.0) 5.0 """ return angka1 + angka2 def kurang(angka1: float, angka2: float) -> float: """ hasil dari pengurangan antara angka1 dan angka2 >>> kurang(3.0, 2.0) ...
class InningsStats: def __init__(self, cursor): self.cursor = cursor def insert(self, match_id, innings_num, runs, wickets, overs, batting_team_id, bowling_team_id): sql = """INSERT INTO innings_stats VALUES(%s, %s, %s, %s, %s, %s, %s)""" self.cursor.execute(sql, (match_id, innings_num,...
class Inningsstats: def __init__(self, cursor): self.cursor = cursor def insert(self, match_id, innings_num, runs, wickets, overs, batting_team_id, bowling_team_id): sql = 'INSERT INTO innings_stats VALUES(%s, %s, %s, %s, %s, %s, %s)' self.cursor.execute(sql, (match_id, innings_num, ru...
# This module defines strings containing XPM data that matches # Golly's built-in icons (see the XPM data in wxalgos.cpp). # The strings are used by icon-importer.py and icon_exporter.py. circles = ''' XPM /* width height num_colors chars_per_pixel */ "31 31 5 1" /* colors */ ". c #000000" "B c #404040" "C c #808080" ...
circles = '\nXPM\n/* width height num_colors chars_per_pixel */\n"31 31 5 1"\n/* colors */\n". c #000000"\n"B c #404040"\n"C c #808080"\n"D c #C0C0C0"\n"E c #FFFFFF"\n/* icon for state 1 */\n"..............................."\n"..............................."\n"..........BCDEEEEEDCB.........."\n".........CEEEEEEEEEEEC....
#!/usr/bin/env python # -*- coding: utf-8 -*- def is_valid(s: str) -> bool: bracket_pairs = {')': '(', '}': '{', ']': '['} stack = [] for c in s: if c in bracket_pairs: if not stack or stack.pop() != bracket_pairs[c]: return False else: stack.append(...
def is_valid(s: str) -> bool: bracket_pairs = {')': '(', '}': '{', ']': '['} stack = [] for c in s: if c in bracket_pairs: if not stack or stack.pop() != bracket_pairs[c]: return False else: stack.append(c) return not stack
""" Program: multiway.py Author: Sharyl Hammer Date: October 9, 2017 """ number = int(input("Enter the numeric grade:")) if number >= 0 and number <= 100: if number > 89: letter = 'A' print("The letter grade is", letter) else: print("Error: grade must be between 100 and 0") ...
""" Program: multiway.py Author: Sharyl Hammer Date: October 9, 2017 """ number = int(input('Enter the numeric grade:')) if number >= 0 and number <= 100: if number > 89: letter = 'A' print('The letter grade is', letter) else: print('Error: grade must be between 100 and 0')
####### Modules of SSS dataset ####### def euler_to_rotation(euler): ex = euler[0] ey = euler[1] ez = euler[2] rx = np.array([[1,0,0],[0,np.cos(ex),-1*np.sin(ex)],[0,np.sin(ex),np.cos(ex)]]) ry = np.array([[np.cos(ey),0,np.sin(ey)],[0,1,0],[-1*np.sin(ey),0,np.cos(ey)]]) rz = np.array([[np.cos(e...
def euler_to_rotation(euler): ex = euler[0] ey = euler[1] ez = euler[2] rx = np.array([[1, 0, 0], [0, np.cos(ex), -1 * np.sin(ex)], [0, np.sin(ex), np.cos(ex)]]) ry = np.array([[np.cos(ey), 0, np.sin(ey)], [0, 1, 0], [-1 * np.sin(ey), 0, np.cos(ey)]]) rz = np.array([[np.cos(ez), -1 * np.sin(ez),...
__init__ = ["SpectrographUI_savejsondict","SpectrographUI_loadjsondict"] def SpectrographUI_savejsondict(self,jdict): '''Autogenerated code from ui's make/awk trick.''' jdict['compLampSwitch'] = self.compLampSwitch.isChecked() jdict['flatLampSwitch'] = self.flatLampSwitch.isChecked() jdict['heater1Switch'] ...
__init__ = ['SpectrographUI_savejsondict', 'SpectrographUI_loadjsondict'] def spectrograph_ui_savejsondict(self, jdict): """Autogenerated code from ui's make/awk trick.""" jdict['compLampSwitch'] = self.compLampSwitch.isChecked() jdict['flatLampSwitch'] = self.flatLampSwitch.isChecked() jdict['heater1S...
"""Contains courses, lessons, sections and tasks and all the things that directly use them This does not handle script execution or the AJAXy stuff that tasks do, see the "tasks" app for that. """
"""Contains courses, lessons, sections and tasks and all the things that directly use them This does not handle script execution or the AJAXy stuff that tasks do, see the "tasks" app for that. """
X_threads = 128*8 Y_threads = 1 Invoc_count = 9 start_index = 95 end_index = 107 src_list = [] SHARED_MEM_USE = False total_shared_mem_size = 1024 domi_list = [89] domi_val = [0]
x_threads = 128 * 8 y_threads = 1 invoc_count = 9 start_index = 95 end_index = 107 src_list = [] shared_mem_use = False total_shared_mem_size = 1024 domi_list = [89] domi_val = [0]
#encoding:utf-8 subreddit = 'crackwatch' t_channel = '@r_crackwatch' def send_post(submission, r2t): return r2t.send_simple(submission)
subreddit = 'crackwatch' t_channel = '@r_crackwatch' def send_post(submission, r2t): return r2t.send_simple(submission)
# -*- coding: utf-8 -*- def implicit_scope(func): def wrapper(*args): args[0].scope.append({}) ans = func(*args) args[0].scope.pop() return ans return wrapper class Solution(object): def __init__(self): self.scope = [{}] @implicit_scope def evaluate(self,...
def implicit_scope(func): def wrapper(*args): args[0].scope.append({}) ans = func(*args) args[0].scope.pop() return ans return wrapper class Solution(object): def __init__(self): self.scope = [{}] @implicit_scope def evaluate(self, expression): if ...
# coding: utf-8 ''' Package exceptions. ''' class NoSuchContent(Exception): pass class ContentSyntaxError(Exception): pass
""" Package exceptions. """ class Nosuchcontent(Exception): pass class Contentsyntaxerror(Exception): pass
old_SYMBOL_INFO = _SYMBOL_INFO class _SYMBOL_INFO(old_SYMBOL_INFO): @property def tag(self): return SymTagEnum.mapper[self.Tag]
old_symbol_info = _SYMBOL_INFO class _Symbol_Info(old_SYMBOL_INFO): @property def tag(self): return SymTagEnum.mapper[self.Tag]
class Solution: def largestTriangleArea(self, points: List[List[int]]) -> float: result = 0 lenList = len(points) for i in range(lenList-2): x1, y1 = points[i] for j in range(lenList-1): x2, y2 = points[j] for k in range(lenList): ...
class Solution: def largest_triangle_area(self, points: List[List[int]]) -> float: result = 0 len_list = len(points) for i in range(lenList - 2): (x1, y1) = points[i] for j in range(lenList - 1): (x2, y2) = points[j] for k in range(len...
""" These are junk terms that commonly occur: Variations: parentheses/brackets, uppercase, lowercase, or Title Style. And with spaces or underscores Ex: 'song' can come as: [epilepsy warning], [EPILEPSY WARNING], [Epilepsy Warning] [epilepsy_warning], [EPILEPSY_WARNING], [Epilepsy_Warning] (epilepsy warnin...
""" These are junk terms that commonly occur: Variations: parentheses/brackets, uppercase, lowercase, or Title Style. And with spaces or underscores Ex: 'song' can come as: [epilepsy warning], [EPILEPSY WARNING], [Epilepsy Warning] [epilepsy_warning], [EPILEPSY_WARNING], [Epilepsy_Warning] (epilepsy warnin...
__all__ = [ 'AutoInitAndCloseable', 'Disposable', 'NoReentrantContext', 'DisposableContext', ] class AutoInitAndCloseable(object): """ Classes with :meth:`init()` to initialize its internal states, and also :meth:`close()` to destroy these states. The :meth:`init()` method can be repe...
__all__ = ['AutoInitAndCloseable', 'Disposable', 'NoReentrantContext', 'DisposableContext'] class Autoinitandcloseable(object): """ Classes with :meth:`init()` to initialize its internal states, and also :meth:`close()` to destroy these states. The :meth:`init()` method can be repeatedly called, which...
# Custom Exceptions class Error(Exception): """Base class for other exceptions """ pass class OptionOutOfRange(Error): """Raised when option selected from menu is out of range """ pass class DBConnectionError(Error): """Raised when option selected from menu is out of range """ pass...
class Error(Exception): """Base class for other exceptions """ pass class Optionoutofrange(Error): """Raised when option selected from menu is out of range """ pass class Dbconnectionerror(Error): """Raised when option selected from menu is out of range """ pass class Toomanyloans...
__all__ = ["Node", "AST", "Value", "Concatenation", "Decision", "Clini"] class Node: """Base class for all nodes of regexp AST.""" def __init__(self, value: chr, left: 'Node', right: 'Node'): self.__value: chr = value self.lchild: Node = left self.rchild: Node = right def childre...
__all__ = ['Node', 'AST', 'Value', 'Concatenation', 'Decision', 'Clini'] class Node: """Base class for all nodes of regexp AST.""" def __init__(self, value: chr, left: 'Node', right: 'Node'): self.__value: chr = value self.lchild: Node = left self.rchild: Node = right def children...
""" coding: utf-8 Created on 13/11/2020 @author: github.com/edrmonteiro From: Hackerrank challenges Language: Python Title: Count Triplets You are given an array and you need to find number of tripets of indices such that the elements at those indices are in geometric progression for a given common ratio and . Fo...
""" coding: utf-8 Created on 13/11/2020 @author: github.com/edrmonteiro From: Hackerrank challenges Language: Python Title: Count Triplets You are given an array and you need to find number of tripets of indices such that the elements at those indices are in geometric progression for a given common ratio and . Fo...
class ProfileError(Exception): def __init__(self, code: str): self.code = code class ProfileNotFoundError(ProfileError): def __init__(self, code: str): super().__init__(code) def __str__(self): return f"Profile {self.code} not found" class ProfileAlreadyExistsError(ProfileError)...
class Profileerror(Exception): def __init__(self, code: str): self.code = code class Profilenotfounderror(ProfileError): def __init__(self, code: str): super().__init__(code) def __str__(self): return f'Profile {self.code} not found' class Profilealreadyexistserror(ProfileError)...
class GotoAckPacket: def __init__(self): self.type = "GOTOACK" self.time = 0 def write(self, writer): writer.writeInt32(self.time) def read(self, reader): self.time = reader.readInt32()
class Gotoackpacket: def __init__(self): self.type = 'GOTOACK' self.time = 0 def write(self, writer): writer.writeInt32(self.time) def read(self, reader): self.time = reader.readInt32()