content
stringlengths
7
1.05M
""" for image in os.listdir(images_path): img = Image.open(os.path.join(images_path,image)) frame_draw = img.copy() draw = ImageDraw.Draw(frame_draw) for box in boxes: draw.rectangle(box.tolist(), outline=(255, 0, 0), width=6) for landmark in landmarks_points: print(landmark) ...
# model model = Model() i1 = Input("op1", "TENSOR_INT32", "{1, 2, 2, 1}") i2 = Output("op2", "TENSOR_INT32", "{1, 2, 2, 1}") model = model.Operation("ZEROS_LIKE_EX", i1).To(i2) # Example 1. Input in operand 0, input0 = {i1: # input 0 [-2, -1, 0, 3]} output0 = {i2: # output 0 [0, 0, 0, 0]} # Inst...
num = int(input('Digite um número: ')) total = 0 for c in range(1, num + 1): if num % c == 0: total += 1 if total == 2: print(True) else: print(False)
# -*- coding: utf-8 -*- """ Global Configuration """ mssql = { 'server' : 'localhost\SQL2016', 'database' : 'bkrob', 'username' : 'bkrob_adm', 'password' : 'bkrob_adm' } google_geocode_api = 'api key'
def hello(): # Hey i'm a comment # I am a helpful note for humans, and will not be ran pass if __name__ == '__main__': hello()
# Prob 2 # Create a small program that will: # Ask for user input # Count the number of vowels in the user text ('a', 'e', 'i', 'o', 'u', 'y') # Display the number of vowels in user text print("Please enter a string") my_string = input() vowels = ['a', 'e', 'i', 'o', 'u', 'y'] count = 0 for letter in my_string.lower()...
termo = int(input('Primeiro Termo: ')) razao = int(input('Razão: ')) contador = 0 acumulador = termo continuar = 1 while contador != 10: print(acumulador, '→ ', end='') acumulador += razao contador += 1 print('PAUSA') while continuar != 0: continuar = int(input('Quer mostrar mais quantos termos?: ')) ...
def my_func(arr1, arr2, arr3): ln1 = len(arr1) ln2 = len(arr2) ln3 = len(arr3) ptr1 = 0 ptr2 = 0 ptr3 = 0 while ptr1 < ln1 and ptr2 < ln2 and ptr3 < ln3: if arr1[ptr1] < arr2[ptr2]: if arr3[ptr3] < arr2[ptr2]: arr1[ptr1] = -1 arr3[ptr3...
n1 = float(input('Informe um número: ')) n2 = float(input('Informe um número: ')) n3 = float(input('Informe um número: ')) if (n1<n2) and (n1<n3) and (n2<n3): print (n1,n2,n3) elif (n2<n1) and (n2<n3) and (n1<n3): print(n2,n1,n3) else: print(n3,n1,n2)
# # PySNMP MIB module RAPTOR-SNMPv1-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RAPTOR-SNMPv1-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:43:39 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
class AppNotFoundError(Exception): pass class ClassNotFoundError(Exception): pass
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Nov 29 10:26:43 2020 @author: fa19 """
class FilterDoesNotExistError(Exception): """ Raised when a filter does not exist. """ pass class APIError(Exception): """ Error returned by the API. """ pass class ValidationError(Exception): """ Raised when filters receive invalid data """ pass
#!/usr/bin/env python3 """ Boolean data 1 bit 0,1 """ def encode(value): return [int(value) & 0x01] def decode(data): return (data & 0x01)
#coding: utf-8 """ Faça um Programa que leia um vetor A com 10 números inteiros, calcule e mostre a soma dos quadrados dos elementos do vetor. """ def tratarErrorInt(n): if n != "": return n.isdigit() else: return False cond = True numInt = [] x = 1 while x <= 10: while cond: num = input("Informe o " + str(x...
#!/usr/bin/env python3 # fileencoding=utf-8 def char_width(char): # For japanese. if len(char) == 1: return 1 else: return 2 def string_width(_string): char_width_list = [] for c in _string.decode('utf-8'): char_width_list.append(char_width(c)) return char_width_list d...
x = "Hello" y = 15 print(bool(x)) print(bool(y))
class Solution: def findMedianSortedArrarys(self, A, B): lengthA = len(A) lengthB = len(B) new_arr = [] i = j = 0 while i < lengthA and j < lengthB: if A[i] < B[j]: new_arr.append(A[i]) i += 1 else: new_...
#!/user/bin/python # -*-coding:UTF-8-*- """循环双链表""" class Node: def __init__(self, elem, prev: "Node" = None, next_: "Node" = None): self.elem = elem self.prev = prev self.next_ = next_ class CyDoubleLinkList: def __init__(self): self._head: Node = None self._rear: ...
""" Dada 2 Strings ("a" e "b"), retorne outra no fomato "abba". Ex.:(('Hi', 'Bye') → 'HiByeByeHi'; ('What', 'Up') → 'WhatUpUpWhat'; ('Yo', 'Alice') → 'YoAliceAliceYo'). """ def make_abba(a, b): return a + 2*b + a print(make_abba("Hi", "bye"))
'''Crie um programa que simule o funcionamento de um caixa eletrônico. No início, pergunte ao usuário qual será o valor a ser sacado (número inteiro) e o programa vai informar quantas cédulas de cada valor serão entregues. OBS: considere que o caixa possui cédulas de R$50, R$20, R$10 e R$5. ''' print('='*40) print('{...
"""LISTA02_Q04 Faça um programa que grave uma lista com 15 posições, calcule e mostre: a) O maior elemento da lista e em que posição esse elemento se encontra; b) O menor elemento da lista e em que posição esse elemento se encontra.""" lista = [] mai = men = 0 for n in range(0, 15): num = int(input("Digite um núme...
#!/usr/bin/env python3 count = 0 with open("romeo.txt") as romeo: text = romeo.readlines() for line in text: if "ROMEO" in line: count += 1 print(count)
# 22004 | Fixing the Fence (Evan intro) sm.setSpeakerID(1013103) sm.sendNext("Ah, did you bring all the Thick Branches? That's my kid! What shall i give you as reward?... Let's see... Oh, right! \r\n #fUI/UIWindow2.img/QuestIcon/4/0# \r\n #v3010097# Strong Wooden Chair \r\n #fUI/UIWindow2.img/QuestIcon/8/0# 210 exp")...
def rice_describ(*rice): print('\n下面介绍各种大米的分类和基础介绍:') print(rice) rice_describ('糙米:稻谷去除稻壳后之稻米,保留了八成的产物比例。营养价值较胚芽米和白米较高,但浸 水和煮食时间也较长') rice_describ('胚芽米:糙米加工后去除糠层保留胚及胚乳,保留了七成半的产物比例,是糙米和白 米的中间产物', '白米:(即我们平时食用的白米或大米) 糙米经继续加工,碾去皮层和胚 (即细 糠),基本上只剩下胚乳,保留了七成的产物比例。市场上最主要的类别', '预熟米 (改造米):将食米经浸润、蒸煮、干燥等处理') rice_describ...
# Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def levelOrder(self, A): queue = [] ansr_queue = [] queue.append(A) marker = "$" queue.append(marker) ...
'''FAÇA UM PROGRAMA QUE LEIA O NOME E O PESO DE VÁRIAS PESSOAS, GUARDANDO TUDO EM UMA LISTA. AO FINAL MOSTRE: A - QUANTAS PESSOAS FORAM CADASTRADAS B - UMA LISTAGEM COM AS PESSOAS MAIS PESADAS C - UMA LISTAGEM COM AS PESSOAS MAIS LEVES CRITÉRIO, PESADO 100 OU MAIS, LEVE 70 OU MENOS''' temp = list() princ = list() mai =...
""" SPI typing class This class includes full support for using ESP32 SPI peripheral in master mode Only SPI master mode is supported for now. Python exception wil be raised if the requested spihost is used by SD Card driver (sdcard in spi mode). If the requested spihost is VSPI and the psRAM is used at 80 MHz, the ...
class Solution: def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ # using library # itertools.permutations(nums) - tuples on iterating # return list(map(list, itertools.permutations(nums))) # recursive # i...
class Solution: def numberOfWays(self, numPeople: int) -> int: kMod = int(1e9) + 7 # dp[i] := # of ways i handshakes pair w//o crossing dp = [1] + [0] * (numPeople // 2) for i in range(1, numPeople // 2 + 1): for j in range(i): dp[i] += dp[j] * dp[i - 1 - j] dp[i] %= kMod r...
# Language: Python 3 n = int(input()) if (n % 2 != 0): print("Weird") elif (2 <= n <= 5): print("Not Weird") elif (6 <= n <= 20): print("Weird") else: print("Not Weird")
bot_token = "" bot_token_dev = "" db_url = "" mod_db_url = "" cloudflare_email = "" cloudflare_token = "" error_webhook_token = "" error_webhook_id = 0 consumer_key = "" consumer_secret_key = "" access_token = "" access_token_secret = ""
# map function #iterable as list or array #function as def or lambda #map(function,iterable) or numbers=[1,2,3,4,5,6] #example def Sqrt(number): return number**2 a=list(map(Sqrt,numbers)) print(a) #example b=list(map(lambda number:number**3,numbers)) print(b) #map(str,int,double variable as ...
# # PySNMP MIB module ChrTrap-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ChrTrap-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:36:20 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...
# Time: 218 ms # Memory: 4 KB for i in range(5): m = list(map(int, input().split())) if 1 in m: r, c = (m.index(1)), (i) sol = abs(r - 2) + abs(2 - c) print(sol)
nama = "azmi" umur_5_tahun_lalu = 23 print ("nama saya") print(nama) print("sedangkan umur saat ini adalah") print(umur_5_tahun_lalu + 5) if (nama == "nathan") : print("selamat datang Nathan!") elif (nama == "azmi") : print("selamat datang Azmi!") else : print("Selamat datang pak") print(nama)
def exact_cover(X, Y): X = {j: set() for j in X} for i, row in Y.items(): for j in row: X[j].add(i) return X, Y def select(X, Y, r): cols = [] for j in Y[r]: for i in X[j]: for k in Y[i]: if k != j: X[k].re...
print('NUMEROS POR EXTENSO!!!') print('=-=' * 15) numeros = ('Zero', 'Um', 'Dois', 'Tres', 'Quatro', 'Cinco', 'Seis', 'Sete', 'Oito', 'Nove', 'Dez', 'Onze', 'Doze', 'Treze', 'Quatorze', 'Quinze', 'Dezesseis', 'Dezessete', 'Dezoito', 'Dezenove', 'Vinte') while True: n = int(input('Escolha um numero entre ...
class Node(object): '''Binary Tree Node''' def __init__(self, data): self.data = data self.left = None self.right = None class BinaryTree(object): '''Building binary Tree''' def __init__(self, data): self.root = Node(data) def addLeft(self, data): if self...
def is_k_anonymous(df, partition, sensitive_column, k=3): """ :param df: The dataframe on which to check the partition. :param partition: The partition of the dataframe to check. :param sensitive_column: The name of the sensitive column :param k: The desired k ...
class MyMeta(type): def __new__(mcs, name, bases, namespace, **kwargs): print(f'{mcs}, called __new__') return super().__new__(mcs, name, bases, namespace) @classmethod def __prepare__(mcs, name, bases, **kwargs): print(f'{mcs}, called __prepare__') return {'🐙🐙🐙': 'たこ'}...
# 1 - Usando estas 2 listas, fazer uma função que crie retorne uma lista com dicionários # com os dados das pessoas com idade maior ou igual a 18 anos # # 2 - Imprima a lista resultante com um for imprimindo um dicionário em cada linha # (não prescisa usar o f-string, .format()) # # 3 - Imprima a lista resultante c...
YELLOW = (255, 255, 0) CYAN = (0, 255, 255) RED = (255, 0, 0)
# this is a python file created in jupyter notbook def list_fruits(fruits=[]): for fruit in fruits: print(fruit) fruits = ['apple','kiwi','banana'] list_fruit(fruits)
lst = [['Harry', 37.21],['Berry', 37.21],['Tina', 37.2],['Akriti', 41],['Harsh', 39]] second_highest = sorted(list(set([marks for name, marks in lst])))[1] print('\n'.join([a for a,b in sorted(lst) if b == second_highest]))
# 二叉堆实现优先队列(PriorityQueue) # 这里使用列表实现二叉堆,其本质是一个有序的完全二叉树,索引从1始计,每个节点的左子节点索引为节点索引*2,右子节点为节点索引*2+1 # 反过来一个子节点其父节点的索引为子节点索引//2,根据该特性,可以快速上浮、下沉元素 class BinaryHeap(object): def __init__(self): """ 创建一个空的二叉堆对象 """ self.heap_list = [0] self.current_size = 0 def insert(self, d...
"""Depth First Search Algorithm implmentation. @author Victor I. Afolabi Artificial Intelligence & Software Engineer. Email: javafolabi@gmail.com GitHub: https://github.com/victor-iyiola @project File: search/depth_first.py Created on 22 August, 2018 @ 8:57 PM. @license MI...
_menu_name = "Networking" _ordering = [ "wpa_cli", "network", "nmap", "upnp"]
i = 0 while True: n, q = map(int, input().split()) if n == 0 and q == 0: break marble_numbers = [] while n>0: n -= 1 num = int(input()) marble_numbers.append(num) marble_numbers.sort() i += 1 print(f"CASE# {i}:") while q > 0: q ...
class Board: ''' A 3x3 board for TicTacToe ''' __board = '' __print_board = '' def __init__(self): self.__board = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']] self.make_printable() def __str__(self): self.make_printable() return self.__print_board ...
#TempConvert_loop.py for i in range(3): val = input("Input the temp:(32C)") if val[-1] in ['C','c']: f = 1.8 * float(val[0:-1]) + 32 print("Converted temp is: %.2fF"%f) elif val[-1] in ['F','f']: c = (float(val[0:-1]) - 32) / 1.8 print("Converted temp is: %.2fC"%c) else: print("Wrong input")
# -*- coding: utf-8 -*- """ This source code file is licensed under the GNU General Public License Version 3. For full details, please refer to the file "LICENSE.txt" which is provided as part of this source code package. Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. """ TOP_LEVEL_TREE_K...
CLASSIFIER_SCALE = 1.1 CLASSIFIER_NEIGHBORS = 5 CLASSIFIER_MIN_SZ = (50, 50) MIN_SAMPLES_PER_USER = 50 FACE_BOX_COLOR = (255, 0, 255) FACE_TXT_COLOR = (115, 249, 255) LBP_RADIUS = 2 LBP_NEIGHBORS = 16 LBP_GRID_X = 8 LBP_GRID_Y = 8 KNOWN_USER_FILE = 'users.lst' LBPH_MACHINE_LEARNING_FILE = 'lbph_face_recognizer.yam...
print('-' * 30) print(f'{"Lojas do Moomen":^30}') print('-' * 30) soma = totmais = menor = cont = 0 while True: produto = str(input('Nome do produto: ')) preco = float(input('Preço: R$')) soma += preco cont += 1 if cont == 1 or preco < menor: menor = preco prodmenor = produto if ...
potencia = int(input()) tempo = int(input()) qw = potencia / 1000 hr = tempo / 60 kwh = hr * qw print('{:.1f} kWh'.format(kwh))
#Una variable que existe fuera de una función tiene alcance dentro del cuerpo de la función. def miFuncion(): print("¿Conozco a la variable?", var) var = 1 miFuncion() print(var) #Una variable que existe fuera de una función tiene un alcance dentro del cuerpo de la función, excluyendo a aquellas que tienen el mis...
n = 60 for i in range(10000): 2 ** n
"""Script to fix indentation of given ``.po`` files.""" __author__ = """Julien Palard""" __email__ = "julien@palard.fr" __version__ = "1.0.0"
class Solution(object): def XXX(self, m, n): """ :type m: int :type n: int :rtype: int """ dp = [1]*n dp = [dp]*m for i in range(m): for j in range(n): if i!=0 and j!=0: dp[i][j] = dp[i-1][j] + dp[i][j-1]...
# ................................................................................................................. level_dict["bombs"] = { "scheme": "red_scheme", "size": (9,9,9), "intro": "bombs", "help": ...
class BaseDecoder(object): def __init__(self, name="BaseDecoder"): self.name = name print(name) def decode(self, **kwargs): """ Using for greedy decoding for a given input, may corresponding with gold target, return the log_probability of decoder steps. """ ...
class Calculator: def __init__(self, socket): self.socket = socket def run(self): self.socket.emit('response', 'Here is your result')
#import sys def interpret_bf_code(bf_code, memory_size = 30000): ''' (str, (int)) -> str This function interprets code in the BrainFuck language, which is passed in via bf_code parameter and returns the output of executing that code. If so specified in BrainFuck code, the function reads input ...
# flatten 2D arrays into a single array A = [[1, 2, 3], [4], [5, 6]] # iterative version def flatten_iterative(A): result = [] for array in A: for element in array: result.append(element) return result print(flatten_iterative(A)) # recursively traverse 2 dimensional list out of order...
# This class provides a way to drive a robot which has a drive train equipped # with separate motors powering the left and right sides of a robot. # Two different drive methods exist: # Arcade Drive: combines 2-axes of a joystick to control steering and driving speed. # Tank Drive: uses two joysticks to control mot...
def formatação(quem, prog, n): return '{quem} está apresentando a {prog} #{n}' nome = 'Eduardo' programa = 'Live de Python' numero = 197 breakpoint() formatado = formatação(nome, programa, numero) breakpoint() # TESTE! assert formatado == 'Eduardo está apresentando a Live de Python #197'
""" ------------------------------------------------------------------------------- G E N E R A L I N F O R M A T I O N ------------------------------------------------------------------------------- This file contains general constants and information about the variables saved in the netCDF file needed for plotge...
if __name__ == '__main__': l = input().strip().split() data = [int(i) for i in l] n = int(input()) sum = [0 for i in range(0, len(data)+1)] sum[0] = data[0] for i in range(1, len(data)): sum[i] = sum[i-1] + data[i] # print(sum) found = False for length in range(0, len(data...
i = 1 while True: inp = input() if inp == "Hajj": inp = "Hajj-e-Akbar" elif inp == "Umrah": inp = "Hajj-e-Asghar" else: break print("Case {}: {}".format(i, inp)) i += 1
class Report: def __init__(self, report): self.report = report @property def name(self): return self.report['name'] @property def filename(self): return self.report['filename'] @property def klass(self): return self.report['class'] @property def s...
def main_menu(): input_map = {'1': 'compute', '2': 'storage', '3': 'default', '4': 'exit'} print('\nSelect from the options below:') print(' 1. Set up or remove a compute service') print(' 2. Set up or remove a storage service') print(' 3. Change settings for compute or storage service (i.e. de...
class Request: pass class DirectoryInfoRequest(Request): def __init__(self, path): super().__init__() self.path = path class AdditionalEntryPropertiesRequest(Request): def __init__(self, filepath): super().__init__() self.filepath = filepath
######################## #######lecture 15####### ######################## class Node: def __init__(self , value=None): self.value = value self.next = None # def __str__(self): # return str(self.value) class Stack: def __init__(self , node=None): self.top = node ...
version_info = (0, 0, '6a1') __version__ = '.'.join(map(str, version_info)) if __name__ == '__main__': print(__version__)
"""Crie um programa que leia um número inteiro e mostre na tela se ele é PAR ou ÍMPAR.""" num = int(input('Digite um número: ')) resultado = num % 2 if resultado == 0: print('O NUMERO {} É PAR'.format(num)) else: print('O NUMERO {} É IMPAR'.format(num))
# Python equivalent of an array is a list def reverse_array(a_list): """ https://www.hackerrank.com/challenges/01_arrays-ds/problem We can reverse an array by simply providing the step value in list slice parameters -1 means go backwards one by one """ return a_list[::-1]
#!/usr/local/bin/python3 try: arquivo = open('pessoas.csv') for it in arquivo: print('Nome {}, Idade {}'.format(*it.strip().split(','))) finally: arquivo.close()
@authenticated def delete(self): model = self.db.query([model_name]).filter([delete_filter]).first() self.db.delete(model) self.db.commit() return JsonResponse(self, '000')
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def longestZigZag(self, root: Tre...
def equal_slices(total, num, per_person): res = num * per_person if res <= total: return True return False foo = equal_slices(11, 11, 1) print(str(foo))
class FileExtractorTimeoutException(Exception): pass class ParamsInvalidException(Exception): pass class NoProperExtractorFindException(Exception): def __init__(self): super().__init__('NoProperExtractorFind Exception')
alunos = list() nomes = list() notas = list() media = somanota = n1 = n2 = cont = 0 while True: nomes.append(str(input('Nome: '))) notas.append(float(input('Nota 1: '))) notas.append(float(input('Nota 2: '))) nomes.append(notas[:]) alunos.append(nomes[:]) notas.clear() nomes.clear() cont...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Purpose: Agent API Methods ''' __author__ = 'Matt Joyce' __email__ = 'matt@joyce.nyc' __copyright__ = 'Copyright 2016, Symphony Communication Services LLC' class Base(object): def __init__(self, *args, **kwargs): super(Base, self).__init__(*...
s = input() k1 = input() k2 = input() out = "" for c in s: found = False for i in range(len(k1)): if c == k1[i]: out += k2[i] found = True break elif c == k2[i]: out += k1[i] found = True break if not found: out ...
# This program converts the speeds 60 kph # through 130 kph (in 10 kph increments) # to mph. START_SPEED = 60 END_SPEED = 131 INCREMENT = 10 CONVERSION_FACTOR = 0.6214 # Print the table headings. print('KPH\tMPH') print('--------------') # Print the speeds for kph in range(START_SPEED, END_SPEED, INCREMENT): ...
d = dict() d['quincy'] = 1 d['beau'] = 5 d['kris'] = 9 for (k,i) in d.items(): print(k, i)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # author by: One Zero # Filename: test.py ## 用户输入数字 #num1 = input('输入第一个数字: ') #num2 = input('输入第二个数字: ') # ## 求和 #sum = float(num1) + float(num2) # ## 显示计算结果 #print('数字 {0} 和 {1} 相加结果为: {2}'.format(num1, num2, sum)) print('两数之和为 %.1f' % (float(input('输入第一个数字: ')) + floa...
# Africa 2010 # Problem A: Store Credit # Jon Hanson # # Declare Variables # ifile = 'input.txt' # simple input ofile = 'output.txt' # simple output #ifile = 'A-large-practice.in' # official input #ofile = 'A-large-practice.out' # official output caselist = [] # list containing cases # # Problem S...
""" -2.合并两个链表 时间复杂度:O(n) 空间复杂度:O(1) """ # -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class ListNode: def __init__(self, x): self.val = x self.next = None def createListNode(list_node): if not list_node: return No...
class PodpingCustomJsonPayloadExceeded(RuntimeError): """Raise when the size of a json string exceeds the custom_json payload limit""" class TooManyCustomJsonsPerBlock(RuntimeError): """Raise when trying to write more than 5 custom_jsons in a single block"""
# Version 1: build products of before and after i, Time: O(n), Space: O(n) class Solution: def productExceptSelf(self, nums): """ :type nums: List[int] :rtype: List[int] """ # scan from left to right to find products before i before_i = [i for i in range(len(nums))] ...
def most_frequent(data): """ determines the most frequently occurring string in the sequence. """ # your code here max = 0 res = '' for each in data: if max < data.count(each): res = each max = data.count(each) return res if __name__ == '__main__': ...
# Crie um programa que leia varios numeros # inteiros pelo teclado. O programa so # vai parar quando o usuario digitar o # valor 999, que eh a condicao de parada. # No final, mostre quantos numeros foram # digitados e qual foi a soma entre eles # (desconsiderando o flag). n = s = c = 0 while True: n = int(input('Di...
class AdapterError(Exception): pass class ServiceAPIError(Exception): pass
#!/usr/bin/env python problem4 = max(i*j for i in range(100, 1000+1) for j in range(i, 1000+1) \ if str(i*j) == str(i*j)[::-1]) print(problem4)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Unit tests for dataset class.""" # import datetime # import os # import unittest # # from pma_api import db, create_app # from pma_api.db_models import Dataset # # from .config import TEST_STATIC_DIR # # # # TODO: incomplete # class TestDataset(unittest.TestCase): # ...
#!/usr/bin/env python class Solution: def search(self, nums: 'List[int]', target: 'int') -> 'int': lo, hi = 0, len(nums)-1 while lo <= hi: mi = lo + (hi-lo)//2 if target == nums[mi]: return mi if nums[lo] <= nums[mi]: if nums[lo] <= target < nums[...
def add_time(start, duration, day=None): time, period = start.split() initial_period = period hr_start, min_start = time.split(':') hr_duration, min_duration = duration.split(':') min_new = int(min_start) + int(min_duration) hr_new = int(hr_start) + int(hr_duration) periods_later = 0 days_later = 0...
# Histogram of life_exp, 15 bins plt.hist(life_exp, bins = 15) # Show and clear plot plt.show() plt.clf() # Histogram of life_exp1950, 15 bins plt.hist(life_exp1950, bins = 15) # Show and clear plot again plt.show() plt.clf()
class Solution(object): def numberToWords(self, num): under_twenty = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"] under_hundred_above_twenty = ["Twenty", "Thi...