content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def beau(vals, diff): lookup = set(vals) result = [] for x in vals: if x - diff in lookup and x + diff in lookup: result.append((x - diff, x, x + diff)) return result n, d = map(int, input().split()) values = tuple(map(int, input().split())) triplets = beau(values, d) print...
def beau(vals, diff): lookup = set(vals) result = [] for x in vals: if x - diff in lookup and x + diff in lookup: result.append((x - diff, x, x + diff)) return result (n, d) = map(int, input().split()) values = tuple(map(int, input().split())) triplets = beau(values, d) print(len(tri...
"""ex113 - Funcoes aprofundadas em Python""" def leiaInt(msg): while True: try: n = int(input(msg)) break except (ValueError, TypeError): print("\033[31mERRO: por favor, digite um numero inteiro valido.\033[m") continue return n def leiaFloat(m...
"""ex113 - Funcoes aprofundadas em Python""" def leia_int(msg): while True: try: n = int(input(msg)) break except (ValueError, TypeError): print('\x1b[31mERRO: por favor, digite um numero inteiro valido.\x1b[m') continue return n def leia_float(m...
class matrix: def __init__(self, data): self.data = [data] if type(data[0]) != list else data #if not all(list(map(lambda x: len(x) == len(self.data[0]), self.data))): raise ValueError("Matrix shape is not OK") self.row = len(self.data) self.col = len(self.data[0]) se...
class Matrix: def __init__(self, data): self.data = [data] if type(data[0]) != list else data self.row = len(self.data) self.col = len(self.data[0]) self.shape = (self.row, self.col) def __null__(self, shape, key=1, diag=False): (row, col) = shape if row != col ...
# In the Manager class of Self Check 11, override the getName method so that managers # have a * before their name (such as *Lin, Sally ). class Employee(): def __init__(self, name="", base_salary=0.0): self._name = name self._base_salary = base_salary def set_name(self, new_name): se...
class Employee: def __init__(self, name='', base_salary=0.0): self._name = name self._base_salary = base_salary def set_name(self, new_name): self._name = new_name def set_base_salary(self, new_salary): self._base_salary = new_salary def get_name(self): return...
typenames = {"int": 4} operations = {"+=", "-="} class VarNameCreator: state = 0 def __init__(self, state=0): self.state = state def char2latin(self, char): x = ('%s' % hex(ord(char)))[2:] #print(x, char) ans = [] #print(x) for el in x: if '0' <= el <= '9': ans.append(chr(ord(el) - ord('0') + ...
typenames = {'int': 4} operations = {'+=', '-='} class Varnamecreator: state = 0 def __init__(self, state=0): self.state = state def char2latin(self, char): x = ('%s' % hex(ord(char)))[2:] ans = [] for el in x: if '0' <= el <= '9': ans.append(ch...
#--------------------------------------- #Since : 2019/04/25 #Update: 2021/11/18 # -*- coding: utf-8 -*- #--------------------------------------- class Parameters: def __init__(self): #Game setting self.board_x = 8 # boad size self.board_y = self.board_...
class Parameters: def __init__(self): self.board_x = 8 self.board_y = self.board_x self.action_size = self.board_x * self.board_y + 1 self.black = 1 self.white = -1 self.num_mcts_sims = 400 self.cpuct = 1.25 self.opening_train = 0 self.opening...
print("Bienvenido al cajero automatico de este banco") print() usuario=int(input("Ingrese la cantidad de dinero que desea\n")) cant500 = usuario // 500 resto500 = usuario % 500 cant200 = resto500 // 200 resto200 = resto500 % 200 cant100 = resto200 // 100 resto100 = resto200 % 100 print("cant de billetes de 500: ", ...
print('Bienvenido al cajero automatico de este banco') print() usuario = int(input('Ingrese la cantidad de dinero que desea\n')) cant500 = usuario // 500 resto500 = usuario % 500 cant200 = resto500 // 200 resto200 = resto500 % 200 cant100 = resto200 // 100 resto100 = resto200 % 100 print('cant de billetes de 500: ', ca...
def f(yan): xan = yan*3 xan -= 2 fin1 = [] tant = [0,1] for i in range(xan): shet = i shet2 = i+1 newr = tant[shet] + tant[shet2] tant.append(int(newr)) #2part for i in range(xan): gav = tant.pop() if (gav % 2 == 0): fin1.append(gav) ...
def f(yan): xan = yan * 3 xan -= 2 fin1 = [] tant = [0, 1] for i in range(xan): shet = i shet2 = i + 1 newr = tant[shet] + tant[shet2] tant.append(int(newr)) for i in range(xan): gav = tant.pop() if gav % 2 == 0: fin1.append(gav) fi...
""" Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm? """ __author__ = 'Daniel' class Solution(object): def hIndex(self, A): """ Given sorted -> binary search From linear search into bin search :type A: List[int] ...
""" Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm? """ __author__ = 'Daniel' class Solution(object): def h_index(self, A): """ Given sorted -> binary search From linear search into bin search :type A: List[int] ...
_BEGIN = 0 BLACK=0 WHITE=1 GRAY=2 _END = 12
_begin = 0 black = 0 white = 1 gray = 2 _end = 12
def swap(s,n): res=bin(n)[2:]*(len(s)//len(bin(n)[2:])+1) index=0 string="" for i in range(len(s)): if not s[i].isalpha(): string+=s[i] continue string+=s[i].swapcase() if res[index]=="1" else s[i] index+=1 return string
def swap(s, n): res = bin(n)[2:] * (len(s) // len(bin(n)[2:]) + 1) index = 0 string = '' for i in range(len(s)): if not s[i].isalpha(): string += s[i] continue string += s[i].swapcase() if res[index] == '1' else s[i] index += 1 return string
class Solution: def XXX(self, s: str) -> int: blank_count = 0 start = 0 for index in range(len(s)): if s[index] != " ": if blank_count == 0: continue else: blank_count = 0 start = index ...
class Solution: def xxx(self, s: str) -> int: blank_count = 0 start = 0 for index in range(len(s)): if s[index] != ' ': if blank_count == 0: continue else: blank_count = 0 start = index ...
# class node to store data and next class Node: def __init__(self,data, next=None, prev=None): self.data = data self.next = next self.prev = prev # defining getter and setter for data, next and prev def getData(self): return self.data def setData(self, data): self.data = data def...
class Node: def __init__(self, data, next=None, prev=None): self.data = data self.next = next self.prev = prev def get_data(self): return self.data def set_data(self, data): self.data = data def get_next_node(self): return self.next def set_next_n...
# Hello world ''' We will use this file to write our first statement in Python Pretty simple: print('Hello world') '''
""" We will use this file to write our first statement in Python Pretty simple: print('Hello world') """
class Point: def __init__(self, x, y): self.x = x self.y = y point = Point(3, 5) print(f"The Point x value is {point.x}") print(f"The Point y value is {point.y}")
class Point: def __init__(self, x, y): self.x = x self.y = y point = point(3, 5) print(f'The Point x value is {point.x}') print(f'The Point y value is {point.y}')
# The Fibonacci Sequence # The Fibonacci sequence begins with fibonacci(0) = 0 and fibonacci(1) = 1 as its respective first and second terms. After these first two elements, each subsequent element is equal to the sum of the previous two elements. def fibonacci(n): if n == 0 or n == 1: return n ret...
def fibonacci(n): if n == 0 or n == 1: return n return fibonacci(n - 1) + fibonacci(n - 2) fib_list = [] for i in range(0, 11): fib_list.append(fibonacci(i)) print(fib_list)
""" category: Model Variations name: Steady State Distrubtion descr: Run repeated steady state calculations using random parameters (based on min/max parameter values) menu: yes icon: module.png tool: no """ items = tc_allItems() params = tc_getParameters(items) params2 = fromTC(params) avgvalues = params2[2][0] minval...
""" category: Model Variations name: Steady State Distrubtion descr: Run repeated steady state calculations using random parameters (based on min/max parameter values) menu: yes icon: module.png tool: no """ items = tc_all_items() params = tc_get_parameters(items) params2 = from_tc(params) avgvalues = params2[2][0] min...
# -*- coding: utf-8 -*- """ eater.errors ~~~~~~~~~~~~ A place for errors that are raised by Eater. """ __all__ = [ 'EaterError', 'EaterTimeoutError', 'EaterConnectError', 'EaterUnexpectedError', 'EaterUnexpectedResponseError' ] class EaterError(Exception): """ Base Eater erro...
""" eater.errors ~~~~~~~~~~~~ A place for errors that are raised by Eater. """ __all__ = ['EaterError', 'EaterTimeoutError', 'EaterConnectError', 'EaterUnexpectedError', 'EaterUnexpectedResponseError'] class Eatererror(Exception): """ Base Eater error. """ class Eatertimeouterror(EaterError):...
# # PySNMP MIB module WWP-LEOS-PORT-STATS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WWP-LEOS-PORT-STATS-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:31:30 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 ...
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_range_constraint, constraints_union, value_size_constraint, constraints_intersection) ...
""" Makes a list of the files to be copied from source to destination. Notes: Couldn't make this doctest work, so useful only as a visual test. >>> from GDLC.GDLC import * # Copy a list of files to the default directory: >>> template_copy(dir='~/GDLC/source/GDLC_unpacked') # doctest:+ELLIPSIS [PosixPath('.../mobi7/...
""" Makes a list of the files to be copied from source to destination. Notes: Couldn't make this doctest work, so useful only as a visual test. >>> from GDLC.GDLC import * # Copy a list of files to the default directory: >>> template_copy(dir='~/GDLC/source/GDLC_unpacked') # doctest:+ELLIPSIS [PosixPath('.../mobi7/...
def partition(arr, left, right): pivot = arr[left] low = left + 1 high = right while low <= high: while low <= right and pivot > arr[low]: low += 1 while high > left and pivot < arr[high]: high -= 1 if (low <= high): arr[low], arr[high] = arr[...
def partition(arr, left, right): pivot = arr[left] low = left + 1 high = right while low <= high: while low <= right and pivot > arr[low]: low += 1 while high > left and pivot < arr[high]: high -= 1 if low <= high: (arr[low], arr[high]) = (arr[...
# Copyright (c) 2019 Cisco and/or its affiliates. # 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 ag...
"""Constants used in CSIT.""" class Constants(object): """Constants used in CSIT. TODO: Yaml files are easier for humans to edit. Figure out how to set the attributes by parsing a file that works regardless of current working directory. """ remote_fw_dir = '/tmp/openvpp-testing' resources_...
sieve = [0] * 300001 for i in range(6, 300000, 7): sieve[i] = sieve[i+2] = 1 MSprimes = [] for i in range(6, 300000, 7): if sieve[i] == 1: MSprimes.append(i) for j in range(2*i, 300000, i): sieve[j] = 0 if sieve[i+2] == 1: MSprimes.append(i+2) for j in range(2*(i...
sieve = [0] * 300001 for i in range(6, 300000, 7): sieve[i] = sieve[i + 2] = 1 m_sprimes = [] for i in range(6, 300000, 7): if sieve[i] == 1: MSprimes.append(i) for j in range(2 * i, 300000, i): sieve[j] = 0 if sieve[i + 2] == 1: MSprimes.append(i + 2) for j in ra...
N = int(input()) a = list(map(int, input().split())) a.sort(reverse=True) print(sum(a[1::2][:N]))
n = int(input()) a = list(map(int, input().split())) a.sort(reverse=True) print(sum(a[1::2][:N]))
if m > 1: b = 'metros equivalem' else: b = 'metro equivale' #https://pt.stackoverflow.com/q/413280/101
if m > 1: b = 'metros equivalem' else: b = 'metro equivale'
# Test of 3.5+ GET_YIELD_FROM_ITER # Code is from https://stackoverflow.com/questions/41136410/python-yield-from-or-return-a-generator def add(a, b): return a + b def sqrt(a): return a ** 0.5 data1 = [*zip(range(1, 3))] # [(1,), (2,)] job1 = (sqrt, data1) def gen_factory(func, seq): """Generator facto...
def add(a, b): return a + b def sqrt(a): return a ** 0.5 data1 = [*zip(range(1, 3))] job1 = (sqrt, data1) def gen_factory(func, seq): """Generator factory returning a generator.""" print('build generator & return') return (func(*args) for args in seq) def gen_generator(func, seq): """Generato...
__version__ = '0.1.0' def cli(): print("Hello from child CLI!")
__version__ = '0.1.0' def cli(): print('Hello from child CLI!')
input_data = '1901,12.3\n1902,45.6\n1903,78.9' print('input data is:') print(input_data) as_lines = input_data.split('\n') print('as lines:') print(as_lines) for line in as_lines: fields = line.split(',') year = int(fields[0]) value = float(fields[1]) print(year, ':', value)
input_data = '1901,12.3\n1902,45.6\n1903,78.9' print('input data is:') print(input_data) as_lines = input_data.split('\n') print('as lines:') print(as_lines) for line in as_lines: fields = line.split(',') year = int(fields[0]) value = float(fields[1]) print(year, ':', value)
def get_function_at(bv, addr): """ Gets the function that contains a given address, even if that address isn't the start of the function """ blocks = bv.get_basic_blocks_at(addr) return blocks[0].function if (blocks is not None and len(blocks) > 0) else None def find_mlil(func, addr): return find_i...
def get_function_at(bv, addr): """ Gets the function that contains a given address, even if that address isn't the start of the function """ blocks = bv.get_basic_blocks_at(addr) return blocks[0].function if blocks is not None and len(blocks) > 0 else None def find_mlil(func, addr): return find_in_...
"""Project metadata. """ __title__ = 'yummly' __summary__ = 'Python library for Yummly API: https://developer.yummly.com' __url__ = 'https://github.com/dgilland/yummly.py' __version__ = '0.5.0' __install_requires__ = ['requests>=1.1.0'] __author__ = 'Derrick Gilland' __email__ = 'dgilland@gmail.com' __license__ = '...
"""Project metadata. """ __title__ = 'yummly' __summary__ = 'Python library for Yummly API: https://developer.yummly.com' __url__ = 'https://github.com/dgilland/yummly.py' __version__ = '0.5.0' __install_requires__ = ['requests>=1.1.0'] __author__ = 'Derrick Gilland' __email__ = 'dgilland@gmail.com' __license__ = 'MIT ...
def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Temperature, obj[3]: Time, obj[4]: Coupon, obj[5]: Coupon_validity, obj[6]: Gender, obj[7]: Age, obj[8]: Maritalstatus, obj[9]: Children, obj[10]: Education, obj[11]: Occupation, obj[12]: Income, obj[13]: Bar, obj[14]: Coffeehouse, obj[15]: Restaurantl...
def find_decision(obj): if obj[7] <= 3: if obj[1] <= 0: if obj[4] <= 3: if obj[15] <= 2.0: if obj[11] <= 8: if obj[12] > 4: return 'True' elif obj[12] <= 4: ...
score = int(input()) if score >= 90: print("A") elif score >= 70: print("B") elif score >= 40: print("C") else: print("D")
score = int(input()) if score >= 90: print('A') elif score >= 70: print('B') elif score >= 40: print('C') else: print('D')
{ "targets": [ { "target_name": "addon", "sources": ["./main_node.cpp", "./GhostServer/GhostServer/networkmanager.cpp"], "libraries": ["-lsfml-network", "-lsfml-system", "-lpthread"], } ] }
{'targets': [{'target_name': 'addon', 'sources': ['./main_node.cpp', './GhostServer/GhostServer/networkmanager.cpp'], 'libraries': ['-lsfml-network', '-lsfml-system', '-lpthread']}]}
print('''Type the phrases bellow to know our answer: 1. Hello 2. How are you? 3. Good bye''') ps = (70 * '-') + '\nYou might have to try again if the phrases will be inserted differently.' print(ps) while True: userInput = str(input('Please input the choosen phrase: ')).upper() if userInput == 'HELLO': ...
print('Type the phrases bellow to know our answer:\n1. Hello\n2. How are you?\n3. Good bye') ps = 70 * '-' + '\nYou might have to try again if the phrases will be inserted differently.' print(ps) while True: user_input = str(input('Please input the choosen phrase: ')).upper() if userInput == 'HELLO': pr...
#!/usr/bin/env python # encoding: utf-8 """ sort_list_to_binary_tree.py Created by Shengwei on 2014-07-03. """ # https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/ # tags: easy, tree, linked-list, sorted, convert, D&C """ Given a singly linked list where elements are sorted in ascending orde...
""" sort_list_to_binary_tree.py Created by Shengwei on 2014-07-03. """ '\nGiven a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.\n' class Solution: def sorted_list_to_bst(self, head): (cur, total) = (head, 0) while cur: total += 1...
""" Tests for the PandaSpark module, you probably don't want to import this directly. """
""" Tests for the PandaSpark module, you probably don't want to import this directly. """
class Member: def __init__( self, name: str, linkedin_url: str = None, github_url: str = None ) -> None: self.name = name self.linkedin_url = linkedin_url self.github_url = github_url def sidebar_markdown(self): markdown = f'<b style="display: inline-block; vertical...
class Member: def __init__(self, name: str, linkedin_url: str=None, github_url: str=None) -> None: self.name = name self.linkedin_url = linkedin_url self.github_url = github_url def sidebar_markdown(self): markdown = f'<b style="display: inline-block; vertical-align: middle; he...
class TransactionError(Exception): def __init__(self, message): self.message = message # Call the base class constructor with the parameters it needs super().__init__(message) class UserError(Exception): def __init__(self, message): self.message = message # Call the base...
class Transactionerror(Exception): def __init__(self, message): self.message = message super().__init__(message) class Usererror(Exception): def __init__(self, message): self.message = message super().__init__(message) class Hackererror(Exception): def __init__(self, mes...
""" Python solution for challenge: "Tennis Game Points" To start the tests, type from CLI: python test_solution_sum_of_missing_numbers.py """ def tennis_game_points(score): # From call to points call_points = {"love": 0, "15": 1, "30": 2, "40": 3} # From string to list (using the separator "-") calls ...
""" Python solution for challenge: "Tennis Game Points" To start the tests, type from CLI: python test_solution_sum_of_missing_numbers.py """ def tennis_game_points(score): call_points = {'love': 0, '15': 1, '30': 2, '40': 3} calls = score.split('-') points = call_points[calls[0]] if calls[1] in call_p...
def e_sum(x, y): return x + y def e_sub(x, y): return x - y
def e_sum(x, y): return x + y def e_sub(x, y): return x - y
s = set(); print(s, type(s)) s = set([1,2,3]); print(s, type(s)) s = set([1,2,3,2,1]); print(s, type(s)) s = {}; print(s, type(s))#dict s = {1,2,3,2,1}; print(s, type(s))
s = set() print(s, type(s)) s = set([1, 2, 3]) print(s, type(s)) s = set([1, 2, 3, 2, 1]) print(s, type(s)) s = {} print(s, type(s)) s = {1, 2, 3, 2, 1} print(s, type(s))
class EventRecorder(object): def __init__(self): super(EventRecorder, self).__init__() self.events = {} self.timestamp = 0 def record(self, event_name, **kwargs): assert event_name not in self.events, "Event {} already recorded".format(event_name) self.timestamp += 1 ...
class Eventrecorder(object): def __init__(self): super(EventRecorder, self).__init__() self.events = {} self.timestamp = 0 def record(self, event_name, **kwargs): assert event_name not in self.events, 'Event {} already recorded'.format(event_name) self.timestamp += 1 ...
level = [ (1, 1 ,1 ,1 ,1 ,1 ,1 ,1), (1, 0, 0, 0, 0, 0, 2, 1), (1, 1 ,1 ,1 ,1 ,1 ,1 ,1), #0-2 (1, 1 ,1 ,1 ,1 ,1 ,1 ,1), (1, 1 ,1 ,1 ,1 ,1 ,1 ,1), (1, 1 ,1 ,1 ,1 ,1 ,1 ,1), #3-5 (1, 1 ,1 ,1 ,1 ,1 ,1 ,1), (1, 1 ,1 ,1 ,1 ,1 ,1 ,1), (1, 0, 0, 0, 0, 0, 2, 1), #6-8 (1, 1 ,1 ,1 ,1 ,1 ,1 ,1), (1,...
level = [(1, 1, 1, 1, 1, 1, 1, 1), (1, 0, 0, 0, 0, 0, 2, 1), (1, 1, 1, 1, 1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1), (1, 0, 0, 0, 0, 0, 2, 1), (1, 1, 1, 1, 1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1),...
# -*- coding: utf-8 -*- class ScraperError(Exception): pass
class Scrapererror(Exception): pass
PYTHON = "python" CPP = "cpp" CSHARP = "csharp" JAVA = 'java' CHOICES = ( (PYTHON, 'Python3'), (CPP, 'C++'), (CSHARP, 'C#'), (JAVA, 'Java') )
python = 'python' cpp = 'cpp' csharp = 'csharp' java = 'java' choices = ((PYTHON, 'Python3'), (CPP, 'C++'), (CSHARP, 'C#'), (JAVA, 'Java'))
# %% Building out get asset events limit = 50 collection_slug, token_id, ='gutter-cat-gang', None asset_contract_addresses, offset, only_opensea, auction_type, occurred_before, occurred_after = None, None, None, None, None, None account_address = None # initiatie query with limit: query = {"limit" : str(limit)} # C...
limit = 50 (collection_slug, token_id) = ('gutter-cat-gang', None) (asset_contract_addresses, offset, only_opensea, auction_type, occurred_before, occurred_after) = (None, None, None, None, None, None) account_address = None query = {'limit': str(limit)} if collection_slug: query['collection_slug'] = collection_slu...
class AWSCloudWatchAlarmPermissions: def get_permissions(self, resname, res): alarmname = self._get_property_or_default(res, "*", "AlarmName") alarmactions = self._get_property_or_default(res, None, "AlarmActions") insufficientdataactions = self._get_property_or_default(res, None, "Insuffici...
class Awscloudwatchalarmpermissions: def get_permissions(self, resname, res): alarmname = self._get_property_or_default(res, '*', 'AlarmName') alarmactions = self._get_property_or_default(res, None, 'AlarmActions') insufficientdataactions = self._get_property_or_default(res, None, 'Insuffic...
""" Configurations for local development and production """ class Config: """ Standard configurations """ DEBUG = False class DevelopmentConfig(Config): """ Configuration for local development """ FLASK_PORT = 5000 FLASK_HOST = '0.0.0.0' class ProductionConfig(Config): """ Configuration for p...
""" Configurations for local development and production """ class Config: """ Standard configurations """ debug = False class Developmentconfig(Config): """ Configuration for local development """ flask_port = 5000 flask_host = '0.0.0.0' class Productionconfig(Config): """ Configuration for p...
#!/usr/bin/env python3 distro={ } library=[] distro["name"]="RedHat" distro["versions"]=["4.0","5.0","6.0","7.0","8.0"] library.append(distro.copy()) distro["name"]="Suse" distro["versions"]=["10.0","11.0","15.0","42.0"] library.append(distro.copy()) print(library)
distro = {} library = [] distro['name'] = 'RedHat' distro['versions'] = ['4.0', '5.0', '6.0', '7.0', '8.0'] library.append(distro.copy()) distro['name'] = 'Suse' distro['versions'] = ['10.0', '11.0', '15.0', '42.0'] library.append(distro.copy()) print(library)
class Method(): def __init__(self): self.methodDefinition = None self.locals = [] self.instructions = [] self.maxStack = -1 self.returnType = None self.parameters = [] self.attributes = []
class Method: def __init__(self): self.methodDefinition = None self.locals = [] self.instructions = [] self.maxStack = -1 self.returnType = None self.parameters = [] self.attributes = []
class Elevator: occupancy_limit = 8 def __init__(self, occupants): if occupants > self.occupancy_limit: print("The maximum occupancy limit has been exceeded." f" {occupants - self.occupancy_limit} occupants must exit the elevator.") self.occupants = occupants ele...
class Elevator: occupancy_limit = 8 def __init__(self, occupants): if occupants > self.occupancy_limit: print(f'The maximum occupancy limit has been exceeded. {occupants - self.occupancy_limit} occupants must exit the elevator.') self.occupants = occupants elevator1 = elevator(6) pr...
first = ['Aousnik', 'Ronodeep', 'Anirban'] last = ['Gupta', 'Gupta', 'Chaudhuri'] names = zip(first, last) # joins the first and last list in the tuples 'names' for a, b in names: print(a, b) ''' this function just basically makes a list of tuples like: [('Aousnik', 'Gupta'), ('Ronodeep', Gup...
first = ['Aousnik', 'Ronodeep', 'Anirban'] last = ['Gupta', 'Gupta', 'Chaudhuri'] names = zip(first, last) for (a, b) in names: print(a, b) " this function just basically makes a list of tuples like:\n [('Aousnik', 'Gupta'), ('Ronodeep', Gupta), ('Anirban', 'Chaudhuri')] just like tuples\n"
# SPDX-FileCopyrightText: 2019 Nicholas Tollervey, written for Adafruit Industries # # SPDX-License-Identifier: MIT """A simple directory based Python module that's missing metadata.""" def hello(): """A hello function""" return "Hello, World!"
"""A simple directory based Python module that's missing metadata.""" def hello(): """A hello function""" return 'Hello, World!'
# x = 5 # y = 10 # z = 20 # x, y, z = 5, 16, 20 # x, y = y, x # x += 5 #x = x + 5 # x -= 5 #x = x - 5 # x *= 5 #x = x * 5 # x /= 5 #x = x / 5 # x %= 5 #x = x % 5 # y //= 5 #y = y // 5 # y **= z #y = y ** z values ...
values = (1, 2, 3, 4, 5) print(values) print(type(values)) (x, y, *z) = values print(x, y, z) print(x, y, z[1])
hght = 420 wdth = 1188 #size(1188,420) #define window size - doesnt work unless in setup inix = int(random(10,50)) #define x as first value for loop iniy1 = int(random(0,hght)) #define y1 as random between 0 and 420=height, no global value yet #iniy2 = iniy1 iniy2 = int(random(...
hght = 420 wdth = 1188 inix = int(random(10, 50)) iniy1 = int(random(0, hght)) iniy2 = int(random(0, hght)) while iniy1 == iniy2: iniy2 = int(random(0, hght)) cnt = 0 x = 0 isw = int(random(1, 3)) x_values = [] y_values = [] def setup(): global x background(255) stroke(0) size(wdth, hght) x = i...
class InvalidWithdrawal(Exception): pass raise InvalidWithdrawal("You don't have $50 in your account")
class Invalidwithdrawal(Exception): pass raise invalid_withdrawal("You don't have $50 in your account")
speed_light_si = 299792458.0 electron_mass_si = 9.10938215e-31 elementary_charge_si = 1.602176487e-19 mu_0_si = 4.0*math.pi*1e-7 epsilon_0_si = 1.0/(mu_0_si*speed_light_si**2) planck_si = 6.62606896e-34 hbar_si = planck_si / (2.0 * math.pi) fine_structure_si = elementary_charge_si**2/(4.0*math.pi*epsilon_0_si*hbar_si*s...
speed_light_si = 299792458.0 electron_mass_si = 9.10938215e-31 elementary_charge_si = 1.602176487e-19 mu_0_si = 4.0 * math.pi * 1e-07 epsilon_0_si = 1.0 / (mu_0_si * speed_light_si ** 2) planck_si = 6.62606896e-34 hbar_si = planck_si / (2.0 * math.pi) fine_structure_si = elementary_charge_si ** 2 / (4.0 * math.pi * eps...
def print_sum(*values): s = 0 for number in values: s += number print(f'The sum of {values} is {s}') print_sum(5, 2) print_sum(2, 9, 4)
def print_sum(*values): s = 0 for number in values: s += number print(f'The sum of {values} is {s}') print_sum(5, 2) print_sum(2, 9, 4)
#!/usr/bin/env python # *-* coding: UTF-8 *-* """Stabileste daca o expresie de paranteze este corecta.""" def este_corect(expresie): """Apreciaza corectitudinea expresiei.""" memo = [] for _, val in enumerate(expresie): if val not in '([)]': return False if val == '(' or val =...
"""Stabileste daca o expresie de paranteze este corecta.""" def este_corect(expresie): """Apreciaza corectitudinea expresiei.""" memo = [] for (_, val) in enumerate(expresie): if val not in '([)]': return False if val == '(' or val == '[': memo.append(val) if...
x = 0 soma = 0 i = 0 while x != -1: x = int(input('digite uma idade: ')) if x != -1: soma += x i += 1 print(soma/i)
x = 0 soma = 0 i = 0 while x != -1: x = int(input('digite uma idade: ')) if x != -1: soma += x i += 1 print(soma / i)
if __name__ == '__main__': n = int(input()) output = "" for i in range(1, n+1): output = output + str(i) print(output)
if __name__ == '__main__': n = int(input()) output = '' for i in range(1, n + 1): output = output + str(i) print(output)
""" Calibration following https://casaguides.nrao.edu/index.php?title=EVLA_6cmWideband_Tutorial_SN2010FZ https://casaguides.nrao.edu/index.php/EVLA_high_frequency_Spectral_Line_tutorial_-_IRC%2B10216-CASA4.5#Bandpass_and_Delay """ vis = '16B-202.sb32532587.eb32875589.57663.07622001157.ms' line_vis = '16B-202.lines.ms'...
""" Calibration following https://casaguides.nrao.edu/index.php?title=EVLA_6cmWideband_Tutorial_SN2010FZ https://casaguides.nrao.edu/index.php/EVLA_high_frequency_Spectral_Line_tutorial_-_IRC%2B10216-CASA4.5#Bandpass_and_Delay """ vis = '16B-202.sb32532587.eb32875589.57663.07622001157.ms' line_vis = '16B-202.lines.ms' ...
# # arr1 = [100,100,200,300,300,400,400] # # arr2 = [14,90,100,100,200,200,450,450,0,0,0,0,0,0,0] # # arr1 = [1,3,5] # # arr2 = [2,4,6,0,0,0] # arr1 = [1,1,1,1,1,1] # arr2 = [12,1,1,1,1,1,2,0,0,0,0,0,0] # # arr1_ptr, arr2_ptr = 0,0 # # while arr2_ptr <= len(arr1) - 1: # # if arr2[arr2_ptr] <= arr1[arr1_ptr]: # # ...
def generate_all_subsets(s): res = [] def helper(data, index, slate): if index == len(data): res.append('|'.join(slate)) return for i in range(index + 1, len(data) + 1): curr = string[index, i] slate.append(data[index]) helper(data, index + 1,...
def factorize(x: int): d = 2 while x != 1: if x % d == 0: print('Hello') yield d x //= d else: d += 1 A = factorize(1023) print(A) for x in map(str, A): print('Factor:', x)
def factorize(x: int): d = 2 while x != 1: if x % d == 0: print('Hello') yield d x //= d else: d += 1 a = factorize(1023) print(A) for x in map(str, A): print('Factor:', x)
def insertion_sort(v): for i in range (1, len(v)): x = v[i] j = i-1 while j>=0 and x< v[j]: v[j+1] = v[j] j -= 1 v[j+1] = x print() b = [8,3,9,2,1,10,7,5,4,6] print(b) print() a = insertion_sort(b) print() a = b print(a) print()
def insertion_sort(v): for i in range(1, len(v)): x = v[i] j = i - 1 while j >= 0 and x < v[j]: v[j + 1] = v[j] j -= 1 v[j + 1] = x print() b = [8, 3, 9, 2, 1, 10, 7, 5, 4, 6] print(b) print() a = insertion_sort(b) print() a = b print(a) print()
""" ==== KEY POINTS ==== - Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right. - Do the above modifications to the input array in place, do not return anything from your function. - arr.length <= 10000 - arr[i] <= 9 """ """ ==== BRUTE FORCE SOL...
""" ==== KEY POINTS ==== - Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right. - Do the above modifications to the input array in place, do not return anything from your function. - arr.length <= 10000 - arr[i] <= 9 """ '\n==== BRUTE FORCE SOLUT...
class User(): def __init__(self , Name , userName , username_type , Game , data_dict): self.index = data_dict.getIndex()+1 self.name = Name self.username = userName self.username_type = username_type self.game = Game self.data = data_dict self.data.AddU...
class User: def __init__(self, Name, userName, username_type, Game, data_dict): self.index = data_dict.getIndex() + 1 self.name = Name self.username = userName self.username_type = username_type self.game = Game self.data = data_dict self.data.AddUser(self) ...
class Time60(object): 'Time60 - track hours and minutes' def __init__(self, hr, min): self.hr = hr self.min = min def __str__(self): return '%d:%d' %(self.hr, self.min) __repr__ = __str__ def __add__(self, other): return self.__class__(self.hr + other.hr, self.min...
class Time60(object): """Time60 - track hours and minutes""" def __init__(self, hr, min): self.hr = hr self.min = min def __str__(self): return '%d:%d' % (self.hr, self.min) __repr__ = __str__ def __add__(self, other): return self.__class__(self.hr + other.hr, self...
#!/usr/bin/env python # -*- coding: utf-8 -*- # AUTHOR = 'gauravssnl' SITENAME = 'Gauravssnl Tech Blog' SITEURL = 'https://gauravssnl.github.io' # Legal SITE_LICENSE = """ &copy; Copyright 2020 by Gaurav (@gauravssnl) and licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/4.0/"> <img al...
author = 'gauravssnl' sitename = 'Gauravssnl Tech Blog' siteurl = 'https://gauravssnl.github.io' site_license = '\n&copy; Copyright 2020 by Gaurav (@gauravssnl) and licensed under a <a rel="license"\n href="http://creativecommons.org/licenses/by/4.0/">\n <img alt="Creative Commons License" style="border-width:0" src=...
# internal flags TRANS_FLIPX = 1 TRANS_FLIPY = 2 TRANS_ROT = 4 # Tiled gid flags GID_TRANS_FLIPX = 1 << 31 GID_TRANS_FLIPY = 1 << 30 GID_TRANS_ROT = 1 << 29
trans_flipx = 1 trans_flipy = 2 trans_rot = 4 gid_trans_flipx = 1 << 31 gid_trans_flipy = 1 << 30 gid_trans_rot = 1 << 29
INSTALLED_APPS += ( "django_mailbox", # "social", 'reversion', # "social_django", 'django_outlook', )
installed_apps += ('django_mailbox', 'reversion', 'django_outlook')
# -*- coding: utf-8 -*- """ Created on Wed Jun 17 17:05:02 2020 @author: fcosta """
""" Created on Wed Jun 17 17:05:02 2020 @author: fcosta """
#Cleansing #remove urls, usernames, NA, special charactars, and numbers class TwitterCleanuper: def iterate(self): for cleanup_method in [self.remove_urls, self.remove_usernames, self.remove_na, self.remove_specia...
class Twittercleanuper: def iterate(self): for cleanup_method in [self.remove_urls, self.remove_usernames, self.remove_na, self.remove_special_chars, self.remove_numbers]: yield cleanup_method def remove_by_regex(tweets, regexp): tweets.loc[:, 'text'].replace(regexp, '', inplace=Tr...
class TweetCriteria: """Search parameters class""" def __init__(self): self.max_tweets = 0 self.top_tweets = False self.within = "15mi" self.username = None self.since = None self.until = None self.near = None self.query_search = None self...
class Tweetcriteria: """Search parameters class""" def __init__(self): self.max_tweets = 0 self.top_tweets = False self.within = '15mi' self.username = None self.since = None self.until = None self.near = None self.query_search = None self...
def get_right(pat, r=256): right = [-1] * r for i in range(len(pat)): right[ord(pat[i])] = i return right def boyemoore_search(txt, pat): right = get_right(pat) skip = 0 i = 0 while i <= len(txt) - len(pat): skip = 0 j = len(pat) - 1 while j >=...
def get_right(pat, r=256): right = [-1] * r for i in range(len(pat)): right[ord(pat[i])] = i return right def boyemoore_search(txt, pat): right = get_right(pat) skip = 0 i = 0 while i <= len(txt) - len(pat): skip = 0 j = len(pat) - 1 while j >= 0: ...
def validate_empty(field, name=None): if not field: raise ValueError('This field is Required.') if name and not field: raise validate_empty('{} is Required'.format(name))
def validate_empty(field, name=None): if not field: raise value_error('This field is Required.') if name and (not field): raise validate_empty('{} is Required'.format(name))
# Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. DEPS = [ 'chromium', 'chromium_android', 'recipe_engine/json', 'recipe_engine/properties', ] def RunSteps(api): api.chromium.set_config('chromium...
deps = ['chromium', 'chromium_android', 'recipe_engine/json', 'recipe_engine/properties'] def run_steps(api): api.chromium.set_config('chromium') api.chromium_android.set_config('main_builder') api.chromium_android.run_sharded_perf_tests(config=api.json.input({'steps': {}, 'version': 1}), max_battery_temp=...
# coded in python3 # video : text = input("Enter your text : ") check = True etext = "" for chars in text: if(ord(chars)) <= 90 and ord(chars) <= 65: if((ord(chars) + 13) > 90): x = 64 + ((ord(chars) + 13) - 90) else: x = ord(chars) + 13 elif(ord(chars) <= 122 and o...
text = input('Enter your text : ') check = True etext = '' for chars in text: if ord(chars) <= 90 and ord(chars) <= 65: if ord(chars) + 13 > 90: x = 64 + (ord(chars) + 13 - 90) else: x = ord(chars) + 13 elif ord(chars) <= 122 and ord(chars) >= 97: if ord(chars) + ...
a = [74,-72,94,-53,-59,-3,-66,36,-13,22,73,15,-52,75] def maxSubArraySum(a): current_sequence = 0 best_sequence = a[0] for x in a: current_sequence = max(x,current_sequence+x) best_sequence = max(best_sequence,current_sequence) return best_sequence print("Largest sum con...
a = [74, -72, 94, -53, -59, -3, -66, 36, -13, 22, 73, 15, -52, 75] def max_sub_array_sum(a): current_sequence = 0 best_sequence = a[0] for x in a: current_sequence = max(x, current_sequence + x) best_sequence = max(best_sequence, current_sequence) return best_sequence print('Largest sum...
class Pic16f15356DeviceInformationArea: def __init__(self, address, dia): if len(dia) != 32: raise ValueError('dia', f'PIC16F15356 DIA is 32 words but received {len(dia)} words') self._address = address self._raw = dia.copy() self._device_id = ''.join(['{:04x}'.format(id_byte) for id_byte in dia[0x00:0x09]...
class Pic16F15356Deviceinformationarea: def __init__(self, address, dia): if len(dia) != 32: raise value_error('dia', f'PIC16F15356 DIA is 32 words but received {len(dia)} words') self._address = address self._raw = dia.copy() self._device_id = ''.join(['{:04x}'.format(i...
arduino = Runtime.createAndStart("arduino","Arduino") arduino.setBoardMega() arduino.connect("COM7") arduino1 = Runtime.createAndStart("arduino1","Arduino") arduino1.setBoardNano() #connecting arduino1 to arduino Serial1 instead to a COMX arduino1.connect(arduino,"Serial1") servo = Runtime.createAndStart("servo","Se...
arduino = Runtime.createAndStart('arduino', 'Arduino') arduino.setBoardMega() arduino.connect('COM7') arduino1 = Runtime.createAndStart('arduino1', 'Arduino') arduino1.setBoardNano() arduino1.connect(arduino, 'Serial1') servo = Runtime.createAndStart('servo', 'Servo') servo.attach(arduino1, 5) sleep(1) servo.moveTo(90)
# Copyright (c) 2015 Intel Corporation # # 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 ...
class Dashboardapiconfig(object): dashboard_api_version = 'v1' dashboard_call_auth_token = dashboard_api_version + '/api/auth/token' class Gearpumpapiconfig(object): version = 'v1.0' prefix = '/api/' + version prefix_master = prefix + '/master/' call_login = '/login' call_submit = prefix_ma...
##Patterns: W0199 assert (1 == 1, 2 == 2), "no error" ##Warn: W0199 assert (1 == 1, 2 == 2) assert 1 == 1, "no error" assert (1 == 1,), "no error" assert (1 == 1,) assert (1 == 1, 2 == 2, 3 == 5), "no error" assert () ##Warn: W0199 assert (True, 'error msg')
assert (1 == 1, 2 == 2), 'no error' assert (1 == 1, 2 == 2) assert 1 == 1, 'no error' assert (1 == 1,), 'no error' assert (1 == 1,) assert (1 == 1, 2 == 2, 3 == 5), 'no error' assert () assert (True, 'error msg')
class Parameters(object): def __init__(self, *, p, q, g): if isinstance(p, bytes): p = int.from_bytes(p, 'big') self.p = p if isinstance(q, bytes): q = int.from_bytes(q, 'big') self.q = q if isinstance(g, bytes): g = int.from_bytes(g, 'bi...
class Parameters(object): def __init__(self, *, p, q, g): if isinstance(p, bytes): p = int.from_bytes(p, 'big') self.p = p if isinstance(q, bytes): q = int.from_bytes(q, 'big') self.q = q if isinstance(g, bytes): g = int.from_bytes(g, 'big...
############################################## ## CONFIG BLOCK ## ############################################## # @string token - API Token # @string user - This is found in Zendesk under Admin > Channels > API, Commonly your login_email/token # @list user_defined_list - List of emails comm...
token = 'TOKEN' user = 'APIUSER/token' user_defined_list = ['useremail@company.com', 'useremail2@company.com'] admin_email = 'user@email.com' default_days = 7 from_addr = 'user@company.com' smtp_server = 'mail.server.net' email_pass = 'password'
# define the time range we are interested in end_time = datetime(2017, 9, 12, 0) start_time = end_time - timedelta(days=2) # build the query query = ncss.query() query.lonlat_point(-155.1, 19.7) query.time_range(start_time, end_time) query.variables('altimeter_setting', 'temperature', 'dewpoint', 'wind...
end_time = datetime(2017, 9, 12, 0) start_time = end_time - timedelta(days=2) query = ncss.query() query.lonlat_point(-155.1, 19.7) query.time_range(start_time, end_time) query.variables('altimeter_setting', 'temperature', 'dewpoint', 'wind_direction', 'wind_speed') query.accept('csv') data = ncss.get_data(query) df = ...
#Fixed by overriding. This does not change behavior, but makes it explicit and comprehensible. class ThreadingTCPServerOverriding(ThreadingMixIn, TCPServer): def process_request(self, request, client_address): #process_request forwards to do_work, so it is OK to call ThreadingMixIn.process_request ...
class Threadingtcpserveroverriding(ThreadingMixIn, TCPServer): def process_request(self, request, client_address): ThreadingMixIn.process_request(self, request, client_address) class Threadingmixin: """Mix-in class to help with threads.""" def do_job_in_thread(self, job, args): """Start a...
# -*- coding: utf-8 -*- class Announce: def __init__(self, data=None): self.guild_id: str = "" self.channel_id: str = "" self.message_id: str = "" if data: self.__dict__ = data class CreateAnnounceRequest: def __init__(self, channel_id: str, message_id: str): ...
class Announce: def __init__(self, data=None): self.guild_id: str = '' self.channel_id: str = '' self.message_id: str = '' if data: self.__dict__ = data class Createannouncerequest: def __init__(self, channel_id: str, message_id: str): self.channel_id = cha...
#!/usr/bin/python3.4 # This program """ Print main text 2 with Exit, List characteristics, Change characteristics, Change characteristics Ask me to choice one of them if choice "Exit": Exit game elif choice "List characteristics": show all characteristics and return to main menu elif choice "Change characte...
""" Print main text 2 with Exit, List characteristics, Change characteristics, Change characteristics Ask me to choice one of them if choice "Exit": Exit game elif choice "List characteristics": show all characteristics and return to main menu elif choice "Change characteristics": show me all characterist...
__all__ = ['class_in_class_factory'] def class_in_class_factory(parent_class, name, bases=None, **fields): if not (isinstance(bases, tuple) or bases is None): raise TypeError('`bases` must be tuple.') fields['__module__'] = '{parent_class_module_name}.{parent_class_name}'.format( parent_class...
__all__ = ['class_in_class_factory'] def class_in_class_factory(parent_class, name, bases=None, **fields): if not (isinstance(bases, tuple) or bases is None): raise type_error('`bases` must be tuple.') fields['__module__'] = '{parent_class_module_name}.{parent_class_name}'.format(parent_class_module_na...
class Tree(object): def __init__(self, x): self.value = x self.left = None self.right = None def balancedBinaryTree(root): def get_height(root): if root is None: return 0 return max(get_height(root.left), get_height(root.right)) + 1 if root is None: ...
class Tree(object): def __init__(self, x): self.value = x self.left = None self.right = None def balanced_binary_tree(root): def get_height(root): if root is None: return 0 return max(get_height(root.left), get_height(root.right)) + 1 if root is None: ...
#Project Euler Question 54 #Poker hands poker_file = open(r"C:\Users\Clayton\Documents\Python Other Files\p054_poker.txt") content = poker_file.read() content = content.replace(" ", "") content = content.split("\n") card_values = {"2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "T": 10, "J": 11, "Q": ...
poker_file = open('C:\\Users\\Clayton\\Documents\\Python Other Files\\p054_poker.txt') content = poker_file.read() content = content.replace(' ', '') content = content.split('\n') card_values = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14} def royal_flush...
def did_from_credential_definition_id(credential_definition_id: str) -> str: parts = credential_definition_id.split(":") return parts[0]
def did_from_credential_definition_id(credential_definition_id: str) -> str: parts = credential_definition_id.split(':') return parts[0]
def solve_knapsack(profits, weights, capacity): n = len(profits) if capacity <= 0 or n == 0 or len(weights) != n: # basic checks return 0 # We only need one previous row to find the optimal solution, # Overall we need '2' rows, the solution is similar to the previous solution, the only differe...
def solve_knapsack(profits, weights, capacity): n = len(profits) if capacity <= 0 or n == 0 or len(weights) != n: return 0 dp = [[0 for x in range(capacity + 1)] for y in range(2)] for c in range(0, capacity + 1): if weights[0] <= c: dp[0][c] = dp[1][c] = profits[0] for i...
# Parent class 1 class Person: def person_info(self, name, age): print('Inside Person class') print('Name:', name, 'Age:', age) # Parent class 2 class Company: def company_info(self, company_name, location): print('Inside Company class') print('Name:', company_name, 'location:'...
class Person: def person_info(self, name, age): print('Inside Person class') print('Name:', name, 'Age:', age) class Company: def company_info(self, company_name, location): print('Inside Company class') print('Name:', company_name, 'location:', location) class Employee(Perso...
BINDIR = '/usr/local/bin' BLOCK_MESSAGE_KEYS = [] BUILD_TYPE = 'app' BUNDLE_NAME = 'pebble-World-Cup.pbw' DEFINES = ['RELEASE'] LIBDIR = '/usr/local/lib' LIB_DIR = 'node_modules' MESSAGE_KEYS = {} MESSAGE_KEYS_HEADER = '/root/hello-pebblejs/pebble-World-Cup/build/include/message_keys.auto.h' NODE_PATH = '/root/.pebble-...
bindir = '/usr/local/bin' block_message_keys = [] build_type = 'app' bundle_name = 'pebble-World-Cup.pbw' defines = ['RELEASE'] libdir = '/usr/local/lib' lib_dir = 'node_modules' message_keys = {} message_keys_header = '/root/hello-pebblejs/pebble-World-Cup/build/include/message_keys.auto.h' node_path = '/root/.pebble-...
# -*- coding: utf-8 -*- __author__ = 'viruzzz-kun' class OptionsFinish(Exception): pass
__author__ = 'viruzzz-kun' class Optionsfinish(Exception): pass
cube = lambda x: pow(x,3) def fibonacci(n): if n >= 0: lst = [0] if n >= 1: lst.append(1) if n >= 2: for i in range(2,n+1): lst.append(lst[-1]+ lst[-2]) return lst[:n] if __name__ == '__main__': n = int(input()) print(list(map(cube, fibonacci(n))))
cube = lambda x: pow(x, 3) def fibonacci(n): if n >= 0: lst = [0] if n >= 1: lst.append(1) if n >= 2: for i in range(2, n + 1): lst.append(lst[-1] + lst[-2]) return lst[:n] if __name__ == '__main__': n = int(input()) print(list(map(cube, fibonacci(n))))
def wire(data): x, y = (0, 0) for dir, step in [(x[0], int(x[1:])) for x in data.split(",")]: for _ in range(step): x += -1 if dir == "L" else 1 if dir == "R" else 0 y += -1 if dir == "D" else 1 if dir == "U" else 0 yield x, y def aoc(data): wires = [set(wire(li...
def wire(data): (x, y) = (0, 0) for (dir, step) in [(x[0], int(x[1:])) for x in data.split(',')]: for _ in range(step): x += -1 if dir == 'L' else 1 if dir == 'R' else 0 y += -1 if dir == 'D' else 1 if dir == 'U' else 0 yield (x, y) def aoc(data): wires = [set(wi...
"""Template python project""" def factorial(n: int) -> int: # pylint: disable=invalid-name """Calculates factorial Example: >>> factorial(10) 3628800 """ return [1, 0][n > 1] or factorial(n-1) * n
"""Template python project""" def factorial(n: int) -> int: """Calculates factorial Example: >>> factorial(10) 3628800 """ return [1, 0][n > 1] or factorial(n - 1) * n