content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def getting_input(): """ Gets input from user and implements it into an 2 dim array """ print('Enter a table:') return [list(map(int, list(input()))) for _ in range(9)]
def getting_input(): """ Gets input from user and implements it into an 2 dim array """ print('Enter a table:') return [list(map(int, list(input()))) for _ in range(9)]
class Type(): NONE = 0x0 NOCOLOR = 0x1 JAIL = 0x2 BHYVE = 0x4 EXIT = 0x8 CONNECTION_CLOSED = 0x10
class Type: none = 0 nocolor = 1 jail = 2 bhyve = 4 exit = 8 connection_closed = 16
# -*- coding:utf-8 -*- # !/usr/bin/env python3 """ """ class AsyncIteratorWrapper: def __init__(self, obj): self._it = iter(obj) def __aiter__(self): return self async def __anext__(self): try: value = next(self._it) except StopIteration: ...
""" """ class Asynciteratorwrapper: def __init__(self, obj): self._it = iter(obj) def __aiter__(self): return self async def __anext__(self): try: value = next(self._it) except StopIteration: raise StopAsyncIteration return value
""" This module implement a filter interface. """ class ImagineFilterInterface(object): """ Filter interface """ def apply(self, resource): """ Apply filter to resource :param resource: Image :return: Image """ raise NotImplementedError()
""" This module implement a filter interface. """ class Imaginefilterinterface(object): """ Filter interface """ def apply(self, resource): """ Apply filter to resource :param resource: Image :return: Image """ raise not_implemented_error()
### naive apporach class Solution: def moveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ zeroNum = 0 i = 0 while nums: if nums[i] == 0: nums.pop(i) zeroNum += 1 ...
class Solution: def move_zeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ zero_num = 0 i = 0 while nums: if nums[i] == 0: nums.pop(i) zero_num += 1 i -= 1 ...
print("==== PROGRAM HITUNG TOTAL HARGA PESANAN ====".center(50)) print("="*38) print("*Menu*".center(37)) print("="*38) print("1. Susu".rjust(8), "Rp.7.000".rjust(27)) print("2. Teh".rjust(7), "Rp.5.000".rjust(28)) print("3. Kopi".rjust(8), " Rp.5.000".rjust(27)) print("="*38, "\n") banyak_jenis = int(input("banyak je...
print('==== PROGRAM HITUNG TOTAL HARGA PESANAN ===='.center(50)) print('=' * 38) print('*Menu*'.center(37)) print('=' * 38) print('1. Susu'.rjust(8), 'Rp.7.000'.rjust(27)) print('2. Teh'.rjust(7), 'Rp.5.000'.rjust(28)) print('3. Kopi'.rjust(8), ' Rp.5.000'.rjust(27)) print('=' * 38, '\n') banyak_jenis = int(input('bany...
first_num = int(input()) second_num = int(input()) third_num = int(input()) for i in range (1, first_num + 1): for j in range (1, second_num + 1): for k in range (1, third_num + 1): if i % 2 == 0 and j > 1 and k % 2 == 0: for prime in range(2, j): if (j % pri...
first_num = int(input()) second_num = int(input()) third_num = int(input()) for i in range(1, first_num + 1): for j in range(1, second_num + 1): for k in range(1, third_num + 1): if i % 2 == 0 and j > 1 and (k % 2 == 0): for prime in range(2, j): if j % prime ...
a = int(input("Enter number a: ")) b = int(input("Enter number b: ")) i = a % b j = b % a print(i * j + 1)
a = int(input('Enter number a: ')) b = int(input('Enter number b: ')) i = a % b j = b % a print(i * j + 1)
class UserMessageError(Exception): def __init__(self, response_code, user_msg=None, server_msg=None): self.user_msg = user_msg or "" self.server_msg = server_msg or self.user_msg self.response_code = response_code super().__init__() class ClientError(UserMessageError): def __in...
class Usermessageerror(Exception): def __init__(self, response_code, user_msg=None, server_msg=None): self.user_msg = user_msg or '' self.server_msg = server_msg or self.user_msg self.response_code = response_code super().__init__() class Clienterror(UserMessageError): def __i...
# https://projecteuler.net/problem=5 def gcd(a, b): if b == 0: return a return gcd(b, a%b) print(gcd(1,6)) result = 1 for i in range(2, 21): g = gcd(result, i) result = result * (i/g) print(i, g, result) print(result)
def gcd(a, b): if b == 0: return a return gcd(b, a % b) print(gcd(1, 6)) result = 1 for i in range(2, 21): g = gcd(result, i) result = result * (i / g) print(i, g, result) print(result)
#Calculadora basica que haga suma,resta,multiplicacion y division def main() : n = input('Ingresa los numeroes entre espacios: \n') print("\t") print("Estos son los numeros ingresados: ") respuesta = input("\n Desea continuar? Y/N: ") if respuesta == "Y": print("Funciono") ...
def main(): n = input('Ingresa los numeroes entre espacios: \n') print('\t') print('Estos son los numeros ingresados: ') respuesta = input('\n Desea continuar? Y/N: ') if respuesta == 'Y': print('Funciono') print(n)
class TimeoutException(Exception): """Class to add a timeout attribute to an exception. If an exception is raised specifically due to a rate-limits being exceeded, this class can be used to add a timeout, indicated how long a task or application should wait until retrying. Attributes: exce...
class Timeoutexception(Exception): """Class to add a timeout attribute to an exception. If an exception is raised specifically due to a rate-limits being exceeded, this class can be used to add a timeout, indicated how long a task or application should wait until retrying. Attributes: exce...
def insertion_sort(lst): for passes in range(1, len(lst)): # n-1 passes current_val = lst[passes] pos = passes while pos > 0 and lst[pos-1] > current_val: lst[pos] = lst[pos-1] pos = pos-1 lst[pos] = current_val return lst arr = [2, 4, 42, 6, 22, 7]...
def insertion_sort(lst): for passes in range(1, len(lst)): current_val = lst[passes] pos = passes while pos > 0 and lst[pos - 1] > current_val: lst[pos] = lst[pos - 1] pos = pos - 1 lst[pos] = current_val return lst arr = [2, 4, 42, 6, 22, 7] print(inserti...
class Util: def __init__(self, node): self._node = node def createmultisig(self, nrequired, keys, address_type="legacy"): # 01 return self._node._rpc.call("createmultisig", nrequired, keys, address_type) def deriveaddresses(self, descriptor, range=None): # 02 return self._node._r...
class Util: def __init__(self, node): self._node = node def createmultisig(self, nrequired, keys, address_type='legacy'): return self._node._rpc.call('createmultisig', nrequired, keys, address_type) def deriveaddresses(self, descriptor, range=None): return self._node._rpc.call('de...
# For singly Linked List # class MySinglyLinkedList: # def __init__(self): # self.head = None # self.size = 0 # # If the index is invalid, return -1 # def get(self, index: int) -> int: # if index >= self.size or index < 0: # return -1 # if self.h...
""" ["MyLinkedList","addAtIndex","addAtIndex","addAtIndex","get"] [[],[0,10],[0,20],[1,30],[0]] ["MyLinkedList","addAtHead","addAtTail","addAtIndex","get","deleteAtIndex","deleteAtIndex","deleteAtIndex","get"] [[],[1],[3],[1,2],[1],[1],[0],[0],[1]] ["MyLinkedList","addAtHead","get","addAtTail","get","addAtIndex","addAt...
widget = WidgetDefault() widget.width = 101 widget.height = 101 widget.border = "None" widget.background = "None" commonDefaults["BarGraphWidget"] = widget def generateBarGraphWidget(file, screen, bar, parentName): name = bar.getName() file.write(" %s = leBarGraphWidget_New();" % (name)) generateBase...
widget = widget_default() widget.width = 101 widget.height = 101 widget.border = 'None' widget.background = 'None' commonDefaults['BarGraphWidget'] = widget def generate_bar_graph_widget(file, screen, bar, parentName): name = bar.getName() file.write(' %s = leBarGraphWidget_New();' % name) generate_base...
# -*- coding: utf-8 -*- """ bandwidth This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). """ class PriorityEnum(object): """Implementation of the 'Priority' enum. The message's priority, currently for toll-free or short code SMS only. Messages with a pr...
""" bandwidth This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). """ class Priorityenum(object): """Implementation of the 'Priority' enum. The message's priority, currently for toll-free or short code SMS only. Messages with a priority value of `"high"` are given prefere...
#!/usr/bin/python35 fp = open('hello.txt') print(fp.__next__()) print(next(fp)) fp.close()
fp = open('hello.txt') print(fp.__next__()) print(next(fp)) fp.close()
GLOBAL_TRANSITIONS = "global_transitions" TRANSITIONS = "transitions" RESPONSE = "response" PROCESSING = "processing" GRAPH = "graph" MISC = "misc"
global_transitions = 'global_transitions' transitions = 'transitions' response = 'response' processing = 'processing' graph = 'graph' misc = 'misc'
################################################################################# # # # Copyright 2018/08/16 Zachary Priddy (me@zpriddy.com) https://zpriddy.com # # ...
class Wtfrequest(object): def __init__(self, request_name, pid=None, **kwargs): self._request_name = request_name self._pid = pid self._kwargs = kwargs self.set_kwargs() def set_kwargs(self): for (name, value) in self._kwargs.iteritems(): setattr(self, name,...
def merge_the_tools(string, k): lens = len(string) for i in range(0, lens, k): lists = [j for j in string[i:i+k]] print(''.join(sorted(set(lists), key=lists.index))) s = input() n = int(input()) merge_the_tools(s, n)
def merge_the_tools(string, k): lens = len(string) for i in range(0, lens, k): lists = [j for j in string[i:i + k]] print(''.join(sorted(set(lists), key=lists.index))) s = input() n = int(input()) merge_the_tools(s, n)
def f(x, y): """ Args: x (int): foo Args: y (int): bar Examples: first line second line third line """
def f(x, y): """ Args: x (int): foo Args: y (int): bar Examples: first line second line third line """
# Stepper mode select STEPPER_m0 = 17 STEPPER_m1 = 27 STEPPER_m2 = 22 # First wheel GPIO Pin WHEEL1_step = 21 WHEEL1_dir = 20 # Second wheel GPIO Pin WHEEL2_step = 11 WHEEL2_dir = 10 # Third wheel GPIO Pin WHEEL3_step = 7 WHEEL3_dir = 8 # Fourth wheel GPIO Pin WHEEL4_step = 24 WHEEL4_dir = 23 CW = 1 ...
stepper_m0 = 17 stepper_m1 = 27 stepper_m2 = 22 wheel1_step = 21 wheel1_dir = 20 wheel2_step = 11 wheel2_dir = 10 wheel3_step = 7 wheel3_dir = 8 wheel4_step = 24 wheel4_dir = 23 cw = 1 ccw = 0 steps_per_revolution = 800 stepper_delay = 0.0005
def compute(a, b): return a + b def Test1(): a = -1 b = 1 assert compute(a, b) == -1 def testabc(): a = 0 b = -1 assert compute(a, b) == 0 def Test3(): a = 1 b = 10 assert compute(a, b) == 10 def Test4(): a = -1 b = -1 assert compute(a, b) == 1
def compute(a, b): return a + b def test1(): a = -1 b = 1 assert compute(a, b) == -1 def testabc(): a = 0 b = -1 assert compute(a, b) == 0 def test3(): a = 1 b = 10 assert compute(a, b) == 10 def test4(): a = -1 b = -1 assert compute(a, b) == 1
URL_PROJECT_VIEW="http://tasks.hotosm.org/project/{project}" URL_PROJECT_EDIT="http://tasks.hotosm.org/project/{project}/edit" URL_PROJECT_TASKS="http://tasks.hotosm.org/project/{project}/tasks.json" URL_CHANGESET_VIEW="http://www.openstreetmap.org/changeset/{changeset}" URL_CHANGESET_API ="https://api.openstreetmap.o...
url_project_view = 'http://tasks.hotosm.org/project/{project}' url_project_edit = 'http://tasks.hotosm.org/project/{project}/edit' url_project_tasks = 'http://tasks.hotosm.org/project/{project}/tasks.json' url_changeset_view = 'http://www.openstreetmap.org/changeset/{changeset}' url_changeset_api = 'https://api.openstr...
def contains_cycle(first_node): nodes_visited = set() if not first_node or not first_node.next: return False current_node = first_node.next while current_node.next: if current_node.value in nodes_visited: return True else: nodes_visited.add(current_node....
def contains_cycle(first_node): nodes_visited = set() if not first_node or not first_node.next: return False current_node = first_node.next while current_node.next: if current_node.value in nodes_visited: return True else: nodes_visited.add(current_node.va...
pessoas = {'nome': 'Gustavo', 'sexo ': 'M', 'idade' : 22} print(pessoas) print(pessoas['idade'])## 22 print(f' O {pessoas["nome"]} tem {pessoas["idade"]} anos.')## O Gustavo tem 22 anos. print(pessoas.keys())## dict_keys(['nome', 'sexo ', 'idade']) print(pessoas.values())##dict_values(['Gustavo', 'M', 22]) print(...
pessoas = {'nome': 'Gustavo', 'sexo ': 'M', 'idade': 22} print(pessoas) print(pessoas['idade']) print(f" O {pessoas['nome']} tem {pessoas['idade']} anos.") print(pessoas.keys()) print(pessoas.values()) print(pessoas.items()) for k in pessoas.keys(): print(k) for (k, v) in pessoas.items(): print(f'{k} = {v}') pe...
CONF_Main = { "environment": "lux_gym:lux-v0", "setup": "rl", "model_name": "actor_critic_sep_residual_six_actions", "n_points": 40, # check tfrecords reading transformation merge_rl } CONF_Scrape = { "lux_version": "3.1.0", "scrape_type": "single", "parallel_calls": 8, "is_for_rl": Tr...
conf__main = {'environment': 'lux_gym:lux-v0', 'setup': 'rl', 'model_name': 'actor_critic_sep_residual_six_actions', 'n_points': 40} conf__scrape = {'lux_version': '3.1.0', 'scrape_type': 'single', 'parallel_calls': 8, 'is_for_rl': True, 'is_pg_rl': True, 'team_name': None, 'only_wins': False, 'only_top_teams': False} ...
# Transmission registers TXB0CTRL = 0x30 TXB1CTRL = 0x40 TXB2CTRL = 0x50 TXRTSCTRL = 0x0D TXB0SIDH = 0x31 TXB1SIDH = 0x41 TXB2SIDH = 0x51 TXB0SIDL = 0x32 TXB1SIDL = 0x42 TXB2SIDL = 0x52 TXB0EID8 = 0x33 TXB1EID8 = 0x43 TXB0EID8 = 0x53 TXB0EID0 = 0x34 TXB1EID0 = 0x44 TXB2EID0 = 0x54 TXB0DLC = 0x35 TXB1DLC = 0x45 T...
txb0_ctrl = 48 txb1_ctrl = 64 txb2_ctrl = 80 txrtsctrl = 13 txb0_sidh = 49 txb1_sidh = 65 txb2_sidh = 81 txb0_sidl = 50 txb1_sidl = 66 txb2_sidl = 82 txb0_eid8 = 51 txb1_eid8 = 67 txb0_eid8 = 83 txb0_eid0 = 52 txb1_eid0 = 68 txb2_eid0 = 84 txb0_dlc = 53 txb1_dlc = 69 txb2_dlc = 85 txb0_d = 54 txb1_d = 70 txb2_d = 86 rx...
class Solution: def increasingTriplet(self, nums): """ :type nums: List[int] :rtype: bool """ first = second = float('inf') for n in nums: if n <= first: first = n elif n <= second: second = n else: ...
class Solution: def increasing_triplet(self, nums): """ :type nums: List[int] :rtype: bool """ first = second = float('inf') for n in nums: if n <= first: first = n elif n <= second: second = n else:...
# Heroku PostgreSQL credentials, rename this file to config.py HOST = "placeholder" DB = "placeholder" USER = "placeholder" PASSWORD = "placeholder" PORT = "5432"
host = 'placeholder' db = 'placeholder' user = 'placeholder' password = 'placeholder' port = '5432'
# Every neuron has a unique connection to the previous neuron. inputs = [3.1 , 2.5 , 5.4] # Every input is going to have a unique weight weights = [4.5 , 7.6 , 2.4] # Every neuron is going to have a unique bias bias = 3 # Now let's check the output from the neuron output = inputs[0] * weights[0] + inputs[1] * weigh...
inputs = [3.1, 2.5, 5.4] weights = [4.5, 7.6, 2.4] bias = 3 output = inputs[0] * weights[0] + inputs[1] * weights[1] + inputs[2] * weights[2] + bias print(output)
class RebarCouplerError(Enum, IComparable, IFormattable, IConvertible): """ Error states for the Rebar Coupler enum RebarCouplerError,values: BarSegementsAreNotParallel (6),BarSegmentsAreNotOnSameLine (7),BarSegmentSmallerThanEngagement (13),BarsNotTouching (3),CurvesOtherThanLine (12),DifferentLayout (...
class Rebarcouplererror(Enum, IComparable, IFormattable, IConvertible): """ Error states for the Rebar Coupler enum RebarCouplerError,values: BarSegementsAreNotParallel (6),BarSegmentsAreNotOnSameLine (7),BarSegmentSmallerThanEngagement (13),BarsNotTouching (3),CurvesOtherThanLine (12),DifferentLayout (2),Inc...
def generate_odd_nums(start, end): for num in range(start, end+1): if num % 2 !=0: print(num, end=" ") generate_odd_nums(start = 0, end = 15)
def generate_odd_nums(start, end): for num in range(start, end + 1): if num % 2 != 0: print(num, end=' ') generate_odd_nums(start=0, end=15)
__author__ = 'KKishore' PAD_WORD = '#=KISHORE=#' HEADERS = ['class', 'sms'] FEATURE_COL = 'sms' LABEL_COL = 'class' WEIGHT_COLUNM_NAME = 'weight' TARGET_LABELS = ['spam', 'ham'] TARGET_SIZE = len(TARGET_LABELS) HEADER_DEFAULTS = [['NA'], ['NA']] MAX_DOCUMENT_LENGTH = 100
__author__ = 'KKishore' pad_word = '#=KISHORE=#' headers = ['class', 'sms'] feature_col = 'sms' label_col = 'class' weight_colunm_name = 'weight' target_labels = ['spam', 'ham'] target_size = len(TARGET_LABELS) header_defaults = [['NA'], ['NA']] max_document_length = 100
class PracticeCenter: def __init__(self, practice_center_id, name, email=None, web_site=None, phone_number=None, climates=None, recommendations=None, average_note=None): self.id = practice_center_id self.name = name self.email = email self.web_site = web_site ...
class Practicecenter: def __init__(self, practice_center_id, name, email=None, web_site=None, phone_number=None, climates=None, recommendations=None, average_note=None): self.id = practice_center_id self.name = name self.email = email self.web_site = web_site self.phone_numb...
class Rectangle: def __init__(self, width, height): self.width = width self.height = height def __str__(self): return "Rectangle(width=" + str(self.width) + ", height="+ str(self.height) + ")" def set_width(self, width): self.width = width def set_height(self, hei...
class Rectangle: def __init__(self, width, height): self.width = width self.height = height def __str__(self): return 'Rectangle(width=' + str(self.width) + ', height=' + str(self.height) + ')' def set_width(self, width): self.width = width def set_height(self, height...
class Test: def foo(a): if a == 'foo': return 'foo' return 'bar'
class Test: def foo(a): if a == 'foo': return 'foo' return 'bar'
#------------------------------------------------------------------- # Copyright (c) 2021, Scott D. Peckham # # Oct. 2021. Added to bypass old tf_utils.py for version, etc. # #------------------------------------------------------------------- # Notes: Update these whenever a new version is released #------------...
def name(): return 'Stochastic Conflict Model' def version_number(): return 0.8 def build_date(): return '2021-10-13' def version_string(): num_str = str(version_number()) date_str = ' (' + build_date() + ')' ver_string = name() + ' Version ' + num_str + date_str return ver_string
class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ max_profit = temp_profit = 0 incresing = [tomorrow-today for today, tomorrow in zip(prices[:-1],prices[1:])] # print(incresing) for price in incresing: ...
class Solution: def max_profit(self, prices): """ :type prices: List[int] :rtype: int """ max_profit = temp_profit = 0 incresing = [tomorrow - today for (today, tomorrow) in zip(prices[:-1], prices[1:])] for price in incresing: temp_profit += pric...
first_name = "ada" last_name = "lovelace" full_name = f"{first_name} {last_name}" #or full_name = "{} {}".format(first_name,last_name) #print(full_name) message = f"Hello, {full_name.title()}!" print(message)
first_name = 'ada' last_name = 'lovelace' full_name = f'{first_name} {last_name}' full_name = '{} {}'.format(first_name, last_name) message = f'Hello, {full_name.title()}!' print(message)
''' the permission will be set in the database and only the managers will have permission to cancel an order already completed ''' class User(): def __init__(self, userid, username, permission): self.userid=userid self.username=username self.permission=permission def getUserNumber(self)...
""" the permission will be set in the database and only the managers will have permission to cancel an order already completed """ class User: def __init__(self, userid, username, permission): self.userid = userid self.username = username self.permission = permission def get_user_numb...
class Solution: def recurse(self, A, stack) : if A == "" : self.ans.append(stack) temp_str = "" n = len(A) for i, ch in enumerate(A) : temp_str += ch if self.isPalindrome(temp_str) : self.recurse(A[i+1:], stack+[temp_str]...
class Solution: def recurse(self, A, stack): if A == '': self.ans.append(stack) temp_str = '' n = len(A) for (i, ch) in enumerate(A): temp_str += ch if self.isPalindrome(temp_str): self.recurse(A[i + 1:], stack + [temp_str]) d...
class DataParser: input_pub_sub_subscription = "" output_pub_sub_subscription = "" stocks: list = [] brokers: list = [] def __init__(self, html): self.html = html def parse_table_content(self, html): """ :param html: a table of stock or broker :return: ...
class Dataparser: input_pub_sub_subscription = '' output_pub_sub_subscription = '' stocks: list = [] brokers: list = [] def __init__(self, html): self.html = html def parse_table_content(self, html): """ :param html: a table of stock or broker :return: ...
# name: TColors # Version: 1 # Created by: Grigory Sazanov # GitHub: https://github.com/SazanovGrigory class TerminalColors: # Description: Class that can be used to color terminal output # Example: print('GitHub: '+f"{BColors.TerminalColors.UNDERLINE}https://github.com/SazanovGr...
class Terminalcolors: header = '\x1b[95m' okblue = '\x1b[94m' okcyan = '\x1b[96m' okgreen = '\x1b[92m' warning = '\x1b[93m' fail = '\x1b[91m' endc = '\x1b[0m' bold = '\x1b[1m' underline = '\x1b[4m' def main(): print('Name: ' + f'{TerminalColors.HEADER}TColors{TerminalCol...
""" #David Hickox #Mar 20 17 #Typing Program #this will tell each of the 7 dwarfs if they can type fast enough or not #variables # STUDENTS = names of the dwarfs # num = WPM """ STUDENTS = ["Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy"] print("Welcome to the Typing program") #starts the loop for...
""" #David Hickox #Mar 20 17 #Typing Program #this will tell each of the 7 dwarfs if they can type fast enough or not #variables # STUDENTS = names of the dwarfs # num = WPM """ students = ['Bashful', 'Doc', 'Dopey', 'Happy', 'Sleepy', 'Sneezy', 'Grumpy'] print('Welcome to the Typing program') for i in enumerate(ST...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def solve(self, t1: TreeNode, t2: TreeNode) -> TreeNode: if not t1 and not t2: return None node = TreeNode(0) ...
class Treenode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def solve(self, t1: TreeNode, t2: TreeNode) -> TreeNode: if not t1 and (not t2): return None node = tree_node(0) if t1: node.val += t1...
"""Question: https://leetcode.com/problems/validate-binary-search-tree/ """ class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def isValidBST(self, root: TreeNode) -> bool: def is_valid_bst_recu...
"""Question: https://leetcode.com/problems/validate-binary-search-tree/ """ class Treenode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def is_valid_bst(self, root: TreeNode) -> bool: def is_valid_bst_r...
# -*- coding: utf-8 -*- """ Created on Wed Jul 17 14:15:21 2019 @author: hu """
""" Created on Wed Jul 17 14:15:21 2019 @author: hu """
def foo(): global bar def bar(): pass
def foo(): global bar def bar(): pass
#!/usr/bin/env python """ idea: break up the address into 3 sections: 0xAABBCC. Treat each section like it is a layer in the page tables. AA is the base of one table. From that, offset BB is the base of the "PTE". Then CC is the offset into the "page" and contains a 24-bit word that we can copy. """ WORD_WIDTH = 24 D...
""" idea: break up the address into 3 sections: 0xAABBCC. Treat each section like it is a layer in the page tables. AA is the base of one table. From that, offset BB is the base of the "PTE". Then CC is the offset into the "page" and contains a 24-bit word that we can copy. """ word_width = 24 depth = 4 bit = 14593470 ...
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompa...
instance_tail_logs_response = '-------------------------------------\n/var/log/awslogs.log\n-------------------------------------\n{\'skipped_events_count\': 0, \'first_event\': {\'timestamp\': 1522962583519, \'start_position\': 559799L, \'end_position\': 560017L}, \'fallback_events_count\': 0, \'last_event\': {\'times...
class ParadoxException(Exception): pass class ParadoxConnectError(ParadoxException): def __init__(self) -> None: super().__init__('Unable to connect to panel') class ParadoxCommandError(ParadoxException): pass class ParadoxTimeout(ParadoxException): pass
class Paradoxexception(Exception): pass class Paradoxconnecterror(ParadoxException): def __init__(self) -> None: super().__init__('Unable to connect to panel') class Paradoxcommanderror(ParadoxException): pass class Paradoxtimeout(ParadoxException): pass
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: def merge(l1, l2): if not l1: return l2 if not l2: return l1 if l1[0] < l2[0]: return [l1[0]] + merge(l1[1:], l2) else: retu...
class Solution: def find_median_sorted_arrays(self, nums1: List[int], nums2: List[int]) -> float: def merge(l1, l2): if not l1: return l2 if not l2: return l1 if l1[0] < l2[0]: return [l1[0]] + merge(l1[1:], l2) ...
cities = [ 'Riga', 'Daugavpils', 'Liepaja', 'Jelgava', 'Jurmala', 'Ventspils', 'Rezekne', 'Jekabpils', 'Valmiera', 'Ogre', 'Tukums', 'Cesis', 'Salaspils', 'Bolderaja', 'Kuldiga', 'Olaine', 'Saldus', 'Talsi', 'Dobele', 'Kraslava', 'Bausk...
cities = ['Riga', 'Daugavpils', 'Liepaja', 'Jelgava', 'Jurmala', 'Ventspils', 'Rezekne', 'Jekabpils', 'Valmiera', 'Ogre', 'Tukums', 'Cesis', 'Salaspils', 'Bolderaja', 'Kuldiga', 'Olaine', 'Saldus', 'Talsi', 'Dobele', 'Kraslava', 'Bauska', 'Ludza', 'Sigulda', 'Livani', 'Daugavgriva', 'Gulbene', 'Madona', 'Limbazi', 'Aiz...
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( s ) : n = len ( s ) ; sub_count = ( n * ( n + 1 ) ) // 2 ; arr = [ 0 ] * sub_count ; index = 0 ; ...
def f_gold(s): n = len(s) sub_count = n * (n + 1) // 2 arr = [0] * sub_count index = 0 for i in range(n): for j in range(1, n - i + 1): arr[index] = s[i:i + j] index += 1 arr.sort() res = '' for i in range(sub_count): res += arr[i] return res i...
morse_translated_to_english = { ".-": "A", "-...": "B", "-.-.": "C", "-..": "D", ".": "E", "..-.": "F", "--.": "G", "....": "H", "..": "I", ".---": "J", "-.-": "K", ".-..": "L", "--": "M", "-.": "N", "---": "O", ".--.": "P", "--.-": "Q", ".-.": "R"...
morse_translated_to_english = {'.-': 'A', '-...': 'B', '-.-.': 'C', '-..': 'D', '.': 'E', '..-.': 'F', '--.': 'G', '....': 'H', '..': 'I', '.---': 'J', '-.-': 'K', '.-..': 'L', '--': 'M', '-.': 'N', '---': 'O', '.--.': 'P', '--.-': 'Q', '.-.': 'R', '...': 'S', '-': 'T', '..-': 'U', '...-': 'V', '.--': 'W', '-..-': 'X',...
# # PySNMP MIB module Wellfleet-NAME-TABLE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-NAME-TABLE-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:41:01 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7....
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_size_constraint, single_value_constraint, value_range_constraint, constraints_union) ...
#!/usr/bin/env python """ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License");...
""" Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this ...
""" Parking Cars in a List """ # create a list of cars row = ['Ford','Audi','BMW','Lexus'] # park my Mercedes at the end of the row row.append('Mercedes') print(row) print(row[4]) # swap the BMW at index 2 for a Jeep row[2] = 'Jeep' print(row) # park a Honda at the end of the row row.append('Honda') ...
""" Parking Cars in a List """ row = ['Ford', 'Audi', 'BMW', 'Lexus'] row.append('Mercedes') print(row) print(row[4]) row[2] = 'Jeep' print(row) row.append('Honda') print(row) print(row[4]) row.insert(0, 'Kia') print(row) print(row[4]) print(row.index('Mercedes')) print(row.pop(5)) print(row) row.remove('Lexus') print(...
#!/usr/bin/env python #### provide two configuration dictionaries: global_setting and feature_set #### ###This is basic configuration global_setting=dict( max_len = 256, # max length for the dataset ) feature_set=dict( ccmpred=dict( suffix = "ccmpred", leng...
global_setting = dict(max_len=256) feature_set = dict(ccmpred=dict(suffix='ccmpred', length=1, parser_name='ccmpred_parser_2d', type='2d', skip=False), ss2=dict(suffix='ss2', length=3, parser_name='ss2_parser_1d', type='1d', skip=False), solv=dict(suffix='solv', length=1, parser_name='solv_parser_1d', type='1d', skip=F...
class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: if not nums: return [] res = [] nums.sort() for i, num in enumerate(nums): if i > 0 and num == nums[i - 1]: continue left, right = i +...
class Solution: def three_sum(self, nums: List[int]) -> List[List[int]]: if not nums: return [] res = [] nums.sort() for (i, num) in enumerate(nums): if i > 0 and num == nums[i - 1]: continue (left, right) = (i + 1, len(nums) - 1) ...
#!/usr/bin/python3 with open('03_input', 'r') as f: lines = f.readlines() bits_list = [list(n.strip()) for n in lines] bit_len = len(bits_list[0]) zeros = [0 for i in range(bit_len)] ones = [0 for i in range(bit_len)] for bits in bits_list: for i, b in enumerate(bits): if b == '0': zero...
with open('03_input', 'r') as f: lines = f.readlines() bits_list = [list(n.strip()) for n in lines] bit_len = len(bits_list[0]) zeros = [0 for i in range(bit_len)] ones = [0 for i in range(bit_len)] for bits in bits_list: for (i, b) in enumerate(bits): if b == '0': zeros[i] += 1 elif...
# WHICH NUMBER IS NOT LIKE THE OTHERS EDABIT SOLUTION: # creating a function to solve the problem. def unique(lst): # creating a for-loop to iterate for the elements in the list. for i in lst: # creating a nested if-statement to check for a distinct element. if lst.count(i) == 1: # ret...
def unique(lst): for i in lst: if lst.count(i) == 1: return i
# Complete the function below. # Function to check ipv4 # @Return boolean def validateIPV4(ipAddress): isIPv4 = True # ipv4 address is composed by octet for octet in ipAddress: try: # pretty straigthforward, convert to int # ensure per-octet value falls between [0,255] ...
def validate_ipv4(ipAddress): is_i_pv4 = True for octet in ipAddress: try: tmp = int(octet) if tmp < 0 or tmp > 255: is_i_pv4 = False break except: is_i_pv4 = False break return 'IPv4' if isIPv4 else 'Neither' d...
""" Contains the Team object used represent NBA teams """ class Team: """ Object representing NBA teams containing: team name - three letter code - unique team id - nickname. """ def __init__(self, name, tricode, teamID, nickname): self.name = name self...
""" Contains the Team object used represent NBA teams """ class Team: """ Object representing NBA teams containing: team name - three letter code - unique team id - nickname. """ def __init__(self, name, tricode, teamID, nickname): self.name = name sel...
def kph(ms): return ms * 3.6 def mph(ms): return ms * 2.2369362920544 def knots(ms): return ms * 1.9438444924574 def minPkm(ms): # minutes per kilometre return ms * (100 / 6) def c(ms): # speed of light return ms / 299792458 def speedOfLight(ms): return c(ms) def mach(ms): return ms / 340 d...
def kph(ms): return ms * 3.6 def mph(ms): return ms * 2.2369362920544 def knots(ms): return ms * 1.9438444924574 def min_pkm(ms): return ms * (100 / 6) def c(ms): return ms / 299792458 def speed_of_light(ms): return c(ms) def mach(ms): return ms / 340 def speed_of_sound(ms): retur...
# -*- encoding: utf-8 -*- # # Copyright 2015-2016 Red Hat, Inc. # # 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 applic...
def test_create_user(runner, test_user): assert test_user['name'] == 'foo' assert test_user['fullname'] == 'Foo Bar' assert test_user['email'] == 'foo@example.org' def test_create_admin(runner): user = runner.invoke(['user-create', '--name', 'foo', '--email', 'foo@example.org', '--password', 'pass'])['...
# -*- coding: utf-8 -*- even = 0 for i in range(5): A = float(input()) if (A % 2) == 0: even +=1 print("%i valores pares"%even)
even = 0 for i in range(5): a = float(input()) if A % 2 == 0: even += 1 print('%i valores pares' % even)
class user(): def __init__(self,id,passwd): self.id = id self.passwd = passwd def get_id(self): pass
class User: def __init__(self, id, passwd): self.id = id self.passwd = passwd def get_id(self): pass
def factorial(no): if no == 1: return no else: return no * factorial(no - 1) """ # Factorial using for loop Without Recursive ans = 1 for i in range(1, no+1): ans = ans * i print(ans) """ def main(): no = int(input("Enter number : ")) # ret = no+1 print(facto...
def factorial(no): if no == 1: return no else: return no * factorial(no - 1) '\n# Factorial using for loop Without Recursive\nans = 1\nfor i in range(1, no+1):\n ans = ans * i\nprint(ans)\n' def main(): no = int(input('Enter number : ')) print(factorial(no)) if __name__ == '__main__'...
## using hashing .. def duplicates_hash(arr, n): s = dict() for i in range(n): if arr[i] in s: s[arr[i]] = s[arr[i]]+1 else: s[arr[i]] = 1 res = [] for i in s: if s[i] > 1: res.append(i) if len(res)>0: return res else: ...
def duplicates_hash(arr, n): s = dict() for i in range(n): if arr[i] in s: s[arr[i]] = s[arr[i]] + 1 else: s[arr[i]] = 1 res = [] for i in s: if s[i] > 1: res.append(i) if len(res) > 0: return res else: return -1 def du...
lastA = 116 lastB = 299 judgeCounter = 0 for i in range(40000000): # Generation cycle aRes = (lastA * 16807) % 2147483647 bRes = (lastB * 48271) % 2147483647 # Judging time if (aRes % 65536 == bRes % 65536): print("Match found! With ", aRes, " and ", bRes, sep="") judgeCounter...
last_a = 116 last_b = 299 judge_counter = 0 for i in range(40000000): a_res = lastA * 16807 % 2147483647 b_res = lastB * 48271 % 2147483647 if aRes % 65536 == bRes % 65536: print('Match found! With ', aRes, ' and ', bRes, sep='') judge_counter += 1 last_a = aRes last_b = bRes print('...
"""In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number. === Example: === high_and_low("1 2 3 4 5") # return "5 1" high_and_low("1 2 -3 4 5") # return "5 -3" high_and_low("1 9 3 4 -5") # return "9 -5" === Notes: === All numbers are valid I...
"""In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number. === Example: === high_and_low("1 2 3 4 5") # return "5 1" high_and_low("1 2 -3 4 5") # return "5 -3" high_and_low("1 9 3 4 -5") # return "9 -5" === Notes: === All numbers are valid I...
# # PySNMP MIB module ZYXEL-DIFFSERV-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-DIFFSERV-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:49:30 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, value_range_constraint, value_size_constraint, single_value_constraint, constraints_intersection) ...
PLUGIN_URL_NAME_PREFIX = 'djangocms_alias' CREATE_ALIAS_URL_NAME = '{}_create'.format(PLUGIN_URL_NAME_PREFIX) DELETE_ALIAS_URL_NAME = '{}_delete'.format(PLUGIN_URL_NAME_PREFIX) DETACH_ALIAS_PLUGIN_URL_NAME = '{}_detach_plugin'.format(PLUGIN_URL_NAME_PREFIX) # noqa: E501 LIST_ALIASES_URL_NAME = '{}_list'.format(PLUGIN...
plugin_url_name_prefix = 'djangocms_alias' create_alias_url_name = '{}_create'.format(PLUGIN_URL_NAME_PREFIX) delete_alias_url_name = '{}_delete'.format(PLUGIN_URL_NAME_PREFIX) detach_alias_plugin_url_name = '{}_detach_plugin'.format(PLUGIN_URL_NAME_PREFIX) list_aliases_url_name = '{}_list'.format(PLUGIN_URL_NAME_PREFI...
class Party: def __init__(self): self.party_people = [] self.party_people_counter = 0 party = Party() people = input() while people != 'End': party.party_people.append(people) party.party_people_counter += 1 people = input() print(f'Going: {", ".join(party.party_people)}') print(f'T...
class Party: def __init__(self): self.party_people = [] self.party_people_counter = 0 party = party() people = input() while people != 'End': party.party_people.append(people) party.party_people_counter += 1 people = input() print(f"Going: {', '.join(party.party_people)}") print(f'Total...
class Solution: def __init__(self): self.count = 0 def waysToStep(self, n: int) -> int: def dfs(n): if n == 1: self.count += 1 elif n == 2: self.count += 2 elif n == 3: self.count += 4 else: ...
class Solution: def __init__(self): self.count = 0 def ways_to_step(self, n: int) -> int: def dfs(n): if n == 1: self.count += 1 elif n == 2: self.count += 2 elif n == 3: self.count += 4 else: ...
# Determine whether a number is a perfect number, an Armstrong number or a palindrome. def perfect_number(n): sum1 = 0 for i in range(1, n): if(n % i == 0): sum1 = sum1 + i if (sum1 == n): return True else: return False def armstrong(n): sum = 0 temp = n ...
def perfect_number(n): sum1 = 0 for i in range(1, n): if n % i == 0: sum1 = sum1 + i if sum1 == n: return True else: return False def armstrong(n): sum = 0 temp = n while temp > 0: digit = temp % 10 sum += digit ** 3 temp //= 10 ...
# Created by MechAviv # [Kyrin] | [1090000] # Nautilus : Navigation Room sm.setSpeakerID(1090000) sm.sendSayOkay("Welcome aboard the Nautilus. The ship isn't headed anywhere for a while. How about going out to the deck?")
sm.setSpeakerID(1090000) sm.sendSayOkay("Welcome aboard the Nautilus. The ship isn't headed anywhere for a while. How about going out to the deck?")
def deduplicate_list(list_with_dups): return list(dict.fromkeys(list_with_dups)) def filter_list_by_set(original_list, filter_set): return [elem for elem in original_list if elem not in filter_set] def write_to_file(filename, text, message): # pragma: no cover with open(filename, 'w') as f: f.w...
def deduplicate_list(list_with_dups): return list(dict.fromkeys(list_with_dups)) def filter_list_by_set(original_list, filter_set): return [elem for elem in original_list if elem not in filter_set] def write_to_file(filename, text, message): with open(filename, 'w') as f: f.write(text) print(m...
# # PySNMP MIB module HM2-DNS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HM2-DNS-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:31:23 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 0...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, single_value_constraint, constraints_intersection, value_range_constraint, value_size_constraint) ...
class Params: def __init__(self): self.embed_size = 75 self.epochs = 2000 self.learning_rate = 0.01 self.top_k = 20 self.ent_top_k = [1, 5, 10, 50] self.lambda_3 = 0.7 self.generate_sim = 10 self.csls = 5 self.heuristic = True self.is_s...
class Params: def __init__(self): self.embed_size = 75 self.epochs = 2000 self.learning_rate = 0.01 self.top_k = 20 self.ent_top_k = [1, 5, 10, 50] self.lambda_3 = 0.7 self.generate_sim = 10 self.csls = 5 self.heuristic = True self.is_...
""" with open("scrabble.txt", 'r') as f: count = 0 for line in f: if count > 5: break print(line) count += 1 """ #1: Compute scrabble tile score of given string input #2: Compute all "valid scrabble" words that you could make # with all char from an input string. Retu...
""" with open("scrabble.txt", 'r') as f: count = 0 for line in f: if count > 5: break print(line) count += 1 """ '\nchars=input("input your characters in ALL CAPS: ")\ncharsList=sorted(list(chars))\nfinal=[]\nwith open("scrabble.txt", \'r\') as f:\n for line in f:\n ...
class Solution: def longestPalindrome(self, s: str) -> int: m = {} for c in s: if c in m: m[c] += 1 else: m[c] = 1 ans = 0 longest_odd = 0 longest_char = None; for key in m: ...
class Solution: def longest_palindrome(self, s: str) -> int: m = {} for c in s: if c in m: m[c] += 1 else: m[c] = 1 ans = 0 longest_odd = 0 longest_char = None for key in m: if m[key] % 2 == 1: ...
# https://www.hackerrank.com/challenges/icecream-parlor/problem t = int(input()) for _ in range(t): m = int(input()) n = int(input()) cost = list(map(int, input().split())) memo = {} for i, c in enumerate(cost): if (m - c) in memo: print('%s %s' % (memo[m - c], i + 1)) ...
t = int(input()) for _ in range(t): m = int(input()) n = int(input()) cost = list(map(int, input().split())) memo = {} for (i, c) in enumerate(cost): if m - c in memo: print('%s %s' % (memo[m - c], i + 1)) break memo[c] = i + 1
# Enum for allegiances ALLEGIANCE_MAP = { 0: "Shadow", 1: "Neutral", 2: "Hunter" } # Enum for card types CARD_COLOR_MAP = { 0: "White", 1: "Black", 2: "Green" } # Enum for text colors TEXT_COLORS = { 'server': 'rgb(200,200,200)', 'number': 'rgb(153,204,255)', 'White': 'rgb(255,255,...
allegiance_map = {0: 'Shadow', 1: 'Neutral', 2: 'Hunter'} card_color_map = {0: 'White', 1: 'Black', 2: 'Green'} text_colors = {'server': 'rgb(200,200,200)', 'number': 'rgb(153,204,255)', 'White': 'rgb(255,255,255)', 'Black': 'rgb(75,75,75)', 'Green': 'rgb(143,194,0)', 'shadow': 'rgb(128,0,0)', 'neutral': 'rgb(255,255,1...
#!/usr/bin/env python # -*- coding: utf-8 -*- """app: The package to hold shell CLI entry points. 1. cistat-cli added for demo. #. cache commands under progress. ..moduleauthor:: Max Wu < http: // maxwu.me > """
"""app: The package to hold shell CLI entry points. 1. cistat-cli added for demo. #. cache commands under progress. ..moduleauthor:: Max Wu < http: // maxwu.me > """
with open('binary_numbers.txt') as f: lines = f.readlines() length = len(lines) # Part One def most_common(strings): # Creates a list of amount of 1's at each index for all lines in the string. E.g. a = [1, 3, 2] will have 3 binary numbers with 1 at index 1. indices = [] bit_length = len(strings[0...
with open('binary_numbers.txt') as f: lines = f.readlines() length = len(lines) def most_common(strings): indices = [] bit_length = len(strings[0].strip()) for _ in range(bit_length): indices.append(0) for line in strings: line = line.strip() for (index, char) in enumera...
""" Sensor of Library to measure the 5g signal How to import: from Sensors.{sensor_package}.lib import device How to use: with device() as sensor: print(sensor.read_power()) """
""" Sensor of Library to measure the 5g signal How to import: from Sensors.{sensor_package}.lib import device How to use: with device() as sensor: print(sensor.read_power()) """
class DarkKeeperError(Exception): pass class DarkKeeperCacheError(DarkKeeperError): pass class DarkKeeperCacheReadError(DarkKeeperCacheError): pass class DarkKeeperCacheWriteError(DarkKeeperCacheError): pass class DarkKeeperParseError(DarkKeeperError): pass class DarkKeeperParseContentErro...
class Darkkeepererror(Exception): pass class Darkkeepercacheerror(DarkKeeperError): pass class Darkkeepercachereaderror(DarkKeeperCacheError): pass class Darkkeepercachewriteerror(DarkKeeperCacheError): pass class Darkkeeperparseerror(DarkKeeperError): pass class Darkkeeperparsecontenterror(Dar...
""" Program: bouncy.py Project 4.8 This program calculates the total distance a ball travels as it bounces given: 1. the initial height of the ball 2. its bounciness index 3. the number of times the ball is allowed to continue bouncing """ height = float(input("Enter the height from which the ball is dropped: ")) bo...
""" Program: bouncy.py Project 4.8 This program calculates the total distance a ball travels as it bounces given: 1. the initial height of the ball 2. its bounciness index 3. the number of times the ball is allowed to continue bouncing """ height = float(input('Enter the height from which the ball is dropped: ')) bou...
def initialize(n): for key in ['queen','row','col','rwtose','swtose']: board[key]={} for i in range(n): board['queen'][i]=-1 board['row'][i]=0 board['col'][i]=0 for i in range(-(n-1),n): board['rwtose'][i]=0 for i in range(2*n-1): board['swtose'][i]=0 def...
def initialize(n): for key in ['queen', 'row', 'col', 'rwtose', 'swtose']: board[key] = {} for i in range(n): board['queen'][i] = -1 board['row'][i] = 0 board['col'][i] = 0 for i in range(-(n - 1), n): board['rwtose'][i] = 0 for i in range(2 * n - 1): boar...
class PackageManager: """ An object that contains the name used by dotstar and the true name of the PM (the one used by the OS, that dotstar calls when installing). dotstar don't uses the same name as the OS because snap has two mods of installation (sandbox and classic) so we have to differentiate ...
class Packagemanager: """ An object that contains the name used by dotstar and the true name of the PM (the one used by the OS, that dotstar calls when installing). dotstar don't uses the same name as the OS because snap has two mods of installation (sandbox and classic) so we have to differentiate ...
def raizI(x,b): if b** 2>x: return b-1 return raizI (x,b+1) raizI(11,5)
def raiz_i(x, b): if b ** 2 > x: return b - 1 return raiz_i(x, b + 1) raiz_i(11, 5)
lambda x: xx def write2(): pass def write(*args, **kw): raise NotImplementedError async def foo(one, *args, **kw): """ Args: args: Test """ data = yield from read_data(db)
lambda x: xx def write2(): pass def write(*args, **kw): raise NotImplementedError async def foo(one, *args, **kw): """ Args: args: Test """ data = (yield from read_data(db))
class Solution: def numberOfSteps (self, num: int) -> int: count = 0 while num!=0: print(num,count) if num==1: count+=1 return count if num%2==0: count+=1 else: c...
class Solution: def number_of_steps(self, num: int) -> int: count = 0 while num != 0: print(num, count) if num == 1: count += 1 return count if num % 2 == 0: count += 1 else: count += 2 ...
class ErrorSeverity(object): FATAL = 'fatal' ERROR = 'error' WARNING = 'warning' ALLOWED_VALUES = (FATAL, ERROR, WARNING) @classmethod def validate(cls, value): return value in cls.ALLOWED_VALUES
class Errorseverity(object): fatal = 'fatal' error = 'error' warning = 'warning' allowed_values = (FATAL, ERROR, WARNING) @classmethod def validate(cls, value): return value in cls.ALLOWED_VALUES
#!/usr/bin/env python3 def write_csv(filename, content): with open(filename, 'w') as csvfile: for line in content: for i, item in enumerate(line): csvfile.write(str(item)) if i != len(line) - 1: csvfile.write(',') csvfile.write('\n'...
def write_csv(filename, content): with open(filename, 'w') as csvfile: for line in content: for (i, item) in enumerate(line): csvfile.write(str(item)) if i != len(line) - 1: csvfile.write(',') csvfile.write('\n') def read_csv(filen...
'''Change the database in this file Change the database in this script locally Careful here '''
"""Change the database in this file Change the database in this script locally Careful here """