content
stringlengths
7
1.05M
n, m = map(int, input().split()) trees = list(map(int, input().split())) minH = 0 maxH = max(trees) ans = 0 while minH <= maxH: cutH = (minH+maxH)//2 cutMount = 0 for tree in trees: cutMount += (tree - cutH if tree >= cutH else 0) if cutMount >= m: ans = cutH minH = cutH + 1 ...
class BaseInferer: """ Base inferer class """ def infer(self, *args, **kwargs): """ Perform an inference on test data. """ raise NotImplementedError def fusion(self, submissions_dir, preds): """ Ensamble predictions. """ raise NotImplementedError ...
# Python - 2.7.6 def logical_calc(array, op): logic = { 'AND': all, 'OR': any, 'XOR': lambda arr: bool(arr.count(True) & 1) } if op in logic: return logic[op](array) return False
# bluetooth device attributes DEVICE_NAME = "TT Camera Slider" MIN_POS = 0 MAX_POS = 0.9 MIN_DURATION = 0 MAX_DURATION = 500 MIN_SPEED = 0.002 MAX_SPEED = 0.25 # motor attributes STEP_ANGLE = 1.8 VEL_TO_RPS = 9.88319028614 * 2 # 1/(2pi(r)) DIST_TO_STEPS = 1976.63805723 # (360)/(1.8*2pi(r)) ONLY for ms=0 RADIUS = 0.01...
""" Hangman. Authors: Nasser Hegar and YOUR_PARTNERS_NAME_HERE. """ # TODO: 1. PUT YOUR NAME IN THE ABOVE LINE. # TODO: 2. Implement Hangman using your Iterative Enhancement Plan. ####### Do NOT attempt this assignment before class! #######
def combinations_fixed_sum(fixed_sum, length_of_list, lst=[]): if length_of_list == 1: lst += [fixed_sum] yield lst else: for i in range(fixed_sum+1): yield from combinations_fixed_sum(i, length_of_list-1, lst + [fixed_sum-i]) def combinations_fixed_sum_limits(fixed_sum, length_of_list, minimum,...
class LoginProviders: google = "google" facebook = "facebook" github = "github" twitter = "twitter" login_providers = LoginProviders()
def startRightHand(): ############## i01.startRightHand(rightPort) i01.rightHand.thumb.setMinMax(0,115) i01.rightHand.index.setMinMax(35,130) i01.rightHand.majeure.setMinMax(35,130) i01.rightHand.ringFinger.setMinMax(35,130) i01.rightHand.pinky.setMinMax(35,130) i01.rightHand.wrist.map(90,90,90,...
# <auto-generated> # This code was generated by the UnitCodeGenerator tool # # Changes to this file will be lost if the code is regenerated # </auto-generated> def to_bits(value): return value * 1048576.0 def to_kilobits(value): return value * 1048.58 def to_megabits(value): return value * 1.04858 def to_gigabit...
async def m001_initial(db): """ Creates an improved withdraw table and migrates the existing data. """ await db.execute( """ CREATE TABLE IF NOT EXISTS withdraw_links ( id TEXT PRIMARY KEY, wallet TEXT, title TEXT, min_withdrawable INTEGER ...
# Crie uma tupla preenchida com os 20 primeiros colocados da tabela o campeonato brasileiro, na ordem de colocação # Depois mostre # a) Apenas os 5 primeiros colocados # b) Os últimos 4 colocados da tabela # c) Uma lista com os times em ordem alfabética # d) Em que posição na tabela está o time da chapecoence # Tentei...
# -*- coding: utf-8 -*- def func1(param1, param2='value2'): """函数注释样例""" print("param1=%s,param2=%s" % (param1, param2)) return param1 print(func1("aa", "bb")) print(func1("cc")) print(func1(param2="ttt", param1="ff")) def func2(*params): """打印所有参数""" for param in params: print("param=...
# Copyright 2018 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
SECRET_KEY = '123' # # For mysql in python3.5, uncomment if you will Use MySQL database driver # import pymysql # pymysql.install_as_MySQLdb() DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db.sqlite3', } } KB_NAME_FILE_PATH = '/home/g10k/git/knowledge_base/kb_li...
class Solution: def isDividingNumber(self, num): if '0' in str(num): return False return 0 == sum(num % int(i) for i in str(num)) def selfDividingNumbers(self, left: int, right: int) -> List[int]: divlist = [] for i in range(left, right + 1, +1): if self....
"""Pyvista specific errors.""" CAMERA_ERROR_MESSAGE = """Invalid camera description Camera description must be one of the following: Iterable containing position, focal_point, and view up. For example: [(2.0, 5.0, 13.0), (0.0, 0.0, 0.0), (-0.7, -0.5, 0.3)] Iterable containing a view vector. For example: [-1.0, 2.0...
# Interpreting the coefficients # The linear regression model for flight duration as a function of distance takes the form # duration=α+β×distance # where # α — intercept (component of duration which does not depend on distance) and # β — coefficient (rate at which duration increases as a function of distance; also c...
class InvalidIPv4Address(Exception): """ Exception raised for invalid IPv4 addresses. Attributes: ipv4: IPv4 address that triggered the error. msg : Explanation of the error. """ def __init__(self, ipv4, msg="Invalid IPv4 Address"): self.ipv4 = ipv4 self.msg ...
# Задача 2. Вариант 7. # Напишите программу, которая будет выводить на экран наиболее понравившееся вам высказывание, автором которого является Стендаль. Не забудьте о том, что автор должен быть упомянут на отдельной строке. # Krasnikov A. S. # 19.03.2016 print("Будем трудиться, потому что труд - это отец удовольствия...
# coding:utf-8 ''' @author = super_fazai @File : __init__.py.py @Time : 2016/12/13 15:39 @connect : superonesfazai@gmail.com '''
''' author: zeller problem_name: Fechem as Portas problem_number: 1371 category: Matemática difficulty_level: 4 link: https://www.urionlinejudge.com.br/judge/pt/problems/view/1371 ''' while True: a, i = int(input()), 2 if a == False: break j = i*i resposta = "1" while(j <= a): respo...
class Manager: def __init__(self): self.states = [] def process_input(self, event): self.states[-1].process_input(event) def update(self): self.states[-1].update() def draw(self, screen): for state in self.states: state.draw(screen) def push(self, stat...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Written by Lucas Sinclair. MIT Licensed. Contact at www.sinclair.bio """ # Built-in modules # ################################################################################ def add_dummy_scores(iterable, score=0): """Add zero scores to all sequences.""" fo...
# # Formatting # x = 12 if x == 24: print('Is valid') else: print("Not valid") def helper(name='sample'): pass def another(name = 'sample'): pass msg = "abc" msg2 = 'abc' print(msg) def print_hello(name) : """ Greets the user by name Parameters: name (str): The name of the user Returns: st...
#!/usr/bin/env python class Real(object): def method(self): return "method" @property def prop(self): # print "prop called" return "prop" class PropertyProxy(object): def __init__( self, object, name ): self._object = object self._name = name def __get__(sel...
#!/usr/bin/python # -*- coding:utf-8 -*- #Filename: print_index.py colors = [ 'red', 'green', 'blue', 'yellow' ] for i in range(len(colors)): print (i, '->', colors[i]) # >>> 0 -> red # 1 -> green # 2 -> blue # 3 -> yellow # >>> for i, color in enumerate(colors): print (i, '->', color)...
class Cluster(object): """ Base Cluster class. This is intended to be a generic interface to different types of clusters. Clusters could be Kubernetes clusters, Docker swarms, or cloud compute/container services. """ def deploy_flow(self, name=None): """ Deploys a flow to the cl...
# coding:utf8 """French dictionary""" fr = { "LANGUAGE": "Français", # Client notifications "config-cleared-notification": "Paramètres effacés. Les modifications seront enregistrées lorsque vous enregistrez une configuration valide.", "relative-config-notification": "Fichiers de configuration relati...
set_A = set(map(int,input().split())) N = int(input()) for i in range(N): arr_A = set(input().split()) arr_N = set(input().split()) if not arr_A.issuperset(arr_N): print(False) else: print(True)
def main(): a = "Java" b = a.replace("a", "ao") print(b) c = a.replace("a", "") print(c) print(b[1:3]) d = a[0] + b[5] print("PRINTS D: " + d) e = 3 * len(a) print("prints e: " + str(e)) print(d + "k" + "e") print(a[2]) main()
#Your Own list. List_of_transportation = ["car","bike","truck"] print("I just love to ride a "+List_of_transportation[1]+".") print("But i also love to sit in a "+List_of_transportation[0]+" comfortably and drive.") print("I also play simulator games of "+List_of_transportation[2]+".")
# Copyright 2017 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
supported_languages = { # .c,.h: C "c": "C", "h": "C", # .cc .cpp .cxx .c++ .h .hh : CPP "cc": "CPP", "cpp": "CPP", "cxx": "CPP", "c++": "CPP", "h": "CPP", "hh": "CPP", # .py .pyw, .pyc, .pyo, .pyd : PYTHON "py": "PYTHON", "pyw": "PYTHON", "pyc": "PYTHON", "py...
""" Given an array of real numbers greater than zero in form of strings. Find if there exists a triplet (a,b,c) such that 1 < a+b+c < 2 . Return 1 for true or 0 for false. 0.6 0.7 0.8 1.2 0.4 0.6 1.3 2.1 3.3 3.7 brute force would be to just try all n^3 possibilities the order does not matter sorting is an opt...
####################### # Dennis MUD # # break_item.py # # Copyright 2018-2020 # # Michael D. Reiley # ####################### # ********** # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal i...
def buildPalindrome(st): if st == st[::-1]: # Check for initial palindrome return st index = 0 subStr = st[index:] while subStr != subStr[::-1]: # while substring is not a palindrome index += 1 subStr = st[index:] return st + st[index - 1 :: -1]
class node: def __init__(self, ID, log): self.ID = ID self.log = log self.peers = list() class ISP(node): def __init__(self, ID, log): super().__init__(ID, log) self.type = 'ISP' def print(self): print(self.ID, self.log, self.peers, self.type) class butt(...
__all__ = [ "gen_init_string" , "gen_function_declaration_string" , "gen_array_declaration" ] def gen_init_string(_type, initializer, indent): init_code = "" if initializer is not None: raw_code = _type.gen_usage_string(initializer) # add indent to initializer code init_code_l...
with open("data/iris.csv") as f: for line in f: print (line.split(',')[:4])
""" Question 6 Write a function that will copy the contents of one file to a new file. """ def copy_file(infile, outfile): with open(infile) as file: with open(outfile, 'w') as new_file: new_file.write(file.read()) copy_file('capitals.txt', 'new_capitals.txt')
"""A mocked database module.""" class DatabaseMongoCollectionMock: """The mocked database mongo class.""" def __init__(self, config): """Start the class.""" self.config = config self.dummy_doc = {} self.valid_response = {"_id": 123, "key": "456", "value": "789"} async def...
n, m = map(int, input().split()) s = input().split() t = input().split() q = int(input()) for _ in range(q): y = int(input()) print(s[(y-1)%len(s)]+t[(y-1)%len(t)])
pkgname = "scdoc" pkgver = "1.11.2" pkgrel = 0 build_style = "makefile" make_cmd = "gmake" hostmakedepends = ["pkgconf", "gmake"] pkgdesc = "Tool for generating roff manual pages" maintainer = "q66 <q66@chimera-linux.org>" license = "MIT" url = "https://git.sr.ht/~sircmpwn/scdoc" source = f"https://git.sr.ht/~sircmpwn/...
"""Base class for file formatters""" __all__ = [ 'BaseFormatter', ] class BaseFormatter: @classmethod def from_file(cls, instr, filename=None, *args, **kwargs): """Reads a game from a file. Args: instr: The input stream. filename: The filename, if any, for tool messag...
__version__ = "3.2" __author__ = "pyLARDA-dev-team" __doc_link__ = "https://lacros-tropos.github.io/larda-doc/" __init_text__ = f""">> LARDA initialized. Documentation available at {__doc_link__}""" __default_info__ = """ The data from this campaign is provided by larda without warranty and liability. Before publis...
# -*- coding: utf-8 -*- ########################################################################## # pySAP - Copyright (C) CEA, 2017 - 2018 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-e...
#Simple calc operations_math = ['+', '-', '*', '/'] print('This is simle calc') try: a = float(input('a = ')) b = float(input('b = ')) choice = input('Please input math operations: +, -, *, / and get result for you') if choice == operations_math[0]: print(a+b) elif choice == operations_math[1]: ...
# -*- coding: utf-8 -*- # UTF-8 encoding when using korean a = int(input()) b = list(map(int, input().split())) maximun = b[0] minimun = b[0] for data in b: if maximun < data: maximun = data if minimun > data: minimun = data if(maximun - minimun + 1 == a): print("YES") else: print("NO")
class Solution: def convertToTitle(self, columnNumber: int) -> str: if columnNumber < 27: return chr(ord('A') - 1 + columnNumber) val = list() columnNumber = columnNumber - 1 while(True): val.append(columnNumber % 26) if (columnNumber < 26): ...
a = b = source() c = 3 if c: b = source2() sink(b)
#!/usr/bin/env python # -*- coding: utf-8 -*- def garage(init_arr, final_arr): init_arr = init_arr[::] seqs = 0 seq = [] while init_arr != final_arr: zero = init_arr.index(0) if zero != final_arr.index(0): tmp_val = final_arr[zero] tmp_pos = init_arr.index(tmp_val...
def test_environment_is_qa(app_config): base_url = app_config.base_url port = app_config.app_port assert base_url == 'https://myqa-env.com' assert port == '80' def test_environment_is_dev(app_config): base_url = app_config.base_url port = app_config.app_port assert base_url == 'https://myd...
class MyClass: def __init__(self, my_val): self.my_val = my_val my_class = MyClass(1) print(my_class.my_val) print(2) res = 2
''' This problem was asked by Facebook. Given a binary tree, return all paths from the root to leaves. For example, given the tree: 1 / \ 2 3 / \ 4 5 Return [[1, 2], [1, 3, 4], [1, 3, 5]]. ''' # Definition for a binary tree node class TreeNode: def __init__(self, x, left=None, right=None): ...
def loadPostSample(): posts = [['my','dog','has','flea','problems','help','please'], ['maybe','not','take','him','to','dog','park','stupid'], ['my','dalmation','is','so','cute','I','love','him'], ['stop','posting','stupid','worthless','garbage'], ['mr','licks','at...
PROVIDER = "S3" KEY = "" SECRET = "" CONTAINER = "yoredis.com" # FOR LOCAL PROVIDER = "LOCAL" CONTAINER = "container_1" CONTAINER2 = "container_2"
""" Insertion Sort Always keep sorted in the sublist of lower positions. Each new item is then `inserted` back into the previous sublist. The insertion step looks like bubble sort, if the item located at `i` is smaller than the one before, then exchange, until to a proper position. [5, 1, 3, 2] -...
def propagate_go(go_id, parent_set, go_term_dict): if len(go_term_dict[go_id]) == 0: return parent_set for parent in go_term_dict[go_id]: parent_set.add(parent) for parent in go_term_dict[go_id]: propagate_go(parent, parent_set, go_term_dict) return parent_set def form_all_go_pa...
def collide(obj1, obj2): offset_x = obj2.x - obj1.x offset_y = obj2.y - obj1.y return obj1.mask.overlap(obj2.mask, (offset_x, offset_y)) != None
# **************************** Desafio 094 ********************************* # # Unindo dicionários e listas # # Crie um programa que leia nome, sexo e idade de várias pessoas, guardando # # os dados de cada pessoa em um dicionário e todos os dicionários em uma # # li...
""" 2.1 Remove duplicates from an unsorted linked lists. What if a temporary buffer is not allow? """ # SOLUTION 1 - HASHTABLE # EFFICIENCY # space: O(n) time: O(n) def remove_dups_ht(sll): d = {} c = sll l = sll while c: if c.val in d: l.nxt = c.nxt c = l.nxt ...
L1 = [1, 2, 3, 4] L2 = ['A', 'B', 'C', 'D'] meshtuple = [] for x in L1: for y in L2: meshtuple.append([x, y]) print(meshtuple)
# Copyright Contributors to the Amundsen project. # SPDX-License-Identifier: Apache-2.0 TERM_FILTERS_QUERY = { "bool": { "must": [ { "multi_match": { "query": "mock_feature", "fields": [ "feature_name.raw^25", ...
# THEMES # Requires restart # Change the theme variable in config.py to one of these: black = { 'foreground': '#FFFFFF', 'background': '#000000', 'fontshadow': '#010101' } orange = { 'foreground': '#d75f00', 'background': '#303030', 'fontshadow': '#010101' ...
""" This code was Ported from CPython's sha512module.c """ SHA_BLOCKSIZE = 128 SHA_DIGESTSIZE = 64 def new_shaobject(): return { "digest": [0] * 8, "count_lo": 0, "count_hi": 0, "data": [0] * SHA_BLOCKSIZE, "local": 0, "digestsize": 0, } ROR64 = ( lambda ...
print('===== Conversor de Medidas =====') m = float(input('Digite um valor em metros: ')) print('O valor de {:.0f}m em Decimetros é {:.1f}dm!'.format(m, m*10)) print('O valor de {:.0f}m em Centimetros é {:.1f}cm!'.format(m, m*100)) print('O valor de {:.0f}m em Milimetros é {:.1f}mm!'.format(m , m*1000)) print('O valor ...
def exchange(A, i, j): temp = A[i] A[i] = A[j] A[j] = temp return A
while True: num_items = int(input()) if num_items == 0: break # Normal sort also works # items = list(sorted(map(int, input().split()))) # print(" ".join(map(str, items))) buckets = [0 for i in range(101)] for age in map(int, input().split()): buckets[age] += 1 for i, j in enumerate(bu...
src =Split(''' aos/board.c aos/board_cli.c aos/st7789.c aos/soc_init.c Src/stm32l4xx_hal_msp.c ''') component =aos_board_component('starterkit', 'stm32l4xx_cube', src) if aos_global_config.compiler == "armcc": component.add_sources('startup_stm32l433xx_keil.s') elif aos_global_config...
return_date = list(map(lambda x: int(x), input().split())) due_date = list(map(lambda x: int(x), input().split())) day = 0 month = 1 year = 2 if return_date[year] > due_date[year]: fine = 10000 elif return_date[year] < due_date[year]: fine = 0 elif return_date[month] > due_date[month]: fine = 500 * (retur...
#coding=utf-8 nombre = input("Dime tu nombre: ") edad = int(input("dime tu edad wey: ")) nombre2 = input("dime tu nombre tambien wey: ") edad2 = int(input("y tu edad es?... ")) if (edad>edad2): print ("%s, eres mayor que %s" % (nombre , nombre2)) elif (edad<edad2): print ("%s, eres mayor que %s" % (nombre2 , nomb...
class ChartError(Exception): """Raised whenever we have a generic error trying to draw the chart.""" class NoTicketsProvided(ChartError): """Raised if we provide no tickets to the chart.""" def __init__(self) -> None: super().__init__("No tickets provided. Check your config.")
nota1 = float(input('Digite a primeira nota: ')) nota2 = float(input('Digite a segunda nota: ')) media = float(nota1+nota2)/2 print('A primeira nota do aluno é: {}\nE a segunda nota é: {}\nA media desse aluno é: {:.1f}'.format(nota1, nota2, media)) if media < 7.0: print('Aluno reprovado!') else: print('Aluno...
class SimpleAgg: def __init__(self, query, size=0): self.__size = size self.__query = query def build(self): return { "size": self.__size, "query": { "multi_match": { "query": self.__query, ...
''' The purpose of this directory is to contain files used by multiple platforms, but not by all. (In some cases GTK and Mac impls. can share code, for example.) '''
__all__ = [ "__name__", "__version__", "__author__", "__author_email__", "__description__", "__license__" ] __name__ = "python-fullcontact" __version__ = "3.1.0" __author__ = "FullContact" __author_email__ = "pypy@fullcontact.com" __description__ = "Client library for FullContact V3 Enrich and ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def longestConsecutive(self, root: TreeNode) -> int: ret = 0 def helper(node): nonlocal ret if n...
def numeric(literal): """Return value of numeric literal or None if can't parse a value""" castings = [int, float, complex, lambda s: int(s,2), #binary lambda s: int(s,8), #octal lambda s: int(s,16)] #hex for cast in castings: try: return cast(literal) e...
#!/usr/bin/env python NAME = 'InfoGuard Airlock' def is_waf(self): # credit goes to W3AF return self.matchcookie('^AL[_-]?(SESS|LB)=')
def splitT(l): l = l.split(" ") for i,e in enumerate(l): try: val = int(e) except ValueError: val = e l[i] = val return l def strToTupple(l): return [tuple(splitT(e)) if len(tuple(splitT(e))) != 1 else splitT(e)[0] for e in l] lines = strToTupple(lines) sys.stderr.write(str(lines)) f = lines.pop(0) ...
class Loss: def __init__(self, name): self.name = name class MeanSquaredError(Loss): """Mean Squared Error """ def __init__(self): super(MeanSquaredError, self).__init__('mean_squared_error') class CategoricalCrossEntropy(Loss): """Categorical Cross-Entropy """ def __in...
#Faça um Programa que calcule a área de um quadrado, em seguida mostre o dobro desta área para o usuário lado = float(input("qual medida do lado em cm?: ")) base = float(input("qual medida da base em cm?: ")) area = base*lado print("a area do quadrado é: ", area, "cm² e o dobro é:", area*2,"cm²")
# -*- coding: utf-8 -*- """ proxy.py ~~~~~~~~ ⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on Network monitoring, controls & Application development, testing, debugging. :copyright: (c) 2013-present by Abhinav Singh and contributors. :license: BSD, see LICENSE...
TAX_RATES = {0 / 100: range(0, 1001), 10 / 100: range(1000, 10001), 15 / 100: range(10000, 20201), 20 / 100: range(20200, 30751), 25 / 100: range(30750, 50001)} # , 30: 50000 def calculate_tax(people_sal): """ Calculate the annual tax :param people_sal: :return: """ ...
def shell_sort(arr): sublistcount = len(arr)/2 # While we still have sub lists while sublistcount > 0: for start in range(sublistcount): # Use a gap insertion gap_insertion_sort(arr,start,sublistcount) sublistcount = sublistcount / 2 def ga...
def format_si(number, places=2): number = float(number) if number > 10**9: return ("{0:.%sf} G" % places).format(number / 10**9) if number > 10**6: return ("{0:.%sf} M" % places).format(number / 10**6) if number > 10**3: return ("{0:.%sf} K" % places).format(number / 10**3) ...
class SensorManager: class Sensor: def __init__(self, id, name, sType, unit): self.id = id self.name = name self.sType = sType self.unit = unit sensorTypes = { "T_celcius": Sensor("T_celcius", "Temperatur", "T", "°C"), "P_hPa": Sensor("...
# Module is basically a dumping ground for various menus and help text blurbs the terminal may need. def HelpText(): print(""" ------------------ INFO --------------------- TD Ameritrade API Query Tool Version 0.0.1 Command List: history\t\t: Displays ticker price history candles. ...
def check_user(user, session_type=False): frontend.page( "dashboard", expect={ "script_user": testing.expect.script_user(user) }) if session_type is False: if user.id is None: # Anonymous user. session_type = None else: ses...
class Solution: def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if len(strs) == 0: return '' min_str = strs[0] for s in strs[1:]: if len(s) < len(min_str): min_str = s ...
class Solution(object): def maxArea(self, height): """ :type height: List[int] :rtype: int """ left = 0 right = len(height)-1 maxarea = 0 while left < right: maxarea = max(maxarea, (right-left) * min(height[right],...
# -*- coding: utf-8 -*- STATE_ABBR_TO_ID = { 'AC': '12', 'AL': '27', 'AM': '13', 'AP': '16', 'BA': '29', 'CE': '23', 'DF': '53', 'ES': '32', 'GO': '52', 'MA': '21', 'MG': '31', 'MS': '50', 'MT': '51', 'PA': '15', 'PB': '25', 'PE': '26', 'PI': '22', 'PR': '41', 'RJ': '33', 'RN': '24', 'RO': '11', ...
dist = float(input("\nQual a distancia da viagem em km? ")) if (dist > 200): print("\nO preço da sua passagem será de R${:.2f}".format(dist*0.45), end="\n\n") else: print("\nO preço da sua passagem será de R${:.2f}".format(dist*0.5), end="\n\n")
class Solution: # @param S, a list of integer # @return a list of lists of integer def subsets(self, S): S.sort() return self._subsets(S, len(S)) def _subsets(self, S, k): if k == 0: return [[]] else: res = [[]] for i in range(len(S)):...
def _exec_hook(hook_name, self): if hasattr(self, hook_name): getattr(self, hook_name)() def hooks(fn): def hooked(self): fn_name = fn.func_name if hasattr(fn, 'func_name') else fn.__name__ _exec_hook('pre_' + fn_name, self) val = fn(self) _exec_hook('post_' + fn_name, ...
def print_formatted(number): # your code goes here for i in range(1, number + 1): print('{0:>{w}d} {0:>{w}o} {0:>{w}X} {0:>{w}b}'.format(i, w=len(bin(number)) - 2)) if __name__ == '__main__': n = int(input()) print_formatted(n)
# Copyright (c) OpenMMLab. All rights reserved. _base_ = ['./t.py'] base = '_base_.item8' item11 = {{ _base_.item8 }} item12 = {{ _base_.item9 }} item13 = {{ _base_.item10 }} item14 = {{ _base_.item1 }} item15 = dict( a = dict( b = {{ _base_.item2 }} ), b = [{{ _base_.item3 }}], c = [{{ _base_.item4 }}], ...
""" Stack Min: How would you design a stack which, in addition to push and pop, has a function min which returns the minimum element? Push, pop and min should all operate in 0(1) time. """ class Stack: def __init__(self): self._arr = [] self._min_arr = [] def is_empty(self): return not...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def recursion(n): if n == 1: return 1 return n + recursion(n - 1) if __name__ == '__main__': n = int(input("Enter n: ")) summary = 0 for i in range(1, n + 1): summary += i print(f"Iterative sum: {summary}") print(f"Recursion ...
# # PySNMP MIB module SVRSYS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SVRSYS-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:04:40 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, 09:...