content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class vehicleStatus: def __init__(self): self.position = [0, 0] self.direction = 1 self.receptive_radius = 1 self.communication_dis = 5 ACTION_MAP = { 0: [0, 0], 1: [-1, 0], 2: [0, 1], 3: [1, 0], 4: [0, -1], } ACTION_SPACE = ACTION_MAP.__len__() ACTION_MAP_I...
class Vehiclestatus: def __init__(self): self.position = [0, 0] self.direction = 1 self.receptive_radius = 1 self.communication_dis = 5 action_map = {0: [0, 0], 1: [-1, 0], 2: [0, 1], 3: [1, 0], 4: [0, -1]} action_space = ACTION_MAP.__len__() action_map_inv = dict([(tuple(value), ke...
class IllegalCountryCodeException(Exception): def __init__(self, message): super(IllegalCountryCodeException, self).__init__(message)
class Illegalcountrycodeexception(Exception): def __init__(self, message): super(IllegalCountryCodeException, self).__init__(message)
"""705. Design HashSet https://leetcode.com/problems/design-hashset/ Design a HashSet without using any built-in hash table libraries. Implement MyHashSet class: void add(key) Inserts the value key into the HashSet. bool contains(key) Returns whether the value key exists in the HashSet or not. void remove(key) Remov...
"""705. Design HashSet https://leetcode.com/problems/design-hashset/ Design a HashSet without using any built-in hash table libraries. Implement MyHashSet class: void add(key) Inserts the value key into the HashSet. bool contains(key) Returns whether the value key exists in the HashSet or not. void remove(key) Remov...
class Cheat: def __init__(self, name: str): self.name = name self.is_running = False def set_is_running(self, is_running: bool): self.is_running = is_running
class Cheat: def __init__(self, name: str): self.name = name self.is_running = False def set_is_running(self, is_running: bool): self.is_running = is_running
''' 08 - Simple scatter plot Scatter are a bi-variate visualization technique. They plot each record in the data as a point. The location of each point is determined by the value of two variables: the first variable determines the distance along the x-axis and the second variable determines the height along the...
""" 08 - Simple scatter plot Scatter are a bi-variate visualization technique. They plot each record in the data as a point. The location of each point is determined by the value of two variables: the first variable determines the distance along the x-axis and the second variable determines the height along the...
class BaseReward(): def __init__(self): pass def compute(self, distance, done): return 1 def __repr__(self): return self.__str__() def __str__(self): return "(Reward function D->X)" class ConstantReward(BaseReward): def __init__(self): """ This functio...
class Basereward: def __init__(self): pass def compute(self, distance, done): return 1 def __repr__(self): return self.__str__() def __str__(self): return '(Reward function D->X)' class Constantreward(BaseReward): def __init__(self): """ This function re...
list = ["boat", "Dadtrough", "dogpaddle", "r%ace /!@# ca%r", "H!i"] reflection = "" badchar = " !@#$%^&*()/~|" for examples in list: print("Input:", examples) for char in badchar: examples = examples.replace(char, "") cleanexamples = examples.replace(char, "") examples = examples.lower...
list = ['boat', 'Dadtrough', 'dogpaddle', 'r%ace /!@# ca%r', 'H!i'] reflection = '' badchar = ' !@#$%^&*()/~|' for examples in list: print('Input:', examples) for char in badchar: examples = examples.replace(char, '') cleanexamples = examples.replace(char, '') examples = examples.lower()...
class DynamicResourceExtensionConverter(TypeConverter): """ Converts from parsed XAML to System.Windows.DynamicResourceExtension and supports dynamic resource references made from XAML. DynamicResourceExtensionConverter() """ def CanConvertTo(self,*__args): """ CanConvertTo(self: DynamicResourceExt...
class Dynamicresourceextensionconverter(TypeConverter): """ Converts from parsed XAML to System.Windows.DynamicResourceExtension and supports dynamic resource references made from XAML. DynamicResourceExtensionConverter() """ def can_convert_to(self, *__args): """ CanConvertTo(self: DynamicRes...
""" input: a valid roman numeral between 1, 3999 output return its integer equivalent key words/phrases: every roman numeral contains the chars ('I', 'V', 'X', 'L', 'C', 'D', 'M') example: iii -> 3 key operation: Given an input string, parse the string and return its integer equivalent simplest version: s = 'I' -> 1...
""" input: a valid roman numeral between 1, 3999 output return its integer equivalent key words/phrases: every roman numeral contains the chars ('I', 'V', 'X', 'L', 'C', 'D', 'M') example: iii -> 3 key operation: Given an input string, parse the string and return its integer equivalent simplest version: s = 'I' -> 1...
# -------------- # Code starts here class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio'] class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes'] new_class= class_1 + class_2 new_class.append("Peter Warden") new_class.remove("Carla Gentry") print(new_class) # Code ends here # --------...
class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio'] class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes'] new_class = class_1 + class_2 new_class.append('Peter Warden') new_class.remove('Carla Gentry') print(new_class) courses = {'Math': 65, 'English': 70, 'History': 80, 'French': 70...
""" # What is modules in python? break down the entire code in smaller packages or modules for easy understanding and debugging, that can reusable for the future projects without copy code from that, just use as package (import and use it) """ def hello(): print("Hello", __name__) print("How ar...
""" # What is modules in python? break down the entire code in smaller packages or modules for easy understanding and debugging, that can reusable for the future projects without copy code from that, just use as package (import and use it) """ def hello(): print('Hello', __name__) print('How are you ?'...
class TwoSum: def __init__(self): self.nums = {} def add(self, number): self.nums[number] = self.nums.get(number, 0) + 1 def find(self, value): for num in self.nums: if value - num in self.nums and (num != value - num or self.nums[num] > 1): return True...
class Twosum: def __init__(self): self.nums = {} def add(self, number): self.nums[number] = self.nums.get(number, 0) + 1 def find(self, value): for num in self.nums: if value - num in self.nums and (num != value - num or self.nums[num] > 1): return True...
# Copyright 2021 The XLS Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
""" This module contains build macros for XLS. """ load('//xls/build_rules:xls_config_rules.bzl', 'enable_generated_file_wrapper') load('//xls/build_rules:xls_rules.bzl', 'get_xls_dslx_verilog_generated_files', 'xls_dslx_verilog') def xls_dslx_verilog_macro(name, dep, ir_conv_args={}, opt_ir_args={}, codegen_args={}, ...
class APIException(Exception): pass class KeyboardException(Exception): pass
class Apiexception(Exception): pass class Keyboardexception(Exception): pass
## ## # File auto-generated against equivalent DynamicSerialize Java class class ServerMsg(object): def __init__(self): self.message = None def getMessage(self): return self.message def setMessage(self, message): self.message = message
class Servermsg(object): def __init__(self): self.message = None def get_message(self): return self.message def set_message(self, message): self.message = message
raw_data = nr.random.normal(10, 1, 100) with tf.session() as sess: for i in range(len(raw_data)): curr_avg = sess.run(update_avg, feed_dict = {curr_value:raw_data[i]} )
raw_data = nr.random.normal(10, 1, 100) with tf.session() as sess: for i in range(len(raw_data)): curr_avg = sess.run(update_avg, feed_dict={curr_value: raw_data[i]})
# Author: btjanaka (Bryon Tjanaka) # Problem: (HackerRank) string-construction # Title: String Construction # Link: https://www.hackerrank.com/challenges/string-construction/problem # Idea: Since you can copy any substring at no charge, you can just copy single # letters that you previously purchased. Thus, the cost is...
for _ in range(int(input())): print(len(set(input().strip())))
class Solution: def spiralOrder(self, matrix): if matrix == []: return [] startRow = startCol = 0 endRow = len(matrix) - 1 endCol = len(matrix[0]) - 1 final_array = [] while startRow <= endRow and startCol <= endCol: ...
class Solution: def spiral_order(self, matrix): if matrix == []: return [] start_row = start_col = 0 end_row = len(matrix) - 1 end_col = len(matrix[0]) - 1 final_array = [] while startRow <= endRow and startCol <= endCol: pointer_a = startCol ...
class Message: def __init__(self, data_dict=None, msg_id=-1, sender_id=-1, sender_ip=-1, msg="", verbose=False): if data_dict == None: if verbose: print(f"Created message sent from id: {sender_id}, with id {msg_id}") self.message_id = msg_id self.sender_...
class Message: def __init__(self, data_dict=None, msg_id=-1, sender_id=-1, sender_ip=-1, msg='', verbose=False): if data_dict == None: if verbose: print(f'Created message sent from id: {sender_id}, with id {msg_id}') self.message_id = msg_id self.sender_i...
def visitor(visitor_class: object): def visited(self, obj: object): # call visitor obj.__getattribute__("visited_" + visitor_class.__name__)(self) setattr(visitor_class, "visit", visited) return visitor_class
def visitor(visitor_class: object): def visited(self, obj: object): obj.__getattribute__('visited_' + visitor_class.__name__)(self) setattr(visitor_class, 'visit', visited) return visitor_class
# A closure in Python is said to occur # when a nested function references # a value in its enclosing scope. # The whole point here is that it remembers the value def A(x): def B(): print(x) return B A(7)()
def a(x): def b(): print(x) return B a(7)()
class Solution: def accountsMerge(self, acconts: List[List[str]]) -> List[List[str]]: n = len(acconts) pos = 0 emailList = {} emailList2 = [] for accont in acconts: for email in accont[1:]: if email not in emailList: em...
class Solution: def accounts_merge(self, acconts: List[List[str]]) -> List[List[str]]: n = len(acconts) pos = 0 email_list = {} email_list2 = [] for accont in acconts: for email in accont[1:]: if email not in emailList: emailLi...
#Language:python #ID:52542 #QLink:https://quera.org/problemset/52542/ #Author:Amirkhaksar groups = int(input()) members =input() member_list = member_list = members.split() for i in member_list: number =int(i) if number <= 3: print("*" * number) else: print("*")
groups = int(input()) members = input() member_list = member_list = members.split() for i in member_list: number = int(i) if number <= 3: print('*' * number) else: print('*')
f_txt = open("ori.txt", "r") f_srt = open("converted.srt", "w") cnt = 1 line = f_txt.readline() while True: next_line = f_txt.readline() start_time = line[0:8] if not next_line: start_time_sec = int(line[6:8]) start_time_mnt = int(line[3:5]) start_time_hr = int(line[0:2]) e...
f_txt = open('ori.txt', 'r') f_srt = open('converted.srt', 'w') cnt = 1 line = f_txt.readline() while True: next_line = f_txt.readline() start_time = line[0:8] if not next_line: start_time_sec = int(line[6:8]) start_time_mnt = int(line[3:5]) start_time_hr = int(line[0:2]) end...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"load_data": "00_utils.ipynb", "average_preds": "00_utils.ipynb", "get_averaged_preds": "00_utils.ipynb", "get_datablock": "01_dataset.ipynb", "get_dls": "01_dataset.ipynb"...
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'load_data': '00_utils.ipynb', 'average_preds': '00_utils.ipynb', 'get_averaged_preds': '00_utils.ipynb', 'get_datablock': '01_dataset.ipynb', 'get_dls': '01_dataset.ipynb', 'get_dls_all_in_1': '01_dataset.ipynb', 'infer_on_test_set': '02_evaluate.i...
# vFabric Administration Server API # Copyright (c) 2012 VMware, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0...
class Vfabricadministrationservererror(Exception): """Raised to indicate a failure has occurred when communicating with the vFabric Administration Server :ivar int code: the HTTP error code returned by the server :ivar list messages: the error messages, if any, returned by the server """ ...
model_name:str = 'AutoEncoder' max_view_imgs:int = 8 view_interval:int = 10 view_point_num:int = 5 lr:float = 0.001 batch_size:int = 64 encoder_nlayers:int = 4 decoder_nlayers:int = 4 def get() ->dict: hparam:dict = { "model_name":model_name, "lr":lr, "batch_size":batch_size, "enc...
model_name: str = 'AutoEncoder' max_view_imgs: int = 8 view_interval: int = 10 view_point_num: int = 5 lr: float = 0.001 batch_size: int = 64 encoder_nlayers: int = 4 decoder_nlayers: int = 4 def get() -> dict: hparam: dict = {'model_name': model_name, 'lr': lr, 'batch_size': batch_size, 'encoder_nlayers': encoder...
x1 = int(input()) y1 = int(input()) x2 = int(input()) y2 = int(input()) if ((x1 + y1) % 2 == 0) and (x2 + y2) % 2 == 0: if (y2 > y1) and (x1 + y1 - y2 <= y1) and (x2 <= x1 + y2 - y1): print("YES") else: print("NO") else: print("NO")
x1 = int(input()) y1 = int(input()) x2 = int(input()) y2 = int(input()) if (x1 + y1) % 2 == 0 and (x2 + y2) % 2 == 0: if y2 > y1 and x1 + y1 - y2 <= y1 and (x2 <= x1 + y2 - y1): print('YES') else: print('NO') else: print('NO')
# TwilioQuest version 3.1.26 # Works in: # 3.1.26 # why you no camelCase? # would be: # favoriteRobot = "Cedric" # meaningOfLife = 42 favorite_robot = "Cedric" meaning_of_life = 42
favorite_robot = 'Cedric' meaning_of_life = 42
class Workspace(object): def __init__(self, ws_str): d_num, current, geom, vp_pos, working_geom, name = self.parse_ws_line(ws_str) self.number = d_num self.name = name self.is_current = current self.geometry = DesktopGeom(*geom) self.working_geometry = WorkareaGeom(*w...
class Workspace(object): def __init__(self, ws_str): (d_num, current, geom, vp_pos, working_geom, name) = self.parse_ws_line(ws_str) self.number = d_num self.name = name self.is_current = current self.geometry = desktop_geom(*geom) self.working_geometry = workarea_ge...
#List Methods numbers = [5,2,1,7,4] numbers2 = numbers.copy() print(f"original: {numbers}") numbers.insert(0, 10) print(numbers) print("\n") numbers.pop() print(numbers) number = [2,2,4,6,3,4,6,1] uniques = [] for num in number: if num not in uniques: uniques.append(num) print(uniques)
numbers = [5, 2, 1, 7, 4] numbers2 = numbers.copy() print(f'original: {numbers}') numbers.insert(0, 10) print(numbers) print('\n') numbers.pop() print(numbers) number = [2, 2, 4, 6, 3, 4, 6, 1] uniques = [] for num in number: if num not in uniques: uniques.append(num) print(uniques)
# Datasets paths LIBRI_FS50K='/mnt/data/FedEnhance/' CHUNK_LIBRI_FS50K='/mnt/data/ChunkFedEnhance/' CHUNK_WHAM_ENH='/mnt/data/PreFedEnhance/' # Federated learning experiments log dir FED_LOG_DIR='/home/thymios/fedenhance_log/' # Cometml your key API_KEY = 'place_your_cometml_key_here'
libri_fs50_k = '/mnt/data/FedEnhance/' chunk_libri_fs50_k = '/mnt/data/ChunkFedEnhance/' chunk_wham_enh = '/mnt/data/PreFedEnhance/' fed_log_dir = '/home/thymios/fedenhance_log/' api_key = 'place_your_cometml_key_here'
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: l = len(strs) ## If there is one string if l == 1: return strs[0] ## Get the length of the first word in the list ## We will use this length to check maximum prefix lw...
class Solution: def longest_common_prefix(self, strs: List[str]) -> str: l = len(strs) if l == 1: return strs[0] lw0 = len(strs[0]) max_prefix = '' for i in range(lw0): for word in strs[1:]: if i == len(word) or strs[0][i] != word[i]: ...
# 1st solution # O(kn) time | O(kn) space # where k = 2 class Solution: def maxProfit(self, prices: List[int]) -> int: if len(prices) <= 1: return 0 n, k = len(prices), 2 profits = [prices[i + 1] - prices[i] for i in range(len(prices) - 1)] if k > len(prices) // 2: ...
class Solution: def max_profit(self, prices: List[int]) -> int: if len(prices) <= 1: return 0 (n, k) = (len(prices), 2) profits = [prices[i + 1] - prices[i] for i in range(len(prices) - 1)] if k > len(prices) // 2: return sum((x for x in profits if x > 0)) ...
"""Some cool functions to show nothing but a test""" def my_sum(a: float, b: float) -> float: """Sum of two floats Parameters ---------- a : float First value to sum b : float Second value to sum Returns ------- float The sum of ``a`` and ``b`` See also ...
"""Some cool functions to show nothing but a test""" def my_sum(a: float, b: float) -> float: """Sum of two floats Parameters ---------- a : float First value to sum b : float Second value to sum Returns ------- float The sum of ``a`` and ``b`` See also ...
''' TODO Greeting Create commandline prompt for height Create commandline prompt for weight Run calculation Look up BMI chart Print results ''' def welcome(): print('Hi welcome to the BMI calculator.') def request_height(): height = 0 return height def request_weight(): '''Commandline user input fo...
""" TODO Greeting Create commandline prompt for height Create commandline prompt for weight Run calculation Look up BMI chart Print results """ def welcome(): print('Hi welcome to the BMI calculator.') def request_height(): height = 0 return height def request_weight(): """Commandline user input for ...
OCTICON_PAINTBRUSH = """ <svg class="octicon octicon-paintbrush" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M11.134 1.535C9.722 2.562 8.16 4.057 6.889 5.312 5.8 6.387 5.041 7.401 4.575 8.294a3.745 3.745 0 00-3.227 1.054c-.43.431-.69 1.066-.86 1.657a11.982...
octicon_paintbrush = '\n<svg class="octicon octicon-paintbrush" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M11.134 1.535C9.722 2.562 8.16 4.057 6.889 5.312 5.8 6.387 5.041 7.401 4.575 8.294a3.745 3.745 0 00-3.227 1.054c-.43.431-.69 1.066-.86 1.657a11.982 1...
__author__ = 'Clement JACOB' __copyright__ = "Copyright 2013, The Python OpenGL Engine" __license__ = "Closed Source" __version__ = "0.0.1" __email__ = "clems71@gmail.com" __status__ = "Prototype" class Stats(object): drawcalls = 0 @staticmethod def clear(): Stats.drawcalls = 0 def __repr__(self)...
__author__ = 'Clement JACOB' __copyright__ = 'Copyright 2013, The Python OpenGL Engine' __license__ = 'Closed Source' __version__ = '0.0.1' __email__ = 'clems71@gmail.com' __status__ = 'Prototype' class Stats(object): drawcalls = 0 @staticmethod def clear(): Stats.drawcalls = 0 def __repr__(s...
class TogglClientException(Exception): pass class ArquivoCOnfiguracaoNaoEncontrado(TogglClientException): pass class TarefaAtivaException(TogglClientException): pass
class Togglclientexception(Exception): pass class Arquivoconfiguracaonaoencontrado(TogglClientException): pass class Tarefaativaexception(TogglClientException): pass
class Cart: def __init__(self): self.__list_of_items = [] def add_item_to_cart(self, item): self.__list_of_items.append(item) def get_items_in_cart(self): return self.__list_of_items
class Cart: def __init__(self): self.__list_of_items = [] def add_item_to_cart(self, item): self.__list_of_items.append(item) def get_items_in_cart(self): return self.__list_of_items
hours = int(input()) minutes = int(input()) add_minutes = minutes + 15 if add_minutes <= 59: hours += 0 minutes = add_minutes elif add_minutes >= 60: hours += 1 minutes = add_minutes - 60 if hours >= 24: hours = 0 if minutes < 10: print(f"{hours}:0{minutes}") else: print(f"{hours}:{minutes}...
hours = int(input()) minutes = int(input()) add_minutes = minutes + 15 if add_minutes <= 59: hours += 0 minutes = add_minutes elif add_minutes >= 60: hours += 1 minutes = add_minutes - 60 if hours >= 24: hours = 0 if minutes < 10: print(f'{hours}:0{minutes}') else: print(f'{hours}:{minutes}'...
#!/usr/bin/env python3 class DirectedEdge: def __init__(self, v, w, weight): self.v = v self.w = w self.weight = weight def fromv(self): return self.v def to(self): return self.w def getVertex(self): return (self.v, self.w) def getWeight(self): ...
class Directededge: def __init__(self, v, w, weight): self.v = v self.w = w self.weight = weight def fromv(self): return self.v def to(self): return self.w def get_vertex(self): return (self.v, self.w) def get_weight(self): return self.wei...
#Link : https://leetcode.com/problems/implement-stack-using-queues/ """ For a list = [1,2,3,4] Stack = [1 , 2 , 3 , 4] -> Top = 4 Stack.pop = 4 Queue = [1 , 2 , 3 , 4 ] -> FIFO -> First ele = 1 In order to make queue perform stack operations , we need to pop 4 i.e the last element We will be using 2 queues he...
""" For a list = [1,2,3,4] Stack = [1 , 2 , 3 , 4] -> Top = 4 Stack.pop = 4 Queue = [1 , 2 , 3 , 4 ] -> FIFO -> First ele = 1 In order to make queue perform stack operations , we need to pop 4 i.e the last element We will be using 2 queues here POP : 1) Store all the elements in q1 = [1,2,3,4] 2) Put all the ...
'''module that contains a plethora of agents and policies This module will contain a number of agents and policies that can be specified by easily in a uniform manner. This way different agents can be easily swapped out between each other. Agents ------- Agents take a state and return an action. Unfortunately, bo...
"""module that contains a plethora of agents and policies This module will contain a number of agents and policies that can be specified by easily in a uniform manner. This way different agents can be easily swapped out between each other. Agents ------- Agents take a state and return an action. Unfortunately, bo...
def prepare_data(df, split, split_valid=None, mode="train"): if mode == "train": df = split_train_test(df, split=split, split_valid=split_valid) df.rename(columns={"^BVSP": "IBOV"}, inplace=True) return df def split_train_test(df, split, split_valid=None, ascending=True): # Number of rows ...
def prepare_data(df, split, split_valid=None, mode='train'): if mode == 'train': df = split_train_test(df, split=split, split_valid=split_valid) df.rename(columns={'^BVSP': 'IBOV'}, inplace=True) return df def split_train_test(df, split, split_valid=None, ascending=True): nrows = df.shape[0] ...
#distinct powers if __name__ == '__main__': s = [] for i in range(2, 101): for j in range(2, 101): s.append(i ** j) print(len(set(s)))
if __name__ == '__main__': s = [] for i in range(2, 101): for j in range(2, 101): s.append(i ** j) print(len(set(s)))
RUN = 1 QUIT = 2 PRINT = 3 TEMPLATE = 4 LIST_SHEET = 5 BACK_TRACE=6 STEP = 7 NEXT = 8 TEST = 9 EVAL = 10 MATCH = 11 AVT = 12 LIST_TEMPLATE = 13 SET_BREAK = 14 LIST_BREAK = 15 DELETE_BREAK = 16 HELP = 100 g_runCommands = [RUN, TEMPLATE, STEP, NEXT, ...
run = 1 quit = 2 print = 3 template = 4 list_sheet = 5 back_trace = 6 step = 7 next = 8 test = 9 eval = 10 match = 11 avt = 12 list_template = 13 set_break = 14 list_break = 15 delete_break = 16 help = 100 g_run_commands = [RUN, TEMPLATE, STEP, NEXT] class Exitexception: pass
""" Profile ../profile-datasets-py/div52_zen30deg/002.py file automaticaly created by prof_gen.py script """ self["ID"] = "../profile-datasets-py/div52_zen30deg/002.py" self["Q"] = numpy.array([ 1.60776800e+00, 3.57700700e+00, 5.25388800e+00, 6.60521100e+00, 5.98130300e+00, 6.68717500e+0...
""" Profile ../profile-datasets-py/div52_zen30deg/002.py file automaticaly created by prof_gen.py script """ self['ID'] = '../profile-datasets-py/div52_zen30deg/002.py' self['Q'] = numpy.array([1.607768, 3.577007, 5.253888, 6.605211, 5.981303, 6.687175, 8.867392, 8.082855, 6.542605, 6.921747, 7.228298, 6.43...
class Msgs: cmd = 1 info = 5 namespace = 7 args = 3 kwargs = 4 class Commands: ping = 1 head = 2 get_state = 3 set_state = 4 exec_atomic_fn = 5 exec_dict_method = 6
class Msgs: cmd = 1 info = 5 namespace = 7 args = 3 kwargs = 4 class Commands: ping = 1 head = 2 get_state = 3 set_state = 4 exec_atomic_fn = 5 exec_dict_method = 6
# ====================================================================== # Amphipod # Advent of Code 2021 Day 23 -- Eric Wastl -- https://adventofcode.com # # Python implementation by Dr. Dean Earl Wright III # ====================================================================== # =================================...
"""Room for the Advent of Code 2021 Day 23 puzzle""" class Room(object): """Object for Amphipod""" def __init__(self, doorway=None, homeroom=None, contents=None): self.doorway = 0 self.homeroom = homeroom self.contents = [] if doorway: self.doorway = doorway ...
''' @author: l4zyc0d3r People who are happy makes other happy. I am gonna finish it slowly but definitely.cdt ''' class Solution: def summaryRanges(self, N: List[int]) -> List[str]: if not N: return N ans,i,l=[],0,len(N) while i<l: j=i+1 while j<l and N[j]-N[j-1]==1:...
""" @author: l4zyc0d3r People who are happy makes other happy. I am gonna finish it slowly but definitely.cdt """ class Solution: def summary_ranges(self, N: List[int]) -> List[str]: if not N: return N (ans, i, l) = ([], 0, len(N)) while i < l: j = i + 1 ...
""" Space : O(1) Time : O(n) """ class Solution: def judgeCircle(self, moves: str) -> bool: x, y = 0, 0 n = len(moves) if n == 0: return True for i in moves: if i == "L": x -= 1 elif i == "R": x += 1 ...
""" Space : O(1) Time : O(n) """ class Solution: def judge_circle(self, moves: str) -> bool: (x, y) = (0, 0) n = len(moves) if n == 0: return True for i in moves: if i == 'L': x -= 1 elif i == 'R': x += 1 ...
def _setup_codeblock_substitutions(app): for ext in [ 'sphinx-prompt', 'sphinx_substitution_extensions', ]: app.setup_extension(ext) # list of interpretable substitutions app.config.substitutions = [ ('|version|', app.config.version), ] def setup(app): _setup_co...
def _setup_codeblock_substitutions(app): for ext in ['sphinx-prompt', 'sphinx_substitution_extensions']: app.setup_extension(ext) app.config.substitutions = [('|version|', app.config.version)] def setup(app): _setup_codeblock_substitutions(app)
""" A mixin for classes all compared the same way. """ class CompareByDict(object): """A mixin for classes that should be compared by their attribute/value pairs. Useful for the Document classes. """ def __eq__(self, other): return self.__dict__ == other.__dict__ def __neq__(self, other):...
""" A mixin for classes all compared the same way. """ class Comparebydict(object): """A mixin for classes that should be compared by their attribute/value pairs. Useful for the Document classes. """ def __eq__(self, other): return self.__dict__ == other.__dict__ def __neq__(self, other):...
def test_export__ExportList__1(search_data, browser): """..export.ExportList() renders an advice if there are no exporters. The actual exporters are tested in their modules. """ browser.login('visitor') browser.open(browser.PERSONS_LIST_URL) browser.getLink('Hohmuth').click() browser.getCo...
def test_export___export_list__1(search_data, browser): """..export.ExportList() renders an advice if there are no exporters. The actual exporters are tested in their modules. """ browser.login('visitor') browser.open(browser.PERSONS_LIST_URL) browser.getLink('Hohmuth').click() browser.get...
uni = "Jacobs" #012345 #654321 Negative reverse_uni = uni[::-1] print(reverse_uni)
uni = 'Jacobs' reverse_uni = uni[::-1] print(reverse_uni)
MAJOR_COLORS = ['White', 'Red', 'Black', 'Yellow', 'Violet'] MINOR_COLORS = ["Blue", "Orange", "Green", "Brown", "Slate"] def color_pair_to_string(major_color, minor_color): return f'{major_color} {minor_color}' def get_color_from_pair_number(pair_number): zero_based_pair_number = pair_number - 1 major_index...
major_colors = ['White', 'Red', 'Black', 'Yellow', 'Violet'] minor_colors = ['Blue', 'Orange', 'Green', 'Brown', 'Slate'] def color_pair_to_string(major_color, minor_color): return f'{major_color} {minor_color}' def get_color_from_pair_number(pair_number): zero_based_pair_number = pair_number - 1 major_in...
country = input('Enter the name of your country: ') if country.lower == 'Kenya': print('so you must love kipchoge!') else: print('Your not from kenya')
country = input('Enter the name of your country: ') if country.lower == 'Kenya': print('so you must love kipchoge!') else: print('Your not from kenya')
class Source: def check_ipv4(self, ipv4): raise NotImplementedError def check_domain(self, domain): raise NotImplementedError def check_md5(self, md5): raise NotImplementedError def check_sha1(self, sha1): raise NotImplementedError def check_sha256(self, sha256): ...
class Source: def check_ipv4(self, ipv4): raise NotImplementedError def check_domain(self, domain): raise NotImplementedError def check_md5(self, md5): raise NotImplementedError def check_sha1(self, sha1): raise NotImplementedError def check_sha256(self, sha256):...
name2 = " \t\n Angela McAdoo " print (name2) name2 = name2.strip() print (name2)
name2 = ' \t\n Angela McAdoo ' print(name2) name2 = name2.strip() print(name2)
x = {1, 2, 3} x = {i for i in range(0, 10)} x = {1: 2, 3: 4} x = {**dic} x = {**dic, 4:5} x = {*l, 2, 3} x = {key : value for (key, value) in zip(keys, values)}
x = {1, 2, 3} x = {i for i in range(0, 10)} x = {1: 2, 3: 4} x = {**dic} x = {**dic, 4: 5} x = {*l, 2, 3} x = {key: value for (key, value) in zip(keys, values)}
def media(alunos): nome = str(input("\ndigite o nome do aluno: ")) flag = 0 for k in alunos.keys(): if(k == nome): M = (alunos[nome][0] + alunos[nome][1])/2 flag = 1 if flag == 0: print("aluno nao encontrado!") else: print(f"\nmedia do aluno {nome} : {...
def media(alunos): nome = str(input('\ndigite o nome do aluno: ')) flag = 0 for k in alunos.keys(): if k == nome: m = (alunos[nome][0] + alunos[nome][1]) / 2 flag = 1 if flag == 0: print('aluno nao encontrado!') else: print(f'\nmedia do aluno {nome} : ...
# Revision of some previous learning cars = ['Bugatti','Verna','BMW-M4'] for car in cars: print(car.title()+"these are my favourite cars.") print("sound of these cars are like a beast."+car.title()) print("\t list of my favourite cars.") # Finding prime numbers for prime in range(0,100,2): print(prime) #...
cars = ['Bugatti', 'Verna', 'BMW-M4'] for car in cars: print(car.title() + 'these are my favourite cars.') print('sound of these cars are like a beast.' + car.title()) print('\t list of my favourite cars.') for prime in range(0, 100, 2): print(prime) for square in range(1, 10): print(square ** 2) for cu...
# -*- coding: utf-8 -*- def pre_save_title(instance, raw, **kwargs): """Save old state to instance and setup path """ if not instance.publisher_is_draft: return page = instance.page page_languages = page.get_languages() if not instance.language in page_languages: page_languag...
def pre_save_title(instance, raw, **kwargs): """Save old state to instance and setup path """ if not instance.publisher_is_draft: return page = instance.page page_languages = page.get_languages() if not instance.language in page_languages: page_languages.append(instance.language)...
PRESETS_FILES = [ ( [ "GE63", "GE73", "GE75", "GS63", "GS73", "GS75", "GX63", "GT63", "GL63", "GP75", "GL73", ], "1.json", ), (["GS65"], "2.json"), ]
presets_files = [(['GE63', 'GE73', 'GE75', 'GS63', 'GS73', 'GS75', 'GX63', 'GT63', 'GL63', 'GP75', 'GL73'], '1.json'), (['GS65'], '2.json')]
DEFAULT_CREDENTIALS_CONFIG = "config/credentials.json" DEFAULT_AUTH_CONFIG = "config/auth.json" DEFAULT_WORKER_CONFIG = "config/worker.json" CONFIG_STORE_DEFAULT = "default" CONFIG_STORES = "stores" CONFIG_STORE_NAME = "name" CONFIG_ENDPOINT = "endpoint" CONFIG_ACCESS_KEY = "accessKey" CONFIG_SECRET_KEY = "secretKey" ...
default_credentials_config = 'config/credentials.json' default_auth_config = 'config/auth.json' default_worker_config = 'config/worker.json' config_store_default = 'default' config_stores = 'stores' config_store_name = 'name' config_endpoint = 'endpoint' config_access_key = 'accessKey' config_secret_key = 'secretKey' c...
class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ def helper(start, end): if start >= end: return s[start], s[end] = s[end], s[start] start += 1 ...
class Solution: def reverse_string(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ def helper(start, end): if start >= end: return (s[start], s[end]) = (s[end], s[start]) start += 1 ...
pkgname = "libmikmod" pkgver = "3.3.11.1" pkgrel = 0 build_style = "gnu_configure" hostmakedepends = ["pkgconf"] pkgdesc = "Mikmod module player and library" maintainer = "q66 <q66@chimera-linux.org>" license = "LGPL-2.1-or-later" url = "http://mikmod.shlomifish.org" source = f"$(SOURCEFORGE_SITE)/mikmod/{pkgname}-{pkg...
pkgname = 'libmikmod' pkgver = '3.3.11.1' pkgrel = 0 build_style = 'gnu_configure' hostmakedepends = ['pkgconf'] pkgdesc = 'Mikmod module player and library' maintainer = 'q66 <q66@chimera-linux.org>' license = 'LGPL-2.1-or-later' url = 'http://mikmod.shlomifish.org' source = f'$(SOURCEFORGE_SITE)/mikmod/{pkgname}-{pkg...
def aumentar(valor=0, taxa=0, fmt=False): res = valor + (valor * taxa/100) return moeda(res) if fmt else res def diminuir(valor=0, taxa=0, fmt=False): res = valor - (valor * taxa / 100) return moeda(res) if fmt else res def dobro(valor=0, fmt=False): res = valor * 2 return moeda(res) if fmt ...
def aumentar(valor=0, taxa=0, fmt=False): res = valor + valor * taxa / 100 return moeda(res) if fmt else res def diminuir(valor=0, taxa=0, fmt=False): res = valor - valor * taxa / 100 return moeda(res) if fmt else res def dobro(valor=0, fmt=False): res = valor * 2 return moeda(res) if fmt else...
# # Codegenerator for Dagger IDL # #!/usr/bin/python TAB_SIZE = 4 class CodeGen: def __init__(self, tmpl_filename = ""): self.__code = "" self.__seek_ptr = 0 def append(self, line): self.__code = self.__code[:self.__seek_ptr] \ + line \ + self.__code[self.__seek_ptr:] self.__se...
tab_size = 4 class Codegen: def __init__(self, tmpl_filename=''): self.__code = '' self.__seek_ptr = 0 def append(self, line): self.__code = self.__code[:self.__seek_ptr] + line + self.__code[self.__seek_ptr:] self.__seek_ptr = len(self.__code) def append_snippet(self, sn...
class ProgressManager: def __init__(self, request): self.request = request def get_progress(self, section): user = self.request.user if self.request.user.is_anonymous: read_article_ids = set(self.request.session.get('read_articles', [])) else: read_artic...
class Progressmanager: def __init__(self, request): self.request = request def get_progress(self, section): user = self.request.user if self.request.user.is_anonymous: read_article_ids = set(self.request.session.get('read_articles', [])) else: read_artic...
class Pessoa: def __init__(self, nome, idade): self.nome = nome self.idade = idade self.nome_classe = self.__class__.__name__ def falar(self): print(f'{self.nome_classe} falando ...') class Cliente(Pessoa): def comprar(self): print(f'{self.nome_classe} comprando .....
class Pessoa: def __init__(self, nome, idade): self.nome = nome self.idade = idade self.nome_classe = self.__class__.__name__ def falar(self): print(f'{self.nome_classe} falando ...') class Cliente(Pessoa): def comprar(self): print(f'{self.nome_classe} comprando ....
orders=[['34587', 'Learning Python', 'Mark Lutz', 4, 40.95], ['98762', 'Programming Python', 'Mark Lutz', 5, 56.80], ['77226', 'Head First Python', 'Paul Barry', 3, 32.95], ['88112', 'Einfuhrung in Python3', 'Bernd Klein', 3, 24.99]] output = [[0]*2]*4 for i in range (0, 4): output[i][0]=orders[i][0] outpu...
orders = [['34587', 'Learning Python', 'Mark Lutz', 4, 40.95], ['98762', 'Programming Python', 'Mark Lutz', 5, 56.8], ['77226', 'Head First Python', 'Paul Barry', 3, 32.95], ['88112', 'Einfuhrung in Python3', 'Bernd Klein', 3, 24.99]] output = [[0] * 2] * 4 for i in range(0, 4): output[i][0] = orders[i][0] outp...
""" Some format recipies """ # INPUT DATA data = [ (1000, 10), (2000, 17), (2500, 170), (2500, -170), ] # Print the header for reference print('REVENUE | PROFIT | PERCENT') # This template aligns and displays the data in the proper format TEMPLATE = '{revenue:>7,} | {profit:>+6} | {percent:>7.2%}' # ...
""" Some format recipies """ data = [(1000, 10), (2000, 17), (2500, 170), (2500, -170)] print('REVENUE | PROFIT | PERCENT') template = '{revenue:>7,} | {profit:>+6} | {percent:>7.2%}' for (revenue, profit) in data: percent = profit / revenue row = TEMPLATE.format(revenue=revenue, profit=profit, percent=percent)...
""" diaper pattern example (This is how you should NOT build your try.. except clauses) """ def fibonacci(n): """Returns the n-th number from the Fibonacci series.""" try: a = 0 b = 1 while n > 0: temp = a+b a = b b = temp ...
""" diaper pattern example (This is how you should NOT build your try.. except clauses) """ def fibonacci(n): """Returns the n-th number from the Fibonacci series.""" try: a = 0 b = 1 while n > 0: temp = a + b a = b b = temp n -= 1 ...
# Definition for singly-linked list. class Node(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def mergeKLists(self, lists): # find start node pendings = [] start = None for list in lists: show(list) ...
class Node(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def merge_k_lists(self, lists): pendings = [] start = None for list in lists: show(list) if list != None and (start == None or list.val < start.val)...
""" Warnings raised during database object interaction. """ class PlayerAlreadyJoinedWarning(Warning): """ Is raised when a player tries to join again. """
""" Warnings raised during database object interaction. """ class Playeralreadyjoinedwarning(Warning): """ Is raised when a player tries to join again. """
class Sale: def __init__(self, town, product, price, quantity): self.town = town self.product = product self.price = price self.quantity = quantity def read_sale(): inputData = input().split(' ') town = inputData[0] product = inputData[1] price = float(inputData[2]) ...
class Sale: def __init__(self, town, product, price, quantity): self.town = town self.product = product self.price = price self.quantity = quantity def read_sale(): input_data = input().split(' ') town = inputData[0] product = inputData[1] price = float(inputData[2]...
class _MemberlistUpdater(object): def add_or_updater(self): pass def _get_memberlist(self): pass
class _Memberlistupdater(object): def add_or_updater(self): pass def _get_memberlist(self): pass
''' Author: Kris Gonzalez DateCreated: 190114 Objective: write tests that execute on a given set of code in order to test compatability and give an example of "continuous integration" General Steps: 1. make a few random functions 2. in another file, write tests for those functions 3. run "pytest" and output result...
""" Author: Kris Gonzalez DateCreated: 190114 Objective: write tests that execute on a given set of code in order to test compatability and give an example of "continuous integration" General Steps: 1. make a few random functions 2. in another file, write tests for those functions 3. run "pytest" and output result...
def get_digits(n): r = [n % 10, n//10 % 10, n//100 % 10, n//1000 % 10, n//10000 % 10, n//100000 % 10] return r def increasing_digits(digits): result = True N = len(digits) for i in range(len(digits) - 1): result = result and digits[N-1 - i] <= digits[N-1 - i-1] return result def two_a...
def get_digits(n): r = [n % 10, n // 10 % 10, n // 100 % 10, n // 1000 % 10, n // 10000 % 10, n // 100000 % 10] return r def increasing_digits(digits): result = True n = len(digits) for i in range(len(digits) - 1): result = result and digits[N - 1 - i] <= digits[N - 1 - i - 1] return re...
''' Template to create a movie test data by yourself: ['Action', 'Adventure', 'Animation', 'Biography', 'Comedy', 'Crime', 'Documentary', 'Drama', 'Family', 'Fantasy', 'Film-Noir', 'Game-Show', 'History', 'Horror', 'Music', 'Musical', 'Mystery', 'News', 'Reality-TV', 'Romance', 'Sci-Fi', 'Short', 'Sport', 'Thriller', ...
""" Template to create a movie test data by yourself: ['Action', 'Adventure', 'Animation', 'Biography', 'Comedy', 'Crime', 'Documentary', 'Drama', 'Family', 'Fantasy', 'Film-Noir', 'Game-Show', 'History', 'Horror', 'Music', 'Musical', 'Mystery', 'News', 'Reality-TV', 'Romance', 'Sci-Fi', 'Short', 'Sport', 'Thriller', ...
"""This is a python program to find the minimum number of left or right moves to reach the target card given start card Index and cards array""" num_of_cards=int(input("Enter the number of cards: "))#ask user of number of cards cards=list(map(str,input("Enter cards: ").strip().split(',')))[:num_of_cards]#add the array ...
"""This is a python program to find the minimum number of left or right moves to reach the target card given start card Index and cards array""" num_of_cards = int(input('Enter the number of cards: ')) cards = list(map(str, input('Enter cards: ').strip().split(',')))[:num_of_cards] start_index = int(input('Enter starti...
pracky = [4, 9, 2, 0, 5, 8, 11, 33, 4, 77, 1, 88, 26, 7] def linSrch(haystack, needle): for ant in haystack: if ant == needle: return haystack.index(ant) elif haystack.index(ant) == len(haystack) - 1: return -1 else: continue # print(linSr...
pracky = [4, 9, 2, 0, 5, 8, 11, 33, 4, 77, 1, 88, 26, 7] def lin_srch(haystack, needle): for ant in haystack: if ant == needle: return haystack.index(ant) elif haystack.index(ant) == len(haystack) - 1: return -1 else: continue def bub_sort(haystack): ...
class ReqonError(Exception): pass class InvalidTypeError(ReqonError): def __init__(self, message): super(InvalidTypeError, self).__init__(message) class InvalidFilterError(ReqonError): def __init__(self, message): super(InvalidFilterError, self).__init__(message)
class Reqonerror(Exception): pass class Invalidtypeerror(ReqonError): def __init__(self, message): super(InvalidTypeError, self).__init__(message) class Invalidfiltererror(ReqonError): def __init__(self, message): super(InvalidFilterError, self).__init__(message)
# ROUND_SUM def round_sum(a, b, c): return round10(a) + round10(b) + round10(c) def round10(n): if n%10>4: n/=10 return (n+1) * 10 else: n/=10 return n * 10
def round_sum(a, b, c): return round10(a) + round10(b) + round10(c) def round10(n): if n % 10 > 4: n /= 10 return (n + 1) * 10 else: n /= 10 return n * 10
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Course: Python programming for life science researchers VT19 # Project: Potential Transcripts Prediction # Author: Yarong Tian # Import the original data sequence=input("Please paste query sequence here: ") # Read the query sequence seq=str(sequence) # Prepare for pr...
sequence = input('Please paste query sequence here: ') seq = str(sequence) result_head = ['RESULTS: ', 'StartPosition', 'NumberOfTranscripts'] start = 'TATA' end = 'AATAAA' result = {} for i in range(len(seq)): sp = seq.find(start, i, len(seq)) if SP == -1: break rest_seq = seq[SP + len(start):] ...
# This program computes batting and slugging averages from a given csv file of player data. # Nigel Myers # Fundamentals of Programming # ACC FALL 2018 # lab8.py # Prof Onabajo # Version: import .csv; output .txt #parse csv function class Player: def __init__(self, stats): self.name = stat...
class Player: def __init__(self, stats): self.name = stats['playernumber'] self.singles = int(stats['singles']) self.doubles = int(stats['doubles']) self.triples = int(stats['triples']) self.homeruns = int(stats['homeruns']) self.atbat = int(stats['atbat']) def ...
class MosartKeyboardCodes: ''' This class allows to convert the Mosart keyboard codes to the corresponding HID code and modifiers. .. warning:: These values have been collected empirically. As a result, the corresponding mapping may contains some mistakes or missing data. ''' @classmethod def getMosartK...
class Mosartkeyboardcodes: """ This class allows to convert the Mosart keyboard codes to the corresponding HID code and modifiers. .. warning:: These values have been collected empirically. As a result, the corresponding mapping may contains some mistakes or missing data. """ @classmethod def ...
# https://leetcode.com/problems/length-of-last-word/#/discuss class Solution(object): def lengthOfLastWord(self, s): """ :type s: str :rtype: int """ if s == '': return 0 word_list = s.split(" ") for w in reversed(word_list): ...
class Solution(object): def length_of_last_word(self, s): """ :type s: str :rtype: int """ if s == '': return 0 word_list = s.split(' ') for w in reversed(word_list): if w != '': return len(w) return 0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Odoo 12 Accounting PDF Reports', 'version': '12.0.1.0.0', 'category': 'Invoicing Management', 'summary': 'Accounting Reports For Odoo 12', 'sequence': '10', 'author': 'MP technolabs', ...
{'name': 'Odoo 12 Accounting PDF Reports', 'version': '12.0.1.0.0', 'category': 'Invoicing Management', 'summary': 'Accounting Reports For Odoo 12', 'sequence': '10', 'author': 'MP technolabs', 'company': 'Odoo Mates', 'maintainer': 'Odoo Mates', 'support': 'odoomates@gmail.com', 'website': 'https://www.mptechnolabs.co...
__version__ = "1.0.10" if __name__ == "__main__": # pragma: no cover print(__version__)
__version__ = '1.0.10' if __name__ == '__main__': print(__version__)
""" Speech constants for the food truck intent """ ADDRESS_NOT_FOUND = "I can't seem to find {}. Try another address" BAD_API_RESPONSE = "Hmm something went wrong. Maybe try again?" MULTIPLE_ADDRESS_ERROR = "I found multiple places with the address {}. " \ "What's the zip code?" ADDRESS_NOT_U...
""" Speech constants for the food truck intent """ address_not_found = "I can't seem to find {}. Try another address" bad_api_response = 'Hmm something went wrong. Maybe try again?' multiple_address_error = "I found multiple places with the address {}. What's the zip code?" address_not_understood = "I didn't understan...
# --- Day 2: Inventory Management System --- # https://adventofcode.com/2018/day/2 file = open("02_input.txt", "r") data = file.read().splitlines() twos = 0 threes = 0 rows = 0 for line in data: rows += 1 ll = [] for i in line: c = 0 for j in line: if i == j: ...
file = open('02_input.txt', 'r') data = file.read().splitlines() twos = 0 threes = 0 rows = 0 for line in data: rows += 1 ll = [] for i in line: c = 0 for j in line: if i == j: c += 1 ll.append(c) if 2 in ll: twos += 1 if 3 in ll: t...
class Employee(): def __init__(self, last, first, money): self.last = last self.first = first self.money = money def give_raise(self, raises=5000): self.raises = raises return raises
class Employee: def __init__(self, last, first, money): self.last = last self.first = first self.money = money def give_raise(self, raises=5000): self.raises = raises return raises
class Solution: def longestValidParentheses(self, s: str) -> int: return self.count(s) def count(self, s): s = s.replace("()", "*") for i in range(1, len(s)): s = s.replace(f"(" + i * "*" + ")", (i + 1) * "*") s = s.replace(")", "(") s = s.split("(") ...
class Solution: def longest_valid_parentheses(self, s: str) -> int: return self.count(s) def count(self, s): s = s.replace('()', '*') for i in range(1, len(s)): s = s.replace(f'(' + i * '*' + ')', (i + 1) * '*') s = s.replace(')', '(') s = s.split('(') ...
class CacheException(Exception): pass class InvalidCachePackage(CacheException): pass class BadLinkError(CacheException): """ Error raised when a symbolic link is bad. Can also arise when the link is possibly malicious. """ pass class BadPathError(CacheException): pass
class Cacheexception(Exception): pass class Invalidcachepackage(CacheException): pass class Badlinkerror(CacheException): """ Error raised when a symbolic link is bad. Can also arise when the link is possibly malicious. """ pass class Badpatherror(CacheException): pass
# https://leetcode.com/problems/trapping-rain-water/ class Solution: def trap(self, height: list[int]) -> int: # Create a helper array to find actual water levels held_water = [0 for _ in range(len(height))] water = 0 # Scan heights from left to right max_left = height[0] ...
class Solution: def trap(self, height: list[int]) -> int: held_water = [0 for _ in range(len(height))] water = 0 max_left = height[0] for idx in range(1, len(height) - 1): if height[idx] < max_left: held_water[idx] = max_left - height[idx] els...
def createLevelArrayFromCircuitDescription(circuitDescription): inputs = circuitDescription[0] gates = circuitDescription[2] levels = [{ i: { 'leaving': None, 'entering': [k for k in gates if i in gates[k]['inputs']][0] } for i in inputs }] numberOfGatesDone = 0 while numberOfGatesDone < len(gates...
def create_level_array_from_circuit_description(circuitDescription): inputs = circuitDescription[0] gates = circuitDescription[2] levels = [{i: {'leaving': None, 'entering': [k for k in gates if i in gates[k]['inputs']][0]} for i in inputs}] number_of_gates_done = 0 while numberOfGatesDone < len(gat...
COLORS = [ "amaranth", "amber", "amethyst", "apricot", "aqua", "aquamarine", "azure", "beige", "black", "blue", "blush", "bronze", "brown", "chocolate", "coffee", "copper", "coral", "crimson", "cyan", "emerald", "fuchsia", "gold", ...
colors = ['amaranth', 'amber', 'amethyst', 'apricot', 'aqua', 'aquamarine', 'azure', 'beige', 'black', 'blue', 'blush', 'bronze', 'brown', 'chocolate', 'coffee', 'copper', 'coral', 'crimson', 'cyan', 'emerald', 'fuchsia', 'gold', 'gray', 'green', 'harlequin', 'indigo', 'ivory', 'jade', 'lavender', 'lime', 'magenta', 'm...