content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
n = int(input()) numbers = [] for _ in range(n): numbers.append(int(input())) for i in numbers: if i % 7 == 0: print(i ** 2)
n = int(input()) numbers = [] for _ in range(n): numbers.append(int(input())) for i in numbers: if i % 7 == 0: print(i ** 2)
class Solution: def isMatch(self, s: str, p: str) -> bool: self.s = s self.p = p @cache def match(p_idx, s_idx): if (s_idx == len(self.s) and p_idx == len(self.p)): return True if p_idx == len(self.p): ...
class Solution: def is_match(self, s: str, p: str) -> bool: self.s = s self.p = p @cache def match(p_idx, s_idx): if s_idx == len(self.s) and p_idx == len(self.p): return True if p_idx == len(self.p): return False ...
a=input() b=input() c=input() if len(a)+len(b) == len(c): print('YES') else: print('NO')
a = input() b = input() c = input() if len(a) + len(b) == len(c): print('YES') else: print('NO')
def get_mean(collection): """ Obtain the average of a collection of objects. Parameters ---------- collection : list A list of numbers Returns ------- float The mean of the numbers. """ return sum(collection) / len(collection)
def get_mean(collection): """ Obtain the average of a collection of objects. Parameters ---------- collection : list A list of numbers Returns ------- float The mean of the numbers. """ return sum(collection) / len(collection)
# Adapted from code written by Paul Kippes and released as # part of the Python standard library, see # https://github.com/python/cpython/blob/v3.8.5/Lib/sqlite3/dump.py CREATE_TABLE_PREFIX = "CREATE TABLE " def iterdump(connection): cu = connection.cursor() yield "BEGIN TRANSACTION;" writable_schema = F...
create_table_prefix = 'CREATE TABLE ' def iterdump(connection): cu = connection.cursor() yield 'BEGIN TRANSACTION;' writable_schema = False q = '\n SELECT "name", "type", "sql"\n FROM "sqlite_master"\n WHERE "sql" NOT NULL AND\n "type" == \'table\'\n ORDER BY "name"\n ' ...
def buildPalindrome(st): if st == st[::-1]: return st for i in range(len(st)): s = st + st[i::-1] if s == s[::-1]: return s def buildPalindrome(st): return re.sub(r"(\w+)\1", r"\1", st + st[::-1]) def buildPalindrome(st): i = 0 while st[i:] != st[i:][::-1]: ...
def build_palindrome(st): if st == st[::-1]: return st for i in range(len(st)): s = st + st[i::-1] if s == s[::-1]: return s def build_palindrome(st): return re.sub('(\\w+)\\1', '\\1', st + st[::-1]) def build_palindrome(st): i = 0 while st[i:] != st[i:][::-1]: ...
def sum(xs): # return the sum of all the elements in the list xs # remove the following line return 0 def test(test_case, expected): actual = sum(test_case) if actual == expected: print("Passed test for " + str(test_case)) else: print("Didn't pass test for " + str(test_case)) ...
def sum(xs): return 0 def test(test_case, expected): actual = sum(test_case) if actual == expected: print('Passed test for ' + str(test_case)) else: print("Didn't pass test for " + str(test_case)) print('The result was ' + str(actual) + ' but it should have been ' + str(expected...
""" Cage acts as the place where the score is stored before it goes into the actual score """ class Box: def __init__(self): """Initializes the class""" self.value = 0 def reset(self): """reset the box (when a 1 is rolled or after the score is stored)""" self.value = 0 def ...
""" Cage acts as the place where the score is stored before it goes into the actual score """ class Box: def __init__(self): """Initializes the class""" self.value = 0 def reset(self): """reset the box (when a 1 is rolled or after the score is stored)""" self.value = 0 de...
class APIError(Exception): """Raised when there is an API error""" pass class NotFound(Exception): """Raised on a 404 status code""" pass class UserNotFound(Exception): """Raised when a specified user cannot be found by the API""" pass class InvalidSearch(Exception): """Raised when a s...
class Apierror(Exception): """Raised when there is an API error""" pass class Notfound(Exception): """Raised on a 404 status code""" pass class Usernotfound(Exception): """Raised when a specified user cannot be found by the API""" pass class Invalidsearch(Exception): """Raised when a sear...
#Multiple of ten: number_of_ten = input("Please enter a number to check whether its multiple of 10 or not:") if (int(number_of_ten) % 10) == 0: print("Yes, your",number_of_ten,"is multiple of ten.") else: print("No, your",number_of_ten,"is not multiple of ten.")
number_of_ten = input('Please enter a number to check whether its multiple of 10 or not:') if int(number_of_ten) % 10 == 0: print('Yes, your', number_of_ten, 'is multiple of ten.') else: print('No, your', number_of_ten, 'is not multiple of ten.')
# Practice Python Exercise 4 -- Divisors # # This script asks the user for a number and returns all of the divisors of that number. # Get user input and convert to a number x = input('Enter a number: ') # Verify that input number is an integer try: x = float(x) except ValueError: print('The provided in put m...
x = input('Enter a number: ') try: x = float(x) except ValueError: print('The provided in put must be a number.\n') exit(1) x = int(x) if x < 1: print('The provided input must be greater than 0.') exit(1) a = [i for i in range(1, x + 1) if x % i == 0] print('The provided input ({}) is divisible by {...
class CircularQueue: DEFAULT_CAPACITY = 10 def __init__(self, initial_size = DEFAULT_CAPACITY): self._data = [None] * initial_size self._front = 0 self._back = 0 self._number_of_items = 0 def enqueue(self, item): self._check_capacity() self._data[self._back...
class Circularqueue: default_capacity = 10 def __init__(self, initial_size=DEFAULT_CAPACITY): self._data = [None] * initial_size self._front = 0 self._back = 0 self._number_of_items = 0 def enqueue(self, item): self._check_capacity() self._data[self._back] =...
def my_function(data=None): return_value = None if data is None: return return_value if isinstance(data, list): sum_of_data = sum(data) len_of_data = len(data) return sum_of_data/len_of_data else: return return_value
def my_function(data=None): return_value = None if data is None: return return_value if isinstance(data, list): sum_of_data = sum(data) len_of_data = len(data) return sum_of_data / len_of_data else: return return_value
def test_clean(imnetdb): imnetdb.wipe_database() imnetdb.ensure_database()
def test_clean(imnetdb): imnetdb.wipe_database() imnetdb.ensure_database()
class Solution: def arrayPairSum(self, arr: list[int]) -> int: s, n = 0, len(arr) arr.sort() for i in range(0, n, 2): s += arr[i] return s
class Solution: def array_pair_sum(self, arr: list[int]) -> int: (s, n) = (0, len(arr)) arr.sort() for i in range(0, n, 2): s += arr[i] return s
# 01.02.04 ASCII KAT print("(---)") print("(o o)") print("(=Y=)") print(" ( ) ")
print('(---)') print('(o o)') print('(=Y=)') print(' ( ) ')
""" PrimitivePShape. Using a PShape to display a primitive shape (in this case, ellipse). """ # The PShape object circle = None def setup(): size(640, 360, P2D) smooth() # Creating the PShape as an ellipse. circle = createShape(ELLIPSE, 0, 0, 100, 50) def draw(): background(51) # We can d...
""" PrimitivePShape. Using a PShape to display a primitive shape (in this case, ellipse). """ circle = None def setup(): size(640, 360, P2D) smooth() circle = create_shape(ELLIPSE, 0, 0, 100, 50) def draw(): background(51) circle.setStroke(color(255)) circle.setStrokeWeight(4) circle.se...
MAILGUN_URL = "<your mailgun URL>" MAILGUN_API_KEY = "<your mailgun key>" MAILGUN_FROM = "<email from address>" MAILGUN_TO = "<email to address>"
mailgun_url = '<your mailgun URL>' mailgun_api_key = '<your mailgun key>' mailgun_from = '<email from address>' mailgun_to = '<email to address>'
# -*- coding: utf-8 -*- # https://github.com/RDFLib/rdflib-jsonld/blob/feature/json-ld-1.1/rdflib_jsonld/errors.py class JSONLDException(ValueError): pass # http://www.w3.org/TR/json-ld-api/#idl-def-JsonLdErrorCode.{code-message} RECURSIVE_CONTEXT_INCLUSION = JSONLDException("recursive context inclusion") INVALID...
class Jsonldexception(ValueError): pass recursive_context_inclusion = jsonld_exception('recursive context inclusion') invalid_remote_context = jsonld_exception('invalid remote context')
GLOBAL_3 = "global 3" """Docs for global 3""" class Class3: """Docs for class 3""" def function_3(): """Docs for function 3"""
global_3 = 'global 3' 'Docs for global 3' class Class3: """Docs for class 3""" def function_3(): """Docs for function 3"""
def inverter_delay(): return 2 def and_gate_delay(): return 3 def or_gate_delay(): return 5
def inverter_delay(): return 2 def and_gate_delay(): return 3 def or_gate_delay(): return 5
def html_tag(tag): def wrap_text(msg): print('<{0}>{1}</{0}>'.format(tag,msg)) return wrap_text print_h1=html_tag('h1') print_h1('Test Headline') print_h1('Another Headline') print_p=html_tag('p') print_p('Test Paragraph')
def html_tag(tag): def wrap_text(msg): print('<{0}>{1}</{0}>'.format(tag, msg)) return wrap_text print_h1 = html_tag('h1') print_h1('Test Headline') print_h1('Another Headline') print_p = html_tag('p') print_p('Test Paragraph')
def bigint_check(val): """ Checks to see if `val` is or contains BIGINTs. Args: val (int, float, list): value or list of values to check. Returns: bool: True if `val` contains one or more BIGINT, False if not. """ if not isinstance(val, list) or isinstance(val, str): va...
def bigint_check(val): """ Checks to see if `val` is or contains BIGINTs. Args: val (int, float, list): value or list of values to check. Returns: bool: True if `val` contains one or more BIGINT, False if not. """ if not isinstance(val, list) or isinstance(val, str): va...
class Tags(object): @staticmethod def from_json(tags_json): result = [] for tag_json in tags_json: tag = Tag(key=tag_json['Key'], value=tag_json['Value']) return result
class Tags(object): @staticmethod def from_json(tags_json): result = [] for tag_json in tags_json: tag = tag(key=tag_json['Key'], value=tag_json['Value']) return result
n = int(input()) a = input().split() cont = 0 x = [] while cont < n: num = int(a[cont]) x.append(num) cont += 1 print("Menor valor:",min(x)) print("Posicao:",x.index((min(x))))
n = int(input()) a = input().split() cont = 0 x = [] while cont < n: num = int(a[cont]) x.append(num) cont += 1 print('Menor valor:', min(x)) print('Posicao:', x.index(min(x)))
""" 0783. Minimum Distance Between BST Nodes Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two different nodes in the tree. Example : Input: root = [4,2,6,1,3,null,null] Output: 1 Explanation: Note that root is a TreeNode object, not an array. The g...
""" 0783. Minimum Distance Between BST Nodes Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two different nodes in the tree. Example : Input: root = [4,2,6,1,3,null,null] Output: 1 Explanation: Note that root is a TreeNode object, not an array. The g...
class PredictedEntry: content_hash = "" web_address = "" bias_value = 0.0 def __init__(self, content_hash, web_address, bias_value): self.content_hash = content_hash self.web_address = web_address self.bias_value = bias_value
class Predictedentry: content_hash = '' web_address = '' bias_value = 0.0 def __init__(self, content_hash, web_address, bias_value): self.content_hash = content_hash self.web_address = web_address self.bias_value = bias_value
#!/usr/bin/python #create valid ipv4 address def valid_ip(ip): parts = ip.split('.') return ( len(parts) == 4 and all(part.isdigit() for part in parts) and all(0 <= int(part) <= 255 for part in parts) ) ip_address = raw_input("enter ip to check: ") if valid_ip(ip_address) is T...
def valid_ip(ip): parts = ip.split('.') return len(parts) == 4 and all((part.isdigit() for part in parts)) and all((0 <= int(part) <= 255 for part in parts)) ip_address = raw_input('enter ip to check: ') if valid_ip(ip_address) is True: print('valid ip!') else: print('no!')
try: file_path = input() all_time = 0 with open(file_path) as file: for line in file: arguments = line.split(',') distance = int(arguments[1]) - int(arguments[0]) + 1 speed = int(arguments[2]) time = float(distance / speed) all_time += tim...
try: file_path = input() all_time = 0 with open(file_path) as file: for line in file: arguments = line.split(',') distance = int(arguments[1]) - int(arguments[0]) + 1 speed = int(arguments[2]) time = float(distance / speed) all_time += time...
class Solution: def minDepth(self, root: Optional[TreeNode]) -> int: if not root: return 0 if not root.left: return self.minDepth(root.right) + 1 if not root.right: return self.minDepth(root.left) + 1 return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
class Solution: def min_depth(self, root: Optional[TreeNode]) -> int: if not root: return 0 if not root.left: return self.minDepth(root.right) + 1 if not root.right: return self.minDepth(root.left) + 1 return min(self.minDepth(root.left), self.min...
dashboard_module_description = { "cloud_element": ["Cloud Info", "Shows some info about the files in your cloud"], "joke_element": ["Random Joke", "Shows a random joke and lets you vote"], "quote_element": ["Random Quote", "Shows a random quote"], "news_element": ["SWC News", "Shows the latest SWC news"...
dashboard_module_description = {'cloud_element': ['Cloud Info', 'Shows some info about the files in your cloud'], 'joke_element': ['Random Joke', 'Shows a random joke and lets you vote'], 'quote_element': ['Random Quote', 'Shows a random quote'], 'news_element': ['SWC News', 'Shows the latest SWC news'], 'ripple_elemen...
filename = 'programming.txt' with open(filename, 'w') as file_object: file_object.write("I love programming.") with open(filename) as file_o: line = file_o.read() print(line)
filename = 'programming.txt' with open(filename, 'w') as file_object: file_object.write('I love programming.') with open(filename) as file_o: line = file_o.read() print(line)
lines = open('data.csv').read().split('\n') data = [(int(x[:x.find(',')]), float(x[x.find(',')+1:])) for x in lines if x] REPORT_THRESHOLD = 0.23 def get_error(scale, elasticity, growth): err = 0 bs_fac, fee_fac = 1 / (1 + elasticity), elasticity / (1 + elasticity) for i, (block_size, avg_fee) in enum...
lines = open('data.csv').read().split('\n') data = [(int(x[:x.find(',')]), float(x[x.find(',') + 1:])) for x in lines if x] report_threshold = 0.23 def get_error(scale, elasticity, growth): err = 0 (bs_fac, fee_fac) = (1 / (1 + elasticity), elasticity / (1 + elasticity)) for (i, (block_size, avg_fee)) in e...
def make_palindrome(s): ''' recursion implementation ''' #base case 1 if not s or len(s)==1: return s #base case 2 if s==s[::-1]: return s if s[0] == s[-1]: return s[0]+make_palindrome(s[1:-1]) + s[-1] else: x = s[0] + make_palindrome(s[1:]) + s[...
def make_palindrome(s): """ recursion implementation """ if not s or len(s) == 1: return s if s == s[::-1]: return s if s[0] == s[-1]: return s[0] + make_palindrome(s[1:-1]) + s[-1] else: x = s[0] + make_palindrome(s[1:]) + s[0] y = s[-1] + make_palind...
"""Package-specific exceptions.""" class NotFittedError(Exception): """Exception raised when predicting using an unfitted estimator.""" pass class ConvergenceError(Exception): """Exception raised when a model fails to converge.""" pass
"""Package-specific exceptions.""" class Notfittederror(Exception): """Exception raised when predicting using an unfitted estimator.""" pass class Convergenceerror(Exception): """Exception raised when a model fails to converge.""" pass
# Copyright 2017 QuantRocket - 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
def add_subparser(subparsers): _parser = subparsers.add_parser('calendar', description='QuantRocket calendar CLI', help='quantrocket calendar -h') _subparsers = _parser.add_subparsers(title='subcommands', dest='subcommand') _subparsers.required = True parser = _subparsers.add_parser('isopen', help='asse...
# following PEP 386 __version__ = "1.9.0" default_app_config = 'statici18n.apps.StaticI18NConfig'
__version__ = '1.9.0' default_app_config = 'statici18n.apps.StaticI18NConfig'
""" Settings to initialize scrapy """ BOT_NAME = 'emblemsnake' SPIDER_MODULES = ['emblemscraper.spiders'] NEWSPIDER_MODULE = 'emblemscraper.spiders' USER_AGENT = 'emblemsnake (+http://www.pradyothkukkapalli.com)' ROBOTSTXT_OBEY = True SPIDER_MIDDLEWARES = { 'scrapy_splash.SplashDeduplicateArgsMiddleware': 100, ...
""" Settings to initialize scrapy """ bot_name = 'emblemsnake' spider_modules = ['emblemscraper.spiders'] newspider_module = 'emblemscraper.spiders' user_agent = 'emblemsnake (+http://www.pradyothkukkapalli.com)' robotstxt_obey = True spider_middlewares = {'scrapy_splash.SplashDeduplicateArgsMiddleware': 100} downloade...
def part1(): """ Only two recipes are on the board: the first recipe got a score of 3, the second, 7. Each of the two Elves has a current recipe: the first Elf starts with the first recipe, and the second Elf starts with the second recipe. To create new recipes, the two Elves combine their current recipes. This ...
def part1(): """ Only two recipes are on the board: the first recipe got a score of 3, the second, 7. Each of the two Elves has a current recipe: the first Elf starts with the first recipe, and the second Elf starts with the second recipe. To create new recipes, the two Elves combine their current recipes. Thi...
# Assign a variable with a value x = 5 # Assign a variable with String y = "My Name is " y = "Vamsi " # Print the Value print (x) # Print the Type of Variable print(type(x)) # Print the Value print (y) # Print the Type of Variable print(type(y)) """ Append same type int """ a = 5 b = 10 c = a+b print("...
x = 5 y = 'My Name is ' y = 'Vamsi ' print(x) print(type(x)) print(y) print(type(y)) '\n\nAppend same type int\n\n' a = 5 b = 10 c = a + b print('Value of Variable C') print(c) print('Value of a+b') print(a + b) '\n\nAppend same type string\n\n' str = 'Hello' s = 'World' string = str + s print('Value of Variable string...
def get_strings(city): dict={} for i in city.lower(): if not i.isalpha(): continue dict[i]=dict.get(i, "")+"*" return ",".join(f"{i}:{j}" for i,j in dict.items())
def get_strings(city): dict = {} for i in city.lower(): if not i.isalpha(): continue dict[i] = dict.get(i, '') + '*' return ','.join((f'{i}:{j}' for (i, j) in dict.items()))
class SimpleScheduler(object): def __init__(self, optimizer, lr): self.optimizer = optimizer self.lr = lr def step(self): self.optimizer.param_groups[0]['lr'] = self.get_lr() self.optimizer.step() def get_lr(self): return self.lr
class Simplescheduler(object): def __init__(self, optimizer, lr): self.optimizer = optimizer self.lr = lr def step(self): self.optimizer.param_groups[0]['lr'] = self.get_lr() self.optimizer.step() def get_lr(self): return self.lr
class States(object): def __init__(self): self.init = 0 self.decimal = 1 self.decpoint = 2 self.afterdp = 3 self.e = 4 self.aftere = 5 self.sign = 6 self.nullpoint = 7 self.esign = 8 self.afteresign = 9 c...
class States(object): def __init__(self): self.init = 0 self.decimal = 1 self.decpoint = 2 self.afterdp = 3 self.e = 4 self.aftere = 5 self.sign = 6 self.nullpoint = 7 self.esign = 8 self.afteresign = 9 class Solution(object): de...
#!/usr/bin/env python # -*- mode:python; coding:utf-8 -*- Config = { 'connect_default_host': "localhost", 'connect_default_port': "8083", 'schema_registry_default_host': "localhost", 'schema_registry_default_port': "8081", }
config = {'connect_default_host': 'localhost', 'connect_default_port': '8083', 'schema_registry_default_host': 'localhost', 'schema_registry_default_port': '8081'}
#Return an array containing the numbers from 1 to N def fizzbuzz(n): l = [] for i in range(1, n+1): if i % 3 == 0 and i % 5 == 0: l.append("FizzBuzz") elif i % 3 == 0: l.append("Fizz") elif i % 5 == 0: l.append("Buzz") else: l.appen...
def fizzbuzz(n): l = [] for i in range(1, n + 1): if i % 3 == 0 and i % 5 == 0: l.append('FizzBuzz') elif i % 3 == 0: l.append('Fizz') elif i % 5 == 0: l.append('Buzz') else: l.append(i) return l def fizzbuzz(n): return ['F...
# Math # Find the smallest prime palindrome greater than or equal to N. # # Recall that a number is prime if it's only divisors are 1 and itself, and it is greater than 1. # # For example, 2,3,5,7,11 and 13 are primes. # # Recall that a number is a palindrome if it reads the same from left to right as it does from rig...
class Solution(object): def is_prime(self, n): if n == 2 or n == 3: return True if n < 2 or n % 2 == 0: return False if n % 3 == 0: return False r = int(n ** 0.5) f = 5 while f <= r: if n % f == 0: retur...
n, c, *a = map(int, open(0).read().split()) c1 = {} c2 = {} for i in range(1, 11): c1[i] = 0 c2[i] = 0 for x in a[::2]: c1[x] += 1 for x in a[1::2]: c2[x] += 1 result = float('inf') x = (n + 1) // 2 y = n - x for i in range(1, 10): for j in range(i + 1, 11): result = min(result, ((x - c1[i...
(n, c, *a) = map(int, open(0).read().split()) c1 = {} c2 = {} for i in range(1, 11): c1[i] = 0 c2[i] = 0 for x in a[::2]: c1[x] += 1 for x in a[1::2]: c2[x] += 1 result = float('inf') x = (n + 1) // 2 y = n - x for i in range(1, 10): for j in range(i + 1, 11): result = min(result, (x - c1[i]...
""" @no 43 @name Multiply Strings """ class Solution: def add(self, num1, num2): ans = '' count = 0 temp = 0 up = 0 while len(num1) - 1 - count >= 0 or len(num2) - 1 - count >= 0: a = int(num1[len(num1) - 1 - count]) if len(num1) - 1 - count >= 0 else 0 ...
""" @no 43 @name Multiply Strings """ class Solution: def add(self, num1, num2): ans = '' count = 0 temp = 0 up = 0 while len(num1) - 1 - count >= 0 or len(num2) - 1 - count >= 0: a = int(num1[len(num1) - 1 - count]) if len(num1) - 1 - count >= 0 else 0 ...
# Taxi (2150007) | Edelstein (1000064) optionList = [ 310040200, # Mine Entrance 310070000 # Haven ] destination = sm.sendNext("Where would you like to go? #b\r\n" "#L0# Verne Mine #l\r\n" "#L1# Haven #l\r\n") sm.warp(optionList[destination])
option_list = [310040200, 310070000] destination = sm.sendNext('Where would you like to go? #b\r\n#L0# Verne Mine #l\r\n#L1# Haven #l\r\n') sm.warp(optionList[destination])
# linelist.py # ALS 2017/06/14 # updated 2017/11/09: added MgII to narrowline """ include line list for spectral line related operations """ # ======= for continuum subtraction =========== narrowline = ['MgII', 'OII', 'OIII', 'OI', 'NII', 'NeV', 'SII', 'Ha', 'Hb', 'Hg', 'Hd', 'ArIII', 'NeIII', 'Dip', 'Mg', 'Na', 'He...
""" include line list for spectral line related operations """ narrowline = ['MgII', 'OII', 'OIII', 'OI', 'NII', 'NeV', 'SII', 'Ha', 'Hb', 'Hg', 'Hd', 'ArIII', 'NeIII', 'Dip', 'Mg', 'Na', 'He', 'HeI', 'HeII', 'FeVII'] broadline = ['Ha', 'Hb', 'Hg', 'Hd'] strongline = ['MgII2800', 'OII3730', 'NeIII3870', 'NeIII3969', 'H...
class Project: def __init__(self, name, slug, description, address=None, specs=None): self.name = name self.slug = slug self.description = description ### specs # never pass mutable data types as default arguments if specs is None: # note: "is" not "==" self.specs = [] else: self.specs = specs ...
class Project: def __init__(self, name, slug, description, address=None, specs=None): self.name = name self.slug = slug self.description = description if specs is None: self.specs = [] else: self.specs = specs if address is None: s...
class ChecksumCalculator: class FormatException(Exception): pass @staticmethod def prepare_code_string(code_string: str) -> str: retval = code_string.replace("-", "") retval = retval.replace(" ", "") return retval @staticmethod def calc_weighted_sum_check_digit(cod...
class Checksumcalculator: class Formatexception(Exception): pass @staticmethod def prepare_code_string(code_string: str) -> str: retval = code_string.replace('-', '') retval = retval.replace(' ', '') return retval @staticmethod def calc_weighted_sum_check_digit(cod...
class Solution: def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: longest=releaseTimes[0] output=keysPressed[0] for i in range(1,len(releaseTimes)) : if releaseTimes[i] - releaseTimes[i-1] > longest : longest=releaseTimes[i] - releaseTimes[i-...
class Solution: def slowest_key(self, releaseTimes: List[int], keysPressed: str) -> str: longest = releaseTimes[0] output = keysPressed[0] for i in range(1, len(releaseTimes)): if releaseTimes[i] - releaseTimes[i - 1] > longest: longest = releaseTimes[i] - releas...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None # reference: leetcode discussion forum class Solution: def isPalindrome(self, head: ListNode) -> bool: rev = None slow = head fast = head # fast will go 2x a...
class Listnode: def __init__(self, x): self.val = x self.next = None class Solution: def is_palindrome(self, head: ListNode) -> bool: rev = None slow = head fast = head while fast and fast.next: fast = fast.next.next (rev, rev.next, slow...
i = 1 j = 7 while i <= 9 and j != 5: print('I = {} J = {}'.format(i, j)) j -= 1 if j == 5: print('I = {} J = {}'.format(i, j)) i += 2 j = 7
i = 1 j = 7 while i <= 9 and j != 5: print('I = {} J = {}'.format(i, j)) j -= 1 if j == 5: print('I = {} J = {}'.format(i, j)) i += 2 j = 7
DUP_ENTRY = 1062 PARSE_ERROR = 1064 NO_SUCH_TABLE = 1146 DATA_TOO_LONG = 1406 ROW_IS_REFERENCED_2 = 1451
dup_entry = 1062 parse_error = 1064 no_such_table = 1146 data_too_long = 1406 row_is_referenced_2 = 1451
def wildcard_match(pattern, text, case_insensitive=True): """ Performs a case-insensitive wildcard match against two strings. This method works with pseduo-regex chars; specifically ? and * are supported. An asterisk (*) represents any combination of characters. A question mark (?) represents any si...
def wildcard_match(pattern, text, case_insensitive=True): """ Performs a case-insensitive wildcard match against two strings. This method works with pseduo-regex chars; specifically ? and * are supported. An asterisk (*) represents any combination of characters. A question mark (?) represents any si...
class Solution: def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ nums.sort() closest = float('inf') for i in range(1, len(nums) - 1): l, r = 0, len(nums) - 1 while l < i < r: ...
class Solution: def three_sum_closest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ nums.sort() closest = float('inf') for i in range(1, len(nums) - 1): (l, r) = (0, len(nums) - 1) while l < i...
# Copyright 2017, OpenCensus 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 w...
common_attributes = {'AGENT': 'g.co/agent', 'COMPONENT': '/component', 'ERROR_MESSAGE': '/error/message', 'ERROR_NAME': '/error/name', 'HTTP_CLIENT_CITY': '/http/client_city', 'HTTP_CLIENT_COUNTRY': '/http/client_country', 'HTTP_CLIENT_PROTOCOL': '/http/client_protocol', 'HTTP_CLIENT_REGION': '/http/client_region', 'HT...
Import("env") with open("version.txt") as fp: version = fp.readline() env.Replace(PROGNAME="firmware_%s" % version.replace(".", "_"))
import('env') with open('version.txt') as fp: version = fp.readline() env.Replace(PROGNAME='firmware_%s' % version.replace('.', '_'))
class RingGame: def reset(self): self.players = [] self.n_players = 0 self.n_active_players = 0 self.ante = 0 self.pot = 0 self.round = 0 def new_game(self, player_names, stakes, ante): self.players = [Player(name, stakes) for name in player_names] ...
class Ringgame: def reset(self): self.players = [] self.n_players = 0 self.n_active_players = 0 self.ante = 0 self.pot = 0 self.round = 0 def new_game(self, player_names, stakes, ante): self.players = [player(name, stakes) for name in player_names] ...
class DataServiceException(Exception): def __init__(self, message, status=400): self.message = message self.status = status
class Dataserviceexception(Exception): def __init__(self, message, status=400): self.message = message self.status = status
# Python3 program to sort an array without comparison operator. def sortArr(arr, n, min_no, max_no): # Count of elements in given range m = max_no - min_no + 1 # Count frequencies of all elements c = [0] * m for i in range(n): c[arr[i] - min_no] += 1 # Traverse through range. F...
def sort_arr(arr, n, min_no, max_no): m = max_no - min_no + 1 c = [0] * m for i in range(n): c[arr[i] - min_no] += 1 for i in range(m): for j in range(c[i]): print(i + min_no, end=' ') arr = [10, 10, 1, 4, 4, 100, 0] (min_no, max_no) = (0, 100) n = len(arr) sort_arr(arr, n, m...
class InvalidFileName(ValueError): def __init__(self, filename): self.message = 'Invalid file name: {}'.format(filename) super(ValueError, self).__init__(self.message)
class Invalidfilename(ValueError): def __init__(self, filename): self.message = 'Invalid file name: {}'.format(filename) super(ValueError, self).__init__(self.message)
# https://leetcode.com/problems/search-insert-position/ # Given a sorted array and a target value, return the index if the target is found. # If not, return the index where it would be if it were inserted in order. # # You may assume no duplicates in the array. # # Example 1: # Input: [1,3,5,6], 5 # Output: 2 # # Exam...
def search_insert(nums, target): return len([i for i in nums if i < target]) assert search_insert([1, 3, 5, 6], 5) == 2 assert search_insert([1, 3, 5, 6], 2) == 1 assert search_insert([1, 3, 5, 6], 7) == 4 assert search_insert([1, 3, 5, 6], 0) == 0
for _ in range(int(input())): a,b = map(int,input().split()) if a//2 + a%2 >=b: l = [["." for i in range(a)] for j in range(a)] k = 0 for i in range(0,a,2): if k<b: l[i][i] = "R" k += 1 else: break for i in l...
for _ in range(int(input())): (a, b) = map(int, input().split()) if a // 2 + a % 2 >= b: l = [['.' for i in range(a)] for j in range(a)] k = 0 for i in range(0, a, 2): if k < b: l[i][i] = 'R' k += 1 else: break ...
def create_tag(item, tag="a"): """ some function to wrapp HTML-tag with data-attributes around a string""" try: item_text = item.text except AttributeError: item_text = "no text provided" try: item_lang = item.language except AttributeError: item_lang = "no lang provi...
def create_tag(item, tag='a'): """ some function to wrapp HTML-tag with data-attributes around a string""" try: item_text = item.text except AttributeError: item_text = 'no text provided' try: item_lang = item.language except AttributeError: item_lang = 'no lang provi...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Purpose: pod endpoint Users methods ''' __author__ = 'Matt Joyce' __email__ = 'matt@joyce.nyc' __copyright__ = 'Copyright 2016, Symphony Communication Services LLC' class Users(object): def __init__(self, *args, **kwargs): super(Users, self)...
""" Purpose: pod endpoint Users methods """ __author__ = 'Matt Joyce' __email__ = 'matt@joyce.nyc' __copyright__ = 'Copyright 2016, Symphony Communication Services LLC' class Users(object): def __init__(self, *args, **kwargs): super(Users, self).__init__(*args, **kwargs) def get_userid_by...
def square_root(a, epsilon): x = 5 a = float(a) while True: y = (x + a/x) / 2 if abs(y-x) < epsilon: break x = y return y print(square_root(a=64, epsilon=0.0001))
def square_root(a, epsilon): x = 5 a = float(a) while True: y = (x + a / x) / 2 if abs(y - x) < epsilon: break x = y return y print(square_root(a=64, epsilon=0.0001))
""" Sudoku """ def sudoku2(grid): def dup_in_list(lst): numbers_only = [n for n in lst if n != '.'] print(numbers_only) return len(numbers_only) > len(set(numbers_only)) dups_in_rows = any(dup_in_list(row) for row in grid) dups_in_cols = any(dup_in_list([grid[r][c] for r in range...
""" Sudoku """ def sudoku2(grid): def dup_in_list(lst): numbers_only = [n for n in lst if n != '.'] print(numbers_only) return len(numbers_only) > len(set(numbers_only)) dups_in_rows = any((dup_in_list(row) for row in grid)) dups_in_cols = any((dup_in_list([grid[r][c] for r in ran...
SUCCESS_RESULT = "success" FAILURE_RESULT = "failure" def api_result(result, reason=None, **kwargs): rv = {} if result == SUCCESS_RESULT: rv["result"] = SUCCESS_RESULT else: rv["result"] = FAILURE_RESULT if reason: rv["reason"] = reason rv.update(kwargs) return rv ...
success_result = 'success' failure_result = 'failure' def api_result(result, reason=None, **kwargs): rv = {} if result == SUCCESS_RESULT: rv['result'] = SUCCESS_RESULT else: rv['result'] = FAILURE_RESULT if reason: rv['reason'] = reason rv.update(kwargs) return rv def c...
# Copyright (c) 2014 Doug Hellmann. All rights reserved. # # # All Rights Reserved # # # """ """ # end_pymotw_header
""" """
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: # paths = [] # if not root: return p...
class Solution: def binary_tree_paths(self, root: TreeNode) -> List[str]: path = [] if not root: return path def inorder(root): if not root: return path.append(root.val) inorder(root.left) if not root.left and (not...
class Node(): def __init__(self, val): self.val = val self.next = None def delete_last_occurrence(head, val): if not head: return None curr = head prev = None final_prev = None final_occ = None while curr != None: if curr.val == val: final_prev...
class Node: def __init__(self, val): self.val = val self.next = None def delete_last_occurrence(head, val): if not head: return None curr = head prev = None final_prev = None final_occ = None while curr != None: if curr.val == val: final_prev = p...
#!/usr/bin/env python3 __all__ = ['__version__'] __version__ = '0.3.7'
__all__ = ['__version__'] __version__ = '0.3.7'
class User_Credentials: """ Class that generates new instances of user credentials """ user_credential_list = [] def __init__(self, platform, firstname, secondname, username, phone_number, email, password): ''' __init__ method that helps us define properties for our objects. ...
class User_Credentials: """ Class that generates new instances of user credentials """ user_credential_list = [] def __init__(self, platform, firstname, secondname, username, phone_number, email, password): """ __init__ method that helps us define properties for our objects. ...
#This document demonstrates how to construct a Linked List using Python and perform various operations on the Linked List. class Node: def __init__(self,data=None,nextNode=None): self.__data = data self.__nextNode = nextNode def setData(self,newData): self.__data = newData def setNext(self,newNext)...
class Node: def __init__(self, data=None, nextNode=None): self.__data = data self.__nextNode = nextNode def set_data(self, newData): self.__data = newData def set_next(self, newNext): self.__nextNode = newNext def get_data(self): return self.__data def ge...
[[StockExplorer]] @route(explore="*") @templateArgs def stock_explore_screen(self): tabs = [("Explore","StockExploreSubApp"), ("Moving Average", "MovingAverageSubApp"), ("ACF and PACF", "AutoCorrelationSubApp")] return """ <style> .btn:active, .btn.active { background-color:aliceblue...
[[StockExplorer]] @route(explore='*') @templateArgs def stock_explore_screen(self): tabs = [('Explore', 'StockExploreSubApp'), ('Moving Average', 'MovingAverageSubApp'), ('ACF and PACF', 'AutoCorrelationSubApp')] return '\n<style> \n .btn:active, .btn.active {\n background-color:aliceblue;\n }\...
# TODO find a better way to do this # This script parses coq tactics\commands index pages and outputs relevant # keywords to be used in CodeMirror coq mode # X_data variables are taken from Coq 8.9.0 documentation commands_data = """ a Abort About Add @table Add Field Add LoadPath Add ML Path Add Morphism Ad...
commands_data = '\n\ta\n\tAbort\n\tAbout\n\tAdd @table\n\tAdd Field\n\tAdd LoadPath\n\tAdd ML Path\n\tAdd Morphism\n\tAdd Parametric Morphism\n\tAdd Parametric Relation\n\tAdd Rec LoadPath\n\tAdd Rec ML Path\n\tAdd Relation\n\tAdd Ring\n\tAdd Setoid\n\tAdmit Obligations\n\tAdmitted\n\tArguments\n\tArguments (implicits)...
class UserCredentialsExhaustedException(Exception): """ Raised when user's have exhausted in user pool """ pass class LoginFailureException(Exception): """ Failed to perform login """ pass
class Usercredentialsexhaustedexception(Exception): """ Raised when user's have exhausted in user pool """ pass class Loginfailureexception(Exception): """ Failed to perform login """ pass
"""Exceptions thrown by the stew scripts.""" class PythonProjectException(Exception): ... class CannotLoadProject(PythonProjectException): ... class NotAPoetryProject(PythonProjectException): ... class RequirementsOutdated(PythonProjectException): ... class PythonProjectNotFound(PythonProjectE...
"""Exceptions thrown by the stew scripts.""" class Pythonprojectexception(Exception): ... class Cannotloadproject(PythonProjectException): ... class Notapoetryproject(PythonProjectException): ... class Requirementsoutdated(PythonProjectException): ... class Pythonprojectnotfound(PythonProjectExcept...
#!/usr/bin/env python """ Summary ------- Useful matrix/modulus operations for mrg32k3a generator. Listing ------- mat33_mat31_mult mat33_mat33_mult mat31_mod mat33_mod mat33_mat33_mod mat33_power_mod """ def mat33_mat31_mult(A, b): """Multiply a 3x3 matrix with a 3x1 matrix. Parameters ---------- A...
""" Summary ------- Useful matrix/modulus operations for mrg32k3a generator. Listing ------- mat33_mat31_mult mat33_mat33_mult mat31_mod mat33_mod mat33_mat33_mod mat33_power_mod """ def mat33_mat31_mult(A, b): """Multiply a 3x3 matrix with a 3x1 matrix. Parameters ---------- A : 'list' ['list' ['flo...
host = "127.0.0.1" port = "9000" fastcgi = False debug = True database = "feeds.db" prefix = "/rss" auto_fetch = True compress = True
host = '127.0.0.1' port = '9000' fastcgi = False debug = True database = 'feeds.db' prefix = '/rss' auto_fetch = True compress = True
# Demo Python Try Except - Raise an exception ''' Raise an exception As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword. ''' # Raise a TypeError if x is not an integer: x = "hello" if not type(x) is int: raise TypeError("Onl...
""" Raise an exception As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword. """ x = 'hello' if not type(x) is int: raise type_error('Only integers are allowed')
list1 = [1, 2, 3] list2 = list1[:] list2.remove(2) print(list1) print(list2)
list1 = [1, 2, 3] list2 = list1[:] list2.remove(2) print(list1) print(list2)
expected_output = { "TenGigabitEthernet0/0/2": { "service_policy": { "output": { "policy_name": { "shape_priority": { "queue_stats_for_all_priority_classes": { "priority_level": { ...
expected_output = {'TenGigabitEthernet0/0/2': {'service_policy': {'output': {'policy_name': {'shape_priority': {'queue_stats_for_all_priority_classes': {'priority_level': {'1': {'queueing': True, 'queue_limit_us': 3932, 'queue_limit_bytes': 49152, 'queue_depth': 49476, 'total_drops': 44577300, 'no_buffer_drops': 0, 'pk...
# # PySNMP MIB module ASCEND-MIBIPX-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIBIPX-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:11:33 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
(configuration,) = mibBuilder.importSymbols('ASCEND-MIB', 'configuration') (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, single_value_constr...
def median (a, b, c): med = c if (b < c): if (a < b): med = b elif (a < c): med = a else: if (a > b): med = b elif (a > c): med = a return med
def median(a, b, c): med = c if b < c: if a < b: med = b elif a < c: med = a elif a > b: med = b elif a > c: med = a return med
def empty_view(request, *args, **kwargs): pass def kwargs_view(request, arg1=1, arg2=2): pass def absolute_kwargs_view(request, arg1=1, arg2=2): pass
def empty_view(request, *args, **kwargs): pass def kwargs_view(request, arg1=1, arg2=2): pass def absolute_kwargs_view(request, arg1=1, arg2=2): pass
#!/usr/bin/env python # # qc.constants.py: constants for QC pipeline # Copyright (C) University of Manchester 2019,2021 Peter Briggs # """ Provides the following constants for the QC pipeline: - FASTQ_SCREENS: tuple of screen names - PROTOCOLS: tuple of QC protocol names """ ##################################...
""" Provides the following constants for the QC pipeline: - FASTQ_SCREENS: tuple of screen names - PROTOCOLS: tuple of QC protocol names """ protocols = ('standardPE', 'standardSE', 'singlecell', '10x_scRNAseq', '10x_snRNAseq', '10x_scATAC', '10x_Visium', '10x_Multiome_GEX', '10x_Multiome_ATAC', '10x_CellPlex', 'ICELL...
# niconico.py - Exceptions class ExtractFailed(Exception): ...
class Extractfailed(Exception): ...
#!/usr/bin/env python3 """ Question 1: Promenade Fractions 1/1 L R 2/1 1/2 3/1 1/3 """ numerator = 1 denominator = 1 def iterate(directions, left, right): l, m = left r, s = right o = (l + r), (m + s) if len(directions) >= 1: if directions[0] == 'L': r...
""" Question 1: Promenade Fractions 1/1 L R 2/1 1/2 3/1 1/3 """ numerator = 1 denominator = 1 def iterate(directions, left, right): (l, m) = left (r, s) = right o = (l + r, m + s) if len(directions) >= 1: if directions[0] == 'L': return iterate(directions...
me = { "name": "milad", "family": "golchinpour", "age": 14, "email": "miladgolchinpour85@gmail.com" } print(me) print("------------") # .pop() # me.pop("name") # print(me) print("------------") # .popitem() # me.popitem() # print(me) print("------------") # .update() sec...
me = {'name': 'milad', 'family': 'golchinpour', 'age': 14, 'email': 'miladgolchinpour85@gmail.com'} print(me) print('------------') print('------------') print('------------') second_dict = {'name': 'milad'} secondDict.update(me) print(secondDict) print('--------------------') secondDict['name'] = 'sara' print(secondDi...
j = 7 for i in range(1,11,2): print('I={0} J={1}'.format(i,j)) print('I={0} J={1}'.format(i,j-1)) print('I={0} J={1}'.format(i,j-2)) j += 2
j = 7 for i in range(1, 11, 2): print('I={0} J={1}'.format(i, j)) print('I={0} J={1}'.format(i, j - 1)) print('I={0} J={1}'.format(i, j - 2)) j += 2
class kafka_config : def __init__(self): self.topic = "depot.task.status.log.1" self.bootstrap_servers = "localhost:9092"
class Kafka_Config: def __init__(self): self.topic = 'depot.task.status.log.1' self.bootstrap_servers = 'localhost:9092'
""" =========== Challenge 1 ============= Take an input from the command line, then convert it to an int and if it is even print 'the number is even' otherwise print 'the number is odd'. """ """ =========== Challenge 2 ============= Take an input from the command line, and convert i...
""" =========== Challenge 1 ============= Take an input from the command line, then convert it to an int and if it is even print 'the number is even' otherwise print 'the number is odd'. """ "\n =========== Challenge 2 =============\n\n Take an input from the command line, and \n convert ...
def reader(): input() print(sum(int(c) for c in input())) if __name__ == '__main__': reader()
def reader(): input() print(sum((int(c) for c in input()))) if __name__ == '__main__': reader()
# -*- coding: utf-8 -*- """ Created on Mon Feb 12 17:57:41 2018 @author: User """ def abbreviate(s): alphaset = [] newstring = '' for i in range(ord('a'), ord('z')+1): alphaset.append(chr(i)) for i in range(len(s)): count = 1 if s[i-1] == s[i]: count ...
""" Created on Mon Feb 12 17:57:41 2018 @author: User """ def abbreviate(s): alphaset = [] newstring = '' for i in range(ord('a'), ord('z') + 1): alphaset.append(chr(i)) for i in range(len(s)): count = 1 if s[i - 1] == s[i]: count += 1 print(s[i], count)...
class InvalidEvent(Exception): def __init__(self, p_value): self.__value = p_value def __str__(self): return repr(self.__value) class event_tools: @staticmethod def test_valid_event(p_event): """ Test if p_event is valid :param p_event: Event to check validity ...
class Invalidevent(Exception): def __init__(self, p_value): self.__value = p_value def __str__(self): return repr(self.__value) class Event_Tools: @staticmethod def test_valid_event(p_event): """ Test if p_event is valid :param p_event: Event to check validity...
balance = 999999 annualInterestRate = 0.18 InterestRate = annualInterestRate/12 low = balance/12 upper = (balance * (1 + InterestRate)**12)/12 x = balance while int(balance) != 0 or balance > 0: balance = x for i in range(12): balance = balance - (low + upper)/2 balance = balance + (In...
balance = 999999 annual_interest_rate = 0.18 interest_rate = annualInterestRate / 12 low = balance / 12 upper = balance * (1 + InterestRate) ** 12 / 12 x = balance while int(balance) != 0 or balance > 0: balance = x for i in range(12): balance = balance - (low + upper) / 2 balance = balance + In...