content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
''' >List of functions 1. contain(value,limit) - contains a value between 0 to limit ''' def contain(value,limit): if value<0: return value+limit elif value>=limit: return value-limit else: return value
""" >List of functions 1. contain(value,limit) - contains a value between 0 to limit """ def contain(value, limit): if value < 0: return value + limit elif value >= limit: return value - limit else: return value
#!/usr/bin/env python # -*- coding: utf-8 -*- # from unittest import mock # from datakit_dworld.push import Push def test_push(capsys): """Sample pytest test function with a built-in pytest fixture as an argument. """ # cmd = Greeting(None, None, cmd_name='dworld push') # parsed_args = mock.Mock() ...
def test_push(capsys): """Sample pytest test function with a built-in pytest fixture as an argument. """
# -*- coding: utf-8 -*- """ .. module:: pytfa :platform: Unix, Windows :synopsis: Simple Kinetic Models in Python .. moduleauthor:: SKiMPy team [---------] Copyright 2017 Laboratory of Computational Systems Biotechnology (LCSB), Ecole Polytechnique Federale de Lausanne (EPFL), Switzerland Licensed under the ...
""" .. module:: pytfa :platform: Unix, Windows :synopsis: Simple Kinetic Models in Python .. moduleauthor:: SKiMPy team [---------] Copyright 2017 Laboratory of Computational Systems Biotechnology (LCSB), Ecole Polytechnique Federale de Lausanne (EPFL), Switzerland Licensed under the Apache License, Version ...
class URLShortener: def __init__(self): self.id_counter = 0 self.links = {} def getURL(self, short_id): return self.links.get(short_id) def shorten(self, url): short_id = self.getNextId() self.links.update({short_id: url}) return short_id def getNextId...
class Urlshortener: def __init__(self): self.id_counter = 0 self.links = {} def get_url(self, short_id): return self.links.get(short_id) def shorten(self, url): short_id = self.getNextId() self.links.update({short_id: url}) return short_id def get_next...
print ('hello world') print ('hey i did something') print ('what happens if i do a ;'); print ('apparently nothing')
print('hello world') print('hey i did something') print('what happens if i do a ;') print('apparently nothing')
class Bank: def __init__(self): self.__agencies = [1111, 2222, 3333] self.__costumers = [] self.__accounts = [] def insert_costumers(self, costumer): self.__costumers.append(costumer) def insert_accounts(self, account): self.__accounts.append(account) def authe...
class Bank: def __init__(self): self.__agencies = [1111, 2222, 3333] self.__costumers = [] self.__accounts = [] def insert_costumers(self, costumer): self.__costumers.append(costumer) def insert_accounts(self, account): self.__accounts.append(account) def auth...
''' Python program to determine which triples sum to zero from a given list of lists. Input: [[1343532, -2920635, 332], [-27, 18, 9], [4, 0, -4], [2, 2, 2], [-20, 16, 4]] Output: [False, True, True, False, True] Input: [[1, 2, -3], [-4, 0, 4], [0, 1, -5], [1, 1, 1], [-2, 4, -1]] Output: [True, True, False, False, False...
""" Python program to determine which triples sum to zero from a given list of lists. Input: [[1343532, -2920635, 332], [-27, 18, 9], [4, 0, -4], [2, 2, 2], [-20, 16, 4]] Output: [False, True, True, False, True] Input: [[1, 2, -3], [-4, 0, 4], [0, 1, -5], [1, 1, 1], [-2, 4, -1]] Output: [True, True, False, False, False...
class AliasNotFound(Exception): def __init__(self, alias): self.alias = alias class AliasAlreadyExists(Exception): def __init__(self, alias): self.alias = alias class UnexpectedServerResponse(Exception): def __init__(self, response): self.response = response
class Aliasnotfound(Exception): def __init__(self, alias): self.alias = alias class Aliasalreadyexists(Exception): def __init__(self, alias): self.alias = alias class Unexpectedserverresponse(Exception): def __init__(self, response): self.response = response
def differentiate(fxn: str) -> str: if fxn == "x": return "1" dividedFxn = getFirstLevel(fxn) coeffOrTrig: str = dividedFxn[0] exponent: str = dividedFxn[2] insideParentheses: str = dividedFxn[1] if coeffOrTrig.isalpha(): ans = computeTrig(coeffOrTrig, insideParentheses) ...
def differentiate(fxn: str) -> str: if fxn == 'x': return '1' divided_fxn = get_first_level(fxn) coeff_or_trig: str = dividedFxn[0] exponent: str = dividedFxn[2] inside_parentheses: str = dividedFxn[1] if coeffOrTrig.isalpha(): ans = compute_trig(coeffOrTrig, insideParentheses) ...
class register: plugin_dict = {} plugin_name = [] @classmethod def register(cls, plugin_name): def wrapper(plugin): cls.plugin_dict[plugin_name] = plugin return plugin return wrapper
class Register: plugin_dict = {} plugin_name = [] @classmethod def register(cls, plugin_name): def wrapper(plugin): cls.plugin_dict[plugin_name] = plugin return plugin return wrapper
#B def average(As :list) -> float: return float(sum(As)/len(As)) def main(): # input As = list(map(int, input().split())) # compute # output print(average(As)) if __name__ == '__main__': main()
def average(As: list) -> float: return float(sum(As) / len(As)) def main(): as = list(map(int, input().split())) print(average(As)) if __name__ == '__main__': main()
if __name__ == '__main__': pass RESULT = 1 # DO NOT REMOVE NEXT LINE - KEEP IT INTENTIONALLY LAST assert RESULT == 1, ''
if __name__ == '__main__': pass result = 1 assert RESULT == 1, ''
class ToolNameAPI: thing = 'thing' toolname_tool = 'example' tln = ToolNameAPI() the_repo = "reponame" author = "authorname" profile = "authorprofile"
class Toolnameapi: thing = 'thing' toolname_tool = 'example' tln = tool_name_api() the_repo = 'reponame' author = 'authorname' profile = 'authorprofile'
class BaseFunction: def __init__(self, name, n_calls, internal_ns): self._name = name self._n_calls = n_calls self._internal_ns = internal_ns @property def name(self): return self._name @property def n_calls(self): return self._n_calls @property def...
class Basefunction: def __init__(self, name, n_calls, internal_ns): self._name = name self._n_calls = n_calls self._internal_ns = internal_ns @property def name(self): return self._name @property def n_calls(self): return self._n_calls @property de...
"""The PWM channel to use.""" CHANNEL0 = 0 """Channel zero.""" CHANNEL1 = 1 """Channel one."""
"""The PWM channel to use.""" channel0 = 0 'Channel zero.' channel1 = 1 'Channel one.'
S = str(input()) if S[0]==S[1] or S[1]==S[2] or S[2]==S[3]: print("Bad") else: print("Good")
s = str(input()) if S[0] == S[1] or S[1] == S[2] or S[2] == S[3]: print('Bad') else: print('Good')
def main(): squareSum = 0 #(1 + 2)^2 square of the sums sumSquare = 0 #1^2 + 2^2 sum of the squares for i in range(1, 101): sumSquare += i ** 2 squareSum += i squareSum = squareSum ** 2 print(str(squareSum - sumSquare)) if __name__ == '__main__': main()
def main(): square_sum = 0 sum_square = 0 for i in range(1, 101): sum_square += i ** 2 square_sum += i square_sum = squareSum ** 2 print(str(squareSum - sumSquare)) if __name__ == '__main__': main()
def find_space(board): for i in range(0,9): for j in range(0,9): if board[i][j]==0: return (i,j) return None def check(board,num,r,c): for i in range(0,9): if board[r][i]==num and c!=i: return False for i in range(0,9): if board[...
def find_space(board): for i in range(0, 9): for j in range(0, 9): if board[i][j] == 0: return (i, j) return None def check(board, num, r, c): for i in range(0, 9): if board[r][i] == num and c != i: return False for i in range(0, 9): if bo...
# A simple list myList = [10,20,4,5,6,2,9,10,2,3,34,14] #print the whole list print("The List is {}".format(myList)) # printing elemts of the list one by one print("printing elemts of the list one by one") for elements in myList: print(elements) print("") #printing elements that are greater than 10 only prin...
my_list = [10, 20, 4, 5, 6, 2, 9, 10, 2, 3, 34, 14] print('The List is {}'.format(myList)) print('printing elemts of the list one by one') for elements in myList: print(elements) print('') print('printing elements that are greater than 10 only') for elements in myList: if elements > 10: print(elements) ...
#!/usr/bin/env python # encoding: utf-8 ''' @author: yuxiqian @license: MIT @contact: akaza_akari@sjtu.edu.cn @software: electsys-api @file: electsysApi/shared/exception.py @time: 2019/1/9 ''' class RequestError(BaseException): pass class ParseError(BaseException): pass class ParseWarning(Warning): pa...
""" @author: yuxiqian @license: MIT @contact: akaza_akari@sjtu.edu.cn @software: electsys-api @file: electsysApi/shared/exception.py @time: 2019/1/9 """ class Requesterror(BaseException): pass class Parseerror(BaseException): pass class Parsewarning(Warning): pass
class Solution: def duplicateZeros(self, arr: List[int]) -> None: """ Do not return anything, modify arr in-place instead. """ i = 0 for num in list(arr): if i >= len(arr): break arr[i] = num if not num: i += 1 ...
class Solution: def duplicate_zeros(self, arr: List[int]) -> None: """ Do not return anything, modify arr in-place instead. """ i = 0 for num in list(arr): if i >= len(arr): break arr[i] = num if not num: i ...
def extractKaedesan721TumblrCom(item): ''' Parser for 'kaedesan721.tumblr.com' ''' bad_tags = [ 'FanArt', "htr asks", 'Spanish translations', 'htr anime','my thoughts', 'Cats', 'answered', 'ask meme', 'relay convos', 'translation related post', 'nightmare fuel', '...
def extract_kaedesan721_tumblr_com(item): """ Parser for 'kaedesan721.tumblr.com' """ bad_tags = ['FanArt', 'htr asks', 'Spanish translations', 'htr anime', 'my thoughts', 'Cats', 'answered', 'ask meme', 'relay convos', 'translation related post', 'nightmare fuel', 'htr manga', 'memes', 'htrweek', 'Video Game...
#!/usr/bin/python3 # --- 001 > U5W2P1_Task3_w1 def solution(i): return float(i) if __name__ == "__main__": print('----------start------------') i = 12 print(solution( i )) print('------------end------------')
def solution(i): return float(i) if __name__ == '__main__': print('----------start------------') i = 12 print(solution(i)) print('------------end------------')
n = int(input()) intz = [int(x) for x in input().split()] alice = 0 bob = 0 for i, num in zip(range(n), sorted(intz)[::-1]): if i%2 == 0: alice += num else: bob += num print(alice, bob)
n = int(input()) intz = [int(x) for x in input().split()] alice = 0 bob = 0 for (i, num) in zip(range(n), sorted(intz)[::-1]): if i % 2 == 0: alice += num else: bob += num print(alice, bob)
# -*- coding: utf-8 -*- """ Created on Mon Apr 13 13:35:33 2020 """ #for finding loss of significances x=1e-1 flag = True a=0 while (flag): print (((2*x)/(1-(x**2))),"......",(1/(1+x))-(1/(1-x))) x= x*(1e-1) a=a+1 if(a==25): flag=False
""" Created on Mon Apr 13 13:35:33 2020 """ x = 0.1 flag = True a = 0 while flag: print(2 * x / (1 - x ** 2), '......', 1 / (1 + x) - 1 / (1 - x)) x = x * 0.1 a = a + 1 if a == 25: flag = False
class Test: def __init__(self): pass def hi(self): print("hello world")
class Test: def __init__(self): pass def hi(self): print('hello world')
def rec_sum(n): if(n<=1): return n else: return(n+rec_sum(n-1))
def rec_sum(n): if n <= 1: return n else: return n + rec_sum(n - 1)
class Solution(object): def twoSum(self, nums, target): seen = {} output = [] for i in range(len(nums)): k = target - nums[i] if k in seen: output.append(seen[k]) output.append(i) del seen[k] else: ...
class Solution(object): def two_sum(self, nums, target): seen = {} output = [] for i in range(len(nums)): k = target - nums[i] if k in seen: output.append(seen[k]) output.append(i) del seen[k] else: ...
# # PySNMP MIB module HPN-ICF-VOICE-IF-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-VOICE-IF-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:41:57 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (defau...
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_size_constraint, constraints_union, constraints_intersection, value_range_constraint) ...
# standard traversal problem class Solution(object): def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ # leaf condition if root == None: return 0 # skeleton, since function has return, need to assign variables for followin...
class Solution(object): def max_depth(self, root): """ :type root: TreeNode :rtype: int """ if root == None: return 0 left_depth = self.maxDepth(root.left) right_depth = self.maxDepth(root.right) return max(left_depth, right_depth) + 1
class GlobalOptions: """ Class to evaluate global options for example: project path""" @staticmethod def evaluate_project_path(path): """ Method to parse the project path provided by the user""" first_dir_from_end = None if path[-1] != "/": path = path + "/" new_p...
class Globaloptions: """ Class to evaluate global options for example: project path""" @staticmethod def evaluate_project_path(path): """ Method to parse the project path provided by the user""" first_dir_from_end = None if path[-1] != '/': path = path + '/' new_...
gScore = 0 #use this to index g(n) fScore = 1 #use this to index f(n) previous = 2 #use this to index previous node inf = 10000 #use this for value of infinity #we represent the graph usind adjacent list #as dictionary of dictionaries G = { 'biratnagar' : {'itahari' : 22, 'biratchowk' : 30, 'rangeli': 2...
g_score = 0 f_score = 1 previous = 2 inf = 10000 g = {'biratnagar': {'itahari': 22, 'biratchowk': 30, 'rangeli': 25}, 'itahari': {'biratnagar': 22, 'dharan': 20, 'biratchowk': 11}, 'dharan': {'itahari': 20}, 'biratchowk': {'biratnagar': 30, 'itahari': 11, 'kanepokhari': 10}, 'rangeli': {'biratnagar': 25, 'kanepokhari':...
t=int(input("")) while (t>0): n=int(input("")) f=1 for i in range(1,n+1): f=f*i print(f) t=t-1
t = int(input('')) while t > 0: n = int(input('')) f = 1 for i in range(1, n + 1): f = f * i print(f) t = t - 1
class Solution(object): def isUgly(self, num): """ :type num: int :rtype: bool """ if num <= 0: return False for x in [2,3,5]: while(num % x ==0): num /= x return num==1
class Solution(object): def is_ugly(self, num): """ :type num: int :rtype: bool """ if num <= 0: return False for x in [2, 3, 5]: while num % x == 0: num /= x return num == 1
#Area of a rectangle = width x length #Perimeter of a rectangle = 2 x [length + width# width_input = float (input("\nPlease enter width: ")) length_input = float (input("Please enter length: ")) areaofRectangle = width_input * length_input perimeterofRectangle = 2 * (width_input * length_input) print ("\n...
width_input = float(input('\nPlease enter width: ')) length_input = float(input('Please enter length: ')) areaof_rectangle = width_input * length_input perimeterof_rectangle = 2 * (width_input * length_input) print('\nArea of Rectangle is: ', areaofRectangle, 'CM') print('\nPerimeter of Rectangle is: ', perimeterofRect...
class DNASuitEdge: COMPONENT_CODE = 22 def __init__(self, startPoint, endPoint, zoneId): self.startPoint = startPoint self.endPoint = endPoint self.zoneId = zoneId def setStartPoint(self, startPoint): self.startPoint = startPoint def setEndPoint(self, endPoint): ...
class Dnasuitedge: component_code = 22 def __init__(self, startPoint, endPoint, zoneId): self.startPoint = startPoint self.endPoint = endPoint self.zoneId = zoneId def set_start_point(self, startPoint): self.startPoint = startPoint def set_end_point(self, endPoint): ...
# This just shifts 1 to i th BIT def BIT(i: int) -> int: return int(1 << i) # This class is equvalent to a C++ enum class EventType: Null, \ WindowClose, WindowResize, WindowFocus, WindowMoved, \ AppTick, AppUpdate, Ap...
def bit(i: int) -> int: return int(1 << i) class Eventtype: (null, window_close, window_resize, window_focus, window_moved, app_tick, app_update, app_render, key_pressed, key_released, char_input, mouse_button_pressed, mouse_button_released, mouse_moved, mouse_scrolled) = range(0, 15) class Eventcategory: ...
class Users: usernamep = 'your_user_email' passwordp = 'your_password' linkp = 'https://www.instagram.com/stories/cznburak/'
class Users: usernamep = 'your_user_email' passwordp = 'your_password' linkp = 'https://www.instagram.com/stories/cznburak/'
INSTANCES = 405 ITERS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 50, 100] N_ITERS = len(ITERS) # === RESULTS GATHERING ====================================================== # # results_m is a [INSTANCES][N_ITERS] matrix to store every test result results_m = [[0 for x in range(...
instances = 405 iters = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 50, 100] n_iters = len(ITERS) results_m = [[0 for x in range(N_ITERS)] for y in range(INSTANCES)] for i in range(N_ITERS): fin = open('tests/' + str(ITERS[I])) out = fin.read() fin.close() counter = 0 ...
# -*- coding: utf-8 -*- # Copyright 1996-2015 PSERC. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. # Copyright (c) 2016-2020 by University of Kassel and Fraunhofer Institute for Energy Economics # and Energy System Technology (IEE), Kassel. ...
"""Defines constants for named column indices to bus matrix. Some examples of usage, after defining the constants using the line above, are:: Pd = bus[3, PD] # get the real power demand at bus 4 bus[:, VMIN] = 0.95 # set the min voltage magnitude to 0.95 at all buses The index, name and meaning of each c...
# # PySNMP MIB module SW-VLAN-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SW-VLAN-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:12:44 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...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, value_size_constraint, constraints_union, constraints_intersection, single_value_constraint) ...
class DFA: current_state = None current_letter = None valid = True def __init__( self, name, alphabet, states, delta_function, start_state, final_states ): self.name = name self.alphabet = alphabet self.states = states self.delta_function = delta_function ...
class Dfa: current_state = None current_letter = None valid = True def __init__(self, name, alphabet, states, delta_function, start_state, final_states): self.name = name self.alphabet = alphabet self.states = states self.delta_function = delta_function self.star...
class LambdaError(Exception): def __init__(self, description): self.description = description class BadRequestError(LambdaError): pass class ForbiddenError(LambdaError): pass class InternalServerError(LambdaError): pass class NotFoundError(LambdaError): pass class ValidationError(L...
class Lambdaerror(Exception): def __init__(self, description): self.description = description class Badrequesterror(LambdaError): pass class Forbiddenerror(LambdaError): pass class Internalservererror(LambdaError): pass class Notfounderror(LambdaError): pass class Validationerror(Lambd...
""" # Sample code to perform I/O: name = input() # Reading input from STDIN print('Hi, %s.' % name) # Writing output to STDOUT # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail """ # Write your code here n, m = map(int, input().strip().split()) a ...
""" # Sample code to perform I/O: name = input() # Reading input from STDIN print('Hi, %s.' % name) # Writing output to STDOUT # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail """ (n, m) = map(int, input().strip().split()) a = sorted(map(int, inpu...
pkgname = "xrandr" pkgver = "1.5.1" pkgrel = 0 build_style = "gnu_configure" hostmakedepends = ["pkgconf"] makedepends = ["libxrandr-devel"] pkgdesc = "Command line interface to X RandR extension" maintainer = "q66 <q66@chimera-linux.org>" license = "MIT" url = "https://xorg.freedesktop.org" source = f"$(XORG_SITE)/app...
pkgname = 'xrandr' pkgver = '1.5.1' pkgrel = 0 build_style = 'gnu_configure' hostmakedepends = ['pkgconf'] makedepends = ['libxrandr-devel'] pkgdesc = 'Command line interface to X RandR extension' maintainer = 'q66 <q66@chimera-linux.org>' license = 'MIT' url = 'https://xorg.freedesktop.org' source = f'$(XORG_SITE)/app...
# Validate input while True: print('Enter your age:') age = input() if age.isdecimal(): break print('Pleas enter a number for your age.')
while True: print('Enter your age:') age = input() if age.isdecimal(): break print('Pleas enter a number for your age.')
# # PySNMP MIB module Fore-Common-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Fore-Common-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:14:34 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_union, single_value_constraint, constraints_intersection, value_size_constraint) ...
class Page(object): def __init__(self, params): self.size = 2 ** 10 self.Time = False self.R = False self.M = False
class Page(object): def __init__(self, params): self.size = 2 ** 10 self.Time = False self.R = False self.M = False
PROMQL = """ start: query // Binary operations are defined separately in order to support precedence ?query\ : or_match | matrix | subquery | offset ?or_match\ : and_unless_match | or_match OR grouping? and_unless_match ?and_unless_match\ : comparison_match | and_unless_match (AND | ...
promql = '\nstart: query\n\n// Binary operations are defined separately in order to support precedence\n\n?query : or_match\n | matrix\n | subquery\n | offset\n\n?or_match : and_unless_match\n | or_match OR grouping? and_unless_match\n\n?and_unless_match : comparison_match\n | and_unless_match (...
ftxus = { 'api_key':'YOUR_API_KEY', 'api_secret':'YOUR_API_SECRET' }
ftxus = {'api_key': 'YOUR_API_KEY', 'api_secret': 'YOUR_API_SECRET'}
a = [1, 2, 3, 4] def subset(a, n): if n == 1: return n else: return (subset(a[n - 1]), subset(a[n - 2])) print(subset(a, n=4))
a = [1, 2, 3, 4] def subset(a, n): if n == 1: return n else: return (subset(a[n - 1]), subset(a[n - 2])) print(subset(a, n=4))
def print_formatted(number): # your code goes here for i in range(1, number +1): width = len(f"{number:b}") print(f"{i:{width}} {i:{width}o} {i:{width}X} {i:{width}b}")
def print_formatted(number): for i in range(1, number + 1): width = len(f'{number:b}') print(f'{i:{width}} {i:{width}o} {i:{width}X} {i:{width}b}')
class Solution: def coinChange(self, coins: List[int], amount: int) -> int: dp = [inf] * (amount + 1) dp[0] = 0 for coin in coins: for x in range(coin, amount + 1): dp[x] = min(dp[x], dp[x - coin] + 1) return dp[amount] if dp[amount] != inf else -1
class Solution: def coin_change(self, coins: List[int], amount: int) -> int: dp = [inf] * (amount + 1) dp[0] = 0 for coin in coins: for x in range(coin, amount + 1): dp[x] = min(dp[x], dp[x - coin] + 1) return dp[amount] if dp[amount] != inf else -1
# # PySNMP MIB module Intel-Common-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Intel-Common-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:54:14 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, constraints_intersection, value_range_constraint, value_size_constraint, single_value_constraint) ...
name = input() class_school = 1 sum_of_grades = 0 ejected = False failed = 0 while True: grade = float(input()) if grade >= 4.00: sum_of_grades += grade if class_school == 12: break class_school += 1 else: failed += 1 if failed == 2: ejected ...
name = input() class_school = 1 sum_of_grades = 0 ejected = False failed = 0 while True: grade = float(input()) if grade >= 4.0: sum_of_grades += grade if class_school == 12: break class_school += 1 else: failed += 1 if failed == 2: ejected = T...
class Solution: def minSwapsCouples(self, row: List[int]) -> int: parent=[i for i in range(len(row))] for i in range(1,len(row),2): parent[i]-=1 def findpath(u,parent): if parent[u]!=u: parent[u]=findpath(parent[u],parent) ...
class Solution: def min_swaps_couples(self, row: List[int]) -> int: parent = [i for i in range(len(row))] for i in range(1, len(row), 2): parent[i] -= 1 def findpath(u, parent): if parent[u] != u: parent[u] = findpath(parent[u], parent) r...
class Token: def __init__(self, type=None, value=None): self.type = type self.value = value def __str__(self): return "Token({0}, {1})".format(self.type, self.value)
class Token: def __init__(self, type=None, value=None): self.type = type self.value = value def __str__(self): return 'Token({0}, {1})'.format(self.type, self.value)
""" Define convention-based global, coordinate and variable attributes in one place for consistent reuse """ DEFAULT_BEAM_COORD_ATTRS = { "frequency": { "long_name": "Transducer frequency", "standard_name": "sound_frequency", "units": "Hz", "valid_min": 0.0, }, "ping_time": ...
""" Define convention-based global, coordinate and variable attributes in one place for consistent reuse """ default_beam_coord_attrs = {'frequency': {'long_name': 'Transducer frequency', 'standard_name': 'sound_frequency', 'units': 'Hz', 'valid_min': 0.0}, 'ping_time': {'long_name': 'Timestamp of each ping', 'standard...
""" ******************************************************************************** * Name: pagintate.py * Author: nswain * Created On: April 17, 2018 * Copyright: (c) Aquaveo 2018 ******************************************************************************** """ def paginate(objects, results_per_page, page, resul...
""" ******************************************************************************** * Name: pagintate.py * Author: nswain * Created On: April 17, 2018 * Copyright: (c) Aquaveo 2018 ******************************************************************************** """ def paginate(objects, results_per_page, page, result...
def not_found_handler(): return '404. Path not found' def internal_error_handler(): return '500. Internal error'
def not_found_handler(): return '404. Path not found' def internal_error_handler(): return '500. Internal error'
# ~*~ coding: utf-8 ~*~ __doc__ = """ `opencannabis.media` --------------------------- Records and definitions that structure digital media and related assets. """ # `opencannabis.media`
__doc__ = '\n\n `opencannabis.media`\n ---------------------------\n Records and definitions that structure digital media and related assets.\n\n'
# -*- coding: utf-8 -*- """ Exceptions for Arequests Created on Tue Nov 13 08:34:14 2018 @author: gfi """ class ArequestsError(Exception): """Basic exception for errors raised by Arequests""" pass class AuthorizationError(ArequestsError): '''401 error new authentification required''' pass class Some...
""" Exceptions for Arequests Created on Tue Nov 13 08:34:14 2018 @author: gfi """ class Arequestserror(Exception): """Basic exception for errors raised by Arequests""" pass class Authorizationerror(ArequestsError): """401 error new authentification required""" pass class Someclienterror(ArequestsErr...
def transform_file(infile,outfile,templates): with open(infile,'r') as fh: indata = fh.read() lines = indata.split('\n') outlines = [] for line in lines: if '//ATL_BEGIN' in line: start = line.find('//ATL_BEGIN') spacing = line[:start] s...
def transform_file(infile, outfile, templates): with open(infile, 'r') as fh: indata = fh.read() lines = indata.split('\n') outlines = [] for line in lines: if '//ATL_BEGIN' in line: start = line.find('//ATL_BEGIN') spacing = line[:start] start = line....
#!/usr/bin/env python # Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
task_type = '' header = [] header_defaults = [] input_numeric_feature_names = [] constructed_numeric_feature_names = [] input_categorical_feature_names_with_identity = {} constructed_categorical_feature_names_with_identity = {} input_categorical_feature_names_with_vocabulary = {} input_categorical_feature_names_with_ha...
# # # This is Support for Drawing Bullet Charts # # # # # # # ''' This is the return json value to the javascript front end { "canvasName":"canvas1","featuredColor":"Green", "featuredMeasure":14.5, "qualScale1":14.5, "qualScale1Color":"Black","titleText":"Step 1" }, ...
""" This is the return json value to the javascript front end { "canvasName":"canvas1","featuredColor":"Green", "featuredMeasure":14.5, "qualScale1":14.5, "qualScale1Color":"Black","titleText":"Step 1" }, { "canvasName":"can...
declerations_test_text_001 = ''' list1 = [ 1, ] ''' declerations_test_text_002 = ''' list1 = [ 1, 2, ] ''' declerations_test_text_003 = ''' tuple1 = ( 1, ) ''' declerations_test_text_004 = ''' tuple1 = ( 1, 2, ) ''' declerations_test_text_005 = ''' set1 = { 1, } ''' declerations_test_text_00...
declerations_test_text_001 = '\nlist1 = [\n 1,\n]\n' declerations_test_text_002 = '\nlist1 = [\n 1,\n 2,\n]\n' declerations_test_text_003 = '\ntuple1 = (\n 1,\n)\n' declerations_test_text_004 = '\ntuple1 = (\n 1,\n 2,\n)\n' declerations_test_text_005 = '\nset1 = {\n 1,\n}\n' declerations_test_text_...
"""Build rules to create C++ code from an Antlr4 grammar.""" def antlr4_cc_lexer(name, src, namespaces = None, imports = None, deps = None, lib_import = None): """Generates the C++ source corresponding to an antlr4 lexer definition. Args: name: The name of the package to use for the cc_library. sr...
"""Build rules to create C++ code from an Antlr4 grammar.""" def antlr4_cc_lexer(name, src, namespaces=None, imports=None, deps=None, lib_import=None): """Generates the C++ source corresponding to an antlr4 lexer definition. Args: name: The name of the package to use for the cc_library. src: The a...
class AnimationException(SystemException,ISerializable,_Exception): """ The exception that is thrown when an error occurs while animating a property. """ def add_SerializeObjectState(self,*args): """ add_SerializeObjectState(self: Exception,value: EventHandler[SafeSerializationEventArgs]) """ pass def remov...
class Animationexception(SystemException, ISerializable, _Exception): """ The exception that is thrown when an error occurs while animating a property. """ def add__serialize_object_state(self, *args): """ add_SerializeObjectState(self: Exception,value: EventHandler[SafeSerializationEventArgs]) """ ...
file_berita = open("berita.txt", "r") berita = file_berita.read() berita = berita.split() berita = [x.lower() for x in berita] berita = list(set(berita)) berita = sorted(berita) print (berita)
file_berita = open('berita.txt', 'r') berita = file_berita.read() berita = berita.split() berita = [x.lower() for x in berita] berita = list(set(berita)) berita = sorted(berita) print(berita)
""" @Fire https://github.com/fire717 """ cfg = { ##### Global Setting 'GPU_ID': '0', "num_workers":8, "random_seed":42, "cfg_verbose":True, "save_dir": "output/", "num_classes": 17, "width_mult":1.0, "img_size": 192, ##### Train Setting 'img_path':"./data/croped/img...
""" @Fire https://github.com/fire717 """ cfg = {'GPU_ID': '0', 'num_workers': 8, 'random_seed': 42, 'cfg_verbose': True, 'save_dir': 'output/', 'num_classes': 17, 'width_mult': 1.0, 'img_size': 192, 'img_path': './data/croped/imgs', 'train_label_path': './data/croped/train2017.json', 'val_label_path': './data/croped/va...
rzymskie={'I':1,'II':2,'III':3,'IV':4,'V':5,'VI':6,'VII':7,'VIII':8} print(rzymskie) print('Jeden element slownika: \n') print(rzymskie['I'])
rzymskie = {'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5, 'VI': 6, 'VII': 7, 'VIII': 8} print(rzymskie) print('Jeden element slownika: \n') print(rzymskie['I'])
H, W = map(int, input().split()) A = [input() for _ in range(H)] if H + W - 1 == sum(a.count('#') for a in A): print('Possible') else: print('Impossible')
(h, w) = map(int, input().split()) a = [input() for _ in range(H)] if H + W - 1 == sum((a.count('#') for a in A)): print('Possible') else: print('Impossible')
""" Get an Etree library. Usage:: >>> from anyetree import etree Returns some etree library. Looks for (in order of decreasing preference): * ``lxml.etree`` (http://cheeseshop.python.org/pypi/lxml/) * ``xml.etree.cElementTree`` (built into Python 2.5) * ``cElementTree`` (http://effbot.org/zone/celem...
""" Get an Etree library. Usage:: >>> from anyetree import etree Returns some etree library. Looks for (in order of decreasing preference): * ``lxml.etree`` (http://cheeseshop.python.org/pypi/lxml/) * ``xml.etree.cElementTree`` (built into Python 2.5) * ``cElementTree`` (http://effbot.org/zone/celem...
# File: etl.py # Purpose: To do the `Transform` step of an Extract-Transform-Load. # Programmer: Amal Shehu # Course: Exercism # Date: Thursday 22 September 2016, 03:40 PM def transform(words): new_words = dict() for point, letters in words.items(): for letter in letters: ...
def transform(words): new_words = dict() for (point, letters) in words.items(): for letter in letters: new_words[letter.lower()] = point return new_words
def have(subj, obj): subj.add(obj) def change(subj, obj, state): pass if __name__ == '__main__': main()
def have(subj, obj): subj.add(obj) def change(subj, obj, state): pass if __name__ == '__main__': main()
# A bot that picks the first action from the list for the first two rounds, # and then exists with an exception. # Used only for tests. game_name = input() play_as = int(input()) print("ready") while True: print("start") num_actions = 0 while True: message = input() if message == "tourname...
game_name = input() play_as = int(input()) print('ready') while True: print('start') num_actions = 0 while True: message = input() if message == 'tournament over': print('tournament over') sys.exit(0) if message.startswith('match over'): print('mat...
''' f we want to add a single element to an existing set, we can use the .add() operation. It adds the element to the set and returns 'None'. Example >>> s = set('HackerRank') >>> s.add('H') >>> print s set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R']) >>> print s.add('HackerRank') None >>> print s set(['a', 'c', 'e', '...
""" f we want to add a single element to an existing set, we can use the .add() operation. It adds the element to the set and returns 'None'. Example >>> s = set('HackerRank') >>> s.add('H') >>> print s set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R']) >>> print s.add('HackerRank') None >>> print s set(['a', 'c', 'e', '...
class LeagueGame: def __init__(self, data): self.patch = data['patch'] self.win = data['win'] self.side = data['side'] self.opp = data['opp'] self.bans = data['bans'] self.vs_bans = data['vs_bans'] self.picks = data['picks'] self.vs_picks = data['vs_picks'] self.players = data['players'] class Lea...
class Leaguegame: def __init__(self, data): self.patch = data['patch'] self.win = data['win'] self.side = data['side'] self.opp = data['opp'] self.bans = data['bans'] self.vs_bans = data['vs_bans'] self.picks = data['picks'] self.vs_picks = data['vs_p...
text1 = '''ABCDEF GHIJKL MNOPQRS TUVWXYZ ''' text2 = 'ABCDEF\ GHIJKL\ MNOPQRS\ TUVWXYZ' text3 = 'ABCD\'EF\'GHIJKL' text4 = 'ABCDEF\nGHIJKL\nMNOPQRS\nTUVWXYZ' text5 = 'ABCDEF\fGHIJKL\fMNOPQRS\fTUVWXYZ' print(text1) print('-' * 25) print(text2) print('-' * 25) print(text3) print('-' * 25) print(text4) print('-' * 2...
text1 = 'ABCDEF\nGHIJKL\nMNOPQRS\nTUVWXYZ\n' text2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' text3 = "ABCD'EF'GHIJKL" text4 = 'ABCDEF\nGHIJKL\nMNOPQRS\nTUVWXYZ' text5 = 'ABCDEF\x0cGHIJKL\x0cMNOPQRS\x0cTUVWXYZ' print(text1) print('-' * 25) print(text2) print('-' * 25) print(text3) print('-' * 25) print(text4) print('-' * 25) print...
# unihernandez22 # https://atcoder.jp/contests/abc166/tasks/abc166_d # math, brute force n = int(input()) for a in range(n): breaked = True for b in range(-1000, 1000): if a**5 - b**5 == n: print(a, b) break; else: breaked = False if breaked: break
n = int(input()) for a in range(n): breaked = True for b in range(-1000, 1000): if a ** 5 - b ** 5 == n: print(a, b) break else: breaked = False if breaked: break
T = int(input()) P = int(input()) controle = 0 #Uso para guardar o valor maior que o limite while P != 0: P = int(input()) if P >= T: controle = 1 #coloquei 1 so pra ser diferente de 0 if controle == 1: print("ALARME") else: print("O Havai pode dormir tranquilo")
t = int(input()) p = int(input()) controle = 0 while P != 0: p = int(input()) if P >= T: controle = 1 if controle == 1: print('ALARME') else: print('O Havai pode dormir tranquilo')
__all__ = [ "aggregation", "association", "composition", "connection", "containment", "dependency", "includes", "membership", "ownership", "responsibility", "usage" ]
__all__ = ['aggregation', 'association', 'composition', 'connection', 'containment', 'dependency', 'includes', 'membership', 'ownership', 'responsibility', 'usage']
class AxisIndex(): #TODO: read this value from config file LEFT_RIGHT=0 FORWARD_BACKWARDS=1 ROTATE=2 UP_DOWN=3 class ButtonIndex(): TRIGGER = 0 SIDE_BUTTON = 1 HOVERING = 2 EXIT = 10 class ThresHold(): SENDING_TIME = 0.5
class Axisindex: left_right = 0 forward_backwards = 1 rotate = 2 up_down = 3 class Buttonindex: trigger = 0 side_button = 1 hovering = 2 exit = 10 class Threshold: sending_time = 0.5
#!/Users/francischen/opt/anaconda3/bin/python #pythons sorts are STABLE: order is the same as original in tie. # sort: key, reverse q = ['two','twelve','One','3'] #sort q, result being a modified list. nothing is returned q.sort() print(q) q = ['two','twelve','One','3',"this has lots of t's"] q.sort(reverse=True) pr...
q = ['two', 'twelve', 'One', '3'] q.sort() print(q) q = ['two', 'twelve', 'One', '3', "this has lots of t's"] q.sort(reverse=True) print(q) def f(x): return x.count('t') q.sort(key=f) print(q) q = ['twelve', 'two', 'One', '3', "this has lots of t's"] q.sort(key=f) print(q) q = ['twelve', 'two', 'One', '3', "this h...
# buildifier: disable=module-docstring load(":native_tools_toolchain.bzl", "access_tool") def get_cmake_data(ctx): return _access_and_expect_label_copied("@rules_foreign_cc//tools/build_defs:cmake_toolchain", ctx, "cmake") def get_ninja_data(ctx): return _access_and_expect_label_copied("@rules_foreign_cc//too...
load(':native_tools_toolchain.bzl', 'access_tool') def get_cmake_data(ctx): return _access_and_expect_label_copied('@rules_foreign_cc//tools/build_defs:cmake_toolchain', ctx, 'cmake') def get_ninja_data(ctx): return _access_and_expect_label_copied('@rules_foreign_cc//tools/build_defs:ninja_toolchain', ctx, 'n...
fname = input("Enter file name: ") if len(fname) < 1 : fname = "mbox-short.txt" list = list() f = open(fname) count = 0 for line in f: line = line.rstrip() list = line.split() if list == []: continue elif list[0].lower() == 'from': count += 1 print(list[1]) print("There w...
fname = input('Enter file name: ') if len(fname) < 1: fname = 'mbox-short.txt' list = list() f = open(fname) count = 0 for line in f: line = line.rstrip() list = line.split() if list == []: continue elif list[0].lower() == 'from': count += 1 print(list[1]) print('There were',...
class FollowupEvent: def __init__(self, name, data=None): self.name = name self.data = data class Response: def __init__(self, text=None, followup_event=None): self.speech = text self.display_text = text self.followup_event = followup_event class UserInput: def _...
class Followupevent: def __init__(self, name, data=None): self.name = name self.data = data class Response: def __init__(self, text=None, followup_event=None): self.speech = text self.display_text = text self.followup_event = followup_event class Userinput: def _...
# Problem Name: Suffix Trie Construction # Problem Description: # Write a SuffixTrie class for Suffix-Trie-like data structures. The class should have a root property set to be the root node of the trie and should support: # - Creating the trie from a string; this will be done by calling populateSuffixTrieFrom me...
""" Explain the solution: - Building a suffix-trie-like data structure consists of essentially storing every suffix of a given string in a trie. To do so, iterate through the input string one character at a time, and insert every substring starting at each character and ending at the end of string into the trie. - To ...
def test_list_devices(client): devices = client.devices() assert len(devices) > 0 assert any(map(lambda device: device.serial == "emulator-5554", devices)) def test_list_devices_by_state(client): devices = client.devices(client.BOOTLOADER) assert len(devices) == 0 devices = client.devices(clie...
def test_list_devices(client): devices = client.devices() assert len(devices) > 0 assert any(map(lambda device: device.serial == 'emulator-5554', devices)) def test_list_devices_by_state(client): devices = client.devices(client.BOOTLOADER) assert len(devices) == 0 devices = client.devices(clien...
"""Top-level package for Goldmeister.""" __author__ = """Micah Johnson""" __email__ = 'micah.johnson150@gmail.com' __version__ = '0.2.0'
"""Top-level package for Goldmeister.""" __author__ = 'Micah Johnson' __email__ = 'micah.johnson150@gmail.com' __version__ = '0.2.0'
def si(p,r,t): n= (p+r+t)//3 return n
def si(p, r, t): n = (p + r + t) // 3 return n
#!/usr/bin/env python3 # This is gonna be up to you. But basically I envisioned a system where you have a students in a classroom. Where the # classroom only has information, like who is the teacher, how many students are there. And it's like an online class, # so students don't know who their peers are, or who their ...
class Student: def __init__(self, name, laziness=5): self.name = name self.preparedness = 0 self._laziness = laziness def take_test(self, hardness): return 0 def do_homework(self): return 0 def study(self): pass class Teacher: def __init__(self, ...
# https://github.com/ArtemNikolaev/gb-hw/issues/24 def multiple_of_20_21(): return (i for i in range(20, 241) if i % 20 == 0 or i % 21 == 0) print(list(multiple_of_20_21()))
def multiple_of_20_21(): return (i for i in range(20, 241) if i % 20 == 0 or i % 21 == 0) print(list(multiple_of_20_21()))
def cc_resources(name, data): out_inc = name + ".inc" cmd = ('echo "static const struct FileToc kPackedFiles[] = {" > $(@); \n' + "for j in $(SRCS); do\n" + ' echo "{\\"$$(basename "$${j}")\\"," >> $(@);\n' + ' echo "R\\"filecontent($$(< $${j}))filecontent\\"" >> $(@);\n' + ...
def cc_resources(name, data): out_inc = name + '.inc' cmd = 'echo "static const struct FileToc kPackedFiles[] = {" > $(@); \n' + 'for j in $(SRCS); do\n' + ' echo "{\\"$$(basename "$${j}")\\"," >> $(@);\n' + ' echo "R\\"filecontent($$(< $${j}))filecontent\\"" >> $(@);\n' + ' echo "}," >> $(@);\n' + 'done &&\...
class Person: def __init__(self, name, age): self.name = name self.age = age def say_hello(self): print('Hello, my name is {} and I am {} years old'.format(self.name, self.age)) if __name__ == '__main__': person = Person('David', 34) print('Age: {}'.format(person.age)) ...
class Person: def __init__(self, name, age): self.name = name self.age = age def say_hello(self): print('Hello, my name is {} and I am {} years old'.format(self.name, self.age)) if __name__ == '__main__': person = person('David', 34) print('Age: {}'.format(person.age)) pers...
num= int (input("enter number of rows=")) for i in range (1,num+1): for j in range(1,num-i+1): print (" ",end="") for j in range(2 and 9): print("2","9") for i in range(1, 6): for j in range(1, 10): if i==5 or i+j==5 or j-i==4: print("*", end...
num = int(input('enter number of rows=')) for i in range(1, num + 1): for j in range(1, num - i + 1): print(' ', end='') for j in range(2 and 9): print('2', '9') for i in range(1, 6): for j in range(1, 10): if i == 5 or i + j == 5 or j - i == 4: print('*', end='') ...
''' Problem:- Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example 1: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. ''' class Solution: def longestPalindrome(self, s: str) -> str: res = "" resL...
""" Problem:- Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example 1: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. """ class Solution: def longest_palindrome(self, s: str) -> str: res = '' re...
def _doxygen_archive_impl(ctx): """Generate a .tar.gz archive containing documentation using Doxygen. Args: name: label for the generated rule. The archive will be "%{name}.tar.gz". doxyfile: configuration file for Doxygen, @@OUTPUT_DIRECTORY@@ will be replaced with the actual output dir ...
def _doxygen_archive_impl(ctx): """Generate a .tar.gz archive containing documentation using Doxygen. Args: name: label for the generated rule. The archive will be "%{name}.tar.gz". doxyfile: configuration file for Doxygen, @@OUTPUT_DIRECTORY@@ will be replaced with the actual output dir ...
# 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 minDiffInBST(self, root: Optional[TreeNode]) -> int: output=[] stack=[root] whil...
class Solution: def min_diff_in_bst(self, root: Optional[TreeNode]) -> int: output = [] stack = [root] while stack: cur = stack.pop(0) output.append(cur.val) if cur.left: stack.append(cur.left) if cur.right: sta...
PREFIX = "/video/tvkultura" NAME = "TVKultura.Ru" ICON = "tvkultura.png" ART = "tvkultura.jpg" BASE_URL = "https://tvkultura.ru/" BRAND_URL = BASE_URL+"brand/" # Channel initialization def Start(): ObjectContainer.title1 = NAME HTTP.Headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko...
prefix = '/video/tvkultura' name = 'TVKultura.Ru' icon = 'tvkultura.png' art = 'tvkultura.jpg' base_url = 'https://tvkultura.ru/' brand_url = BASE_URL + 'brand/' def start(): ObjectContainer.title1 = NAME HTTP.Headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0' ...