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) draw.point(landmark,fill="black") frame_draw.show() d = display.display(draw, display_id=True) """ sys.exit() # For a model pretrained on VGGFace2 model = InceptionResnetV1(pretrained='vggface2').eval() # For a model pretrained on CASIA-Webface model = InceptionResnetV1(pretrained='casia-webface').eval() # For an untrained model with 100 classes model = InceptionResnetV1(num_classes=100).eval() # For an untrained 1001-class classifier model = InceptionResnetV1(classify=True, num_classes=1001).eval() # If required, create a face detection pipeline using MTCNN: #mtcnn = MTCNN(image_size=<image_size>, margin=<margin>) # Draw faces frame_draw = img.copy() draw = ImageDraw.Draw(frame_draw) for box in boxes: draw.rectangle(box.tolist(), outline=(255, 0, 0), width=6) draw.point() frame_draw.show() d = display.display(draw, display_id=True) # Create an inception resnet (in eval mode): resnet = InceptionResnetV1(pretrained='vggface2').eval()
# 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]} # Instantiate an example Example((input0, output0))
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(): if letter in vowels: count += 1 print("Number of vowels in string: " + str(count)) # Prob 3 # Create a small program where # The user inputs an email # The program checks if the email ends with @gmail.com # The program prints True if email ends with @gmail.com and False if it doesn't print("Please enter a Gmail email") email = input() print(email[-10:] == "@gmail.com")
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?: ')) for c in range(0, continuar): print(acumulador, '→ ', end='') acumulador += razao contador += 1 if continuar != 0: print('PAUSA') print('Progressão finalizada com {} termos mostrados, Obrigado.'.format(contador))
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] = -1 ptr3 += 1 ptr1 += 1 else: arr1[ptr1] = -1 ptr1 += 1 elif arr2[ptr2] < arr3[ptr3]: if arr1[ptr1] < arr3[ptr3]: arr1[ptr1] = -1 arr2[ptr2] = -1 ptr1 += 1 ptr2 += 1 else: arr2[ptr2] = -1 ptr2 += 1 elif arr3[ptr3] < arr1[ptr1]: if arr2[ptr2] < arr1[ptr1]: arr2[ptr2] = -1 arr3[ptr3] = -1 ptr2 += 1 ptr3 += 1 else: arr3[ptr3] = -1 ptr3 += 1 else: ptr1 += 1 ptr2 += 1 ptr3 += 1 for i in arr1: if i != -1: print(i, end=' ') ls1 = [1, 5, 5] ls2 = [3, 4, 5, 5, 10] ls3 = [5, 5, 10, 20] my_func(ls1, ls2, ls3)
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, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") MibIdentifier, Gauge32, enterprises, Counter64, Bits, Unsigned32, Counter32, ModuleIdentity, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, IpAddress, NotificationType, NotificationType, iso, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "Gauge32", "enterprises", "Counter64", "Bits", "Unsigned32", "Counter32", "ModuleIdentity", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "IpAddress", "NotificationType", "NotificationType", "iso", "TimeTicks") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") raptorSystems = MibIdentifier((1, 3, 6, 1, 4, 1, 1294)) raptorModules = MibIdentifier((1, 3, 6, 1, 4, 1, 1294, 1)) raptorObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 1294, 2)) raptorTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 1294, 3)) raptorNotifyMessage = MibScalar((1, 3, 6, 1, 4, 1, 1294, 2, 1), OctetString()) if mibBuilder.loadTexts: raptorNotifyMessage.setStatus('mandatory') raptorNotifyTrap = NotificationType((1, 3, 6, 1, 4, 1, 1294) + (0,1)).setObjects(("RAPTOR-SNMPv1-MIB", "raptorNotifyMessage")) mibBuilder.exportSymbols("RAPTOR-SNMPv1-MIB", raptorTraps=raptorTraps, raptorNotifyMessage=raptorNotifyMessage, raptorSystems=raptorSystems, raptorModules=raptorModules, raptorNotifyTrap=raptorNotifyTrap, raptorObjects=raptorObjects)
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) + "º número: ") if tratarErrorInt(num) == True: num = int(num) num **= 2 numInt.append(num) break else: print("Informe um valor válido") x += 1 print() print("Soma dos quadrados do número é", str(sum(numInt))) input()
#!/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 def add_space(_string, num): return _string+' '*num def constant_width(_string, width): out = '' char_width_list = string_width(_string) width_sum = 0 _end = 0 if sum(char_width_list) < width: return add_space(_string, width - sum(char_width_list)) for i, val in enumerate(char_width_list): width_sum += val if width_sum > width: _end = i break ustring = _str return out
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_arr.append(B[j]) j += 1 while i < lengthA: new_arr.append(A[i]) i += 1 while j < lengthB: new_arr.append(B[j]) j += 1 if((lengthA + lengthB)%2 == 1): return(new_arr[int((lengthA+lengthB)/2)]) else: return((new_arr[int((lengthA+lengthB)/2)]+new_arr[int((lengthA+lengthB)/2)-1])/2)
#!/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: Node = None def prepend(self, elem): """向表首插入元素""" p = Node(elem, prev=self._rear, next_=self._head) if self._head is None: p.next_, p.prev = p, p self._rear = p else: self._rear.next_ = p self._head.prev = p self._head = p def append(self, elem): """向表尾插入元素""" p = Node(elem, prev=self._rear, next_=self._head) if self._head is None: p.next_, p.prev = p, p else: self._rear.next_ = p self._head.prev = p self._rear = p def insert(self, elem, idx: int): if not isinstance(idx, int): raise TypeError("idx must be integer") if idx < 0 or idx > self.length(): raise IndexError("idx must greater >= 0 and <= list's length") if idx == 0: self.prepend(elem) elif idx == self.length(): self.append(elem) else: new_node = Node(elem) p = self._head while idx > 0: p = p.next_ idx -= 1 q = p.prev q.next_, new_node.prev = new_node, q new_node.next_, p.prev = p, new_node def del_first(self): if self._head is None: raise ValueError("list is null") del_elem = self._head.elem if self._head is self._rear: self._head: Node = None self._rear: Node = None else: p = self._head.next_ p.prev, self._rear.next_, self._head = self._rear, p, p return del_elem def del_last(self): if self._head is None: raise ValueError("list is null") del_elem = self._rear.elem if self._head is self._rear: self._head: Node = None self._rear: Node = None else: p = self._rear.prev p.next_, self._head.prev, self._rear = self._head, p, p return del_elem def pop(self, idx): if not isinstance(idx, int): raise TypeError("idx must be integer") if idx < 0 or idx >= self.length(): raise IndexError("idx must greater >= 0 and < list's length") if idx == 0: return self.del_first() elif idx == self.length() - 1: return self.del_last() else: p = self._head while idx > 0: p = p.next_ idx -= 1 p.prev.next_, p.next_.prev = p.next_, p.prev return p.elem def length(self): p = self._head if p is None: return 0 _sum = 1 while p is not self._rear: _sum += 1 p = p.next_ return _sum def is_empty(self): return self._head is None def __str__(self): print_list = ["["] p = self._head while p is not self._rear: if p.next_ is self._rear: print_list.append(f"{p.elem}, {self._rear.elem}]") else: print_list.append(f"{p.elem}, ") p = p.next_ return "".join(print_list) lst = CyDoubleLinkList() for i in range(5, -1, -1): lst.prepend(i) print(lst.length()) # 6 print(lst) # [0, 1, 2, 3, 4, 5] for i in range(6, 10): lst.append(i) print(lst.length()) # 10 print(lst) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] lst.insert(2.5, 3) print(lst.length()) # 11 print(lst) # [0, 1, 2, 2.5, 3, 4, 5, 6, 7, 8, 9] print(lst.del_first()) # 0 print(lst.length()) # 10 print(lst) # [1, 2, 2.5, 3, 4, 5, 6, 7, 8, 9] print(lst.del_last()) # 9 print(lst.length()) # 9 print(lst) # [1, 2, 2.5, 3, 4, 5, 6, 7, 8] print(lst.pop(2)) # 2.5 print(lst.length()) # 8 print(lst) # [1, 2, 3, 4, 5, 6, 7, 8]
""" 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('{: ^40}'.format('CAIXA ELETRÔNICO')) print('='*40) saque = int(input('Qual valor você gostaria de sacar? R$')) tot = saque cedula = 50 totced = 0 while True: if tot >= cedula: tot -= cedula totced += 1 else: if totced > 0: print(f'Total de {totced} cédulas de R${cedula}') if cedula == 50: cedula = 20 elif cedula == 20: cedula = 10 elif cedula == 10: cedula = 5 totced = 0 if tot == 0: break print('Obrigado volte sempre!')
"""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úmero: ")) lista.append(num) if n == 0: mai = men = num else: if num > mai: mai = num if num < men: men = num for i, v in enumerate(lista): if lista[i] == mai: print(f"O maior número da lista {lista} é: {mai}, e está na posição {i}.") for i, v in enumerate(lista): if lista[i] == men: print(f"O menor número da lista {lista} é: {men}, e está na posição {i}.")
#!/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") if sm.canHold(3010097): sm.giveItem(3010097) sm.giveExp(210) sm.completeQuest(parentID) sm.dispose() else: sm.sendNext("Please make room in your Set-up Inventory") sm.dispose()
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) row = [] while len(queue) > 0: ele = queue.pop(0) if ele != marker: row.append(ele.val) if ele.left is not None: left = ele.left queue.append(left) if ele.right is not None: right = ele.right queue.append(right) else: ansr_queue.append(row) row = [] if len(queue) == 0: break queue.append(marker) return ansr_queue
'''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 = men = 0 while True: temp.append(str(input('Nome: '))) temp.append(float(input('Peso: '))) if len(princ) == 0: mai = men = temp[1] else: if temp[1] > mai: mai = temp[1] if temp[1] < men: men = temp[1] princ.append(temp[:]) temp.clear() resp = str(input('Quer continuar?: ')) if resp in 'Nn': break print('-=' * 30) print(f'Ao todo foram cadastradas {len(princ)} pessoas.') print(f'O maior peso digitado foi {mai}kg. Peso de ', end='') for p in princ: if p[1] == mai: print(f'[{p[0]}] ', end='') print() print(f'O menor peso digitado foi {men}kg. Peso de ', end='') for p in princ: if p[1] == men: print(f'[{p[0]}] ', end='') print()
""" 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 exception will be raised. The exception will be raised if SPI cannot be configured for given configurations. """ class SPI: def deinit(self): """ Deinitialize the SPI object, free all used resources. """ pass def read(self, len, val): """ Read len bytes from SPI device. Returns the string of read bytes. If the optional val argument is given, outputs val byte on mosi during read (if duplex mode is used). """ pass def readinto(self, buf, val): """ Read bytes from SPI device into buffer object buf. Length of buf bytes are read. If the optional val argument is given, outputs val byte on mosi during read (if duplex mode is used). """ pass def readfrom_mem(self, address, length, addrlen): """ Writes address to the spi device and reads length bytes. The number of the address bytes to write is determined from the address value (1 byte for 0-255, 2 bytes for 256-65535, ...). The number of address bytes to be written can also be set by the optional argument addrlen (1-4). Returns the string of read bytes. """ pass def write(self, buf): """ Write bytes from buffer object buf to the SPI device. Returns True on success, False ion error """ pass def write_readinto(self, wr_buf, rd_buf): """ Write bytes from buffer object wr_buf to the SPI device and reads from SPI device into buffer object rd_buf. The lenghts of wr_buf and rd_buf can be different. In fullduplex mode write and read are simultaneous. In halfduplex mode the data are first written to the device, then read from it. Returns True on success, False ion error """ pass def select(self): """ Activates the CS pin if it was configured when the spi object was created. """ pass
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 # if len(nums) == 1: # return [nums] # result = [] # for i in range(len(nums)): # result = result + [[nums[i]] + l for l in self.permute(nums[:i]+nums[i+1:])] # return result # iterative result = [[]] for n in nums: new_permutations = [] # each current configuration has to have this n inserted in it for permutation in result: # insert current n at all possible positions (including front and back) for i in range(len(permutation) + 1): new_permutations.append(permutation[:i] + [n] + permutation[i:]) result = new_permutations return result
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 return dp[numPeople // 2]
# 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 convert,iterable) #example str_numbers=["1","2","3","4","5","6"] c=list(map(int,str_numbers)) print(c)
# # 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, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection") chrComTrap, = mibBuilder.importSymbols("Chromatis-MIB", "chrComTrap") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") IpAddress, NotificationType, iso, TimeTicks, NotificationType, Counter64, Counter32, Integer32, ObjectIdentity, Gauge32, ModuleIdentity, MibIdentifier, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "NotificationType", "iso", "TimeTicks", "NotificationType", "Counter64", "Counter32", "Integer32", "ObjectIdentity", "Gauge32", "ModuleIdentity", "MibIdentifier", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") chrComTrapLoggedTrap = NotificationType((1, 3, 6, 1, 4, 1, 3695, 1, 6) + (0,1)) if mibBuilder.loadTexts: chrComTrapLoggedTrap.setDescription('This trap informs about a new event that was reported to the TrapLog table.') mibBuilder.exportSymbols("ChrTrap-MIB", chrComTrapLoggedTrap=chrComTrapLoggedTrap)
# 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].remove(i) cols.append(X.pop(j)) return cols def deselect(X, Y, r, cols): for j in reversed(Y[r]): X[j] = cols.pop() for i in X[j]: for k in Y[i]: if k != j: X[k].add(i) def solve(X, Y, solution): if not X: yield list(solution) else: c = min(X, key=lambda c: len(X[c])) for r in list(X[c]): solution.append(r) cols = select(X, Y, r) for s in solve(X, Y, solution): yield s deselect(X, Y, r, cols) solution.pop()
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 0 e 20: ')) print('=-=' * 15) if -1 < n < 21: print(f'Numero {n}: {numeros[n]}') break print('Opção invalida!') print('=-=' * 15)
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.root.left is None: self.root.left = Node(data) else: binary_tree_obj = Node(data) binary_tree_obj.left = self.root.left self.root.left = binary_tree_obj def addRight(self, data): if self.root.right is None: self.root.right = Node(data) else: binary_tree_obj = Node(data) binary_tree_obj.right = self.root.right self.root.right = binary_tree_obj def getRightChild(self): return self.root.right def getLeftChild(self): return self.root.left def setRightChild(self, value): self.root.right = value def setLeftChild(self, value): self.root.left = value def setRootValue(self, value): self.root.data = value def getRootValue(self): return self.root.data def __repr__(self): return str(self.root.data) binary_tree = BinaryTree(10) binary_tree.addLeft(20) binary_tree.addLeft(34) binary_tree.addRight(4) binary_tree.addRight(50) print(binary_tree) # This prints only the node # Create Binary tree
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 :returns : True if the partition is valid according to our k-anonymity criteria, False otherwise. """ if len(partition) < k: # we cannot split this partition further... return False return True def partition_dataset(df, feature_columns, sensitive_column, scale, is_valid): """ :param df: The dataframe to be partitioned. :param feature_columns: A list of column names along which to partition the dataset. :param sensitive_column: The name of the sensitive column (to be passed on to the `is_valid` function) :param scale: The column spans as generated before. :param is_valid: A function that takes a dataframe and a partition and returns True if the partition is valid. :returns : A list of valid partitions that cover the entire dataframe. """ finished_partitions = [] partitions = [df.index] while partitions: partition = partitions.pop(0) spans = get_spans(df[feature_columns], partition, scale) for column, span in sorted(spans.items(), key=lambda x:-x[1]): #we try to split this partition along a given column lp, rp = split(df, partition, column) if not is_valid(df, lp, sensitive_column) or not is_valid(df, rp, sensitive_column): continue # the split is valid, we put the new partitions on the list and continue partitions.extend((lp, rp)) break else: # no split was possible, we add the partition to the finished partitions finished_partitions.append(partition) return finished_partitions
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 {'🐙🐙🐙': 'たこ'} class MyClass(metaclass=MyMeta): pass def test(): print(vars(MyClass)) if __name__ == '__main__': test()
# 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 com um for imprimindo um dicionário em cada linha # (usando o f-string) cadastroHBSIS = ['nome', ['Alex' ,'Paulo' ,'Pedro' ,'Mateus' ,'Carlos' ,'João' ,'Joaquim'], 'telefone',['4799991','4799992','4799993','4799994','4799995','4799996','4799997'], 'email', ['a@a.com','b@b.com','c@c.com','d@d.com','e@e.com','f@f.com','g@g.com'], 'idade', ['18' ,'25' ,'40' ,'16' ,'15' ,'19' ,'17' ] ] cab = cadastroHBSIS[0::2] dados = cadastroHBSIS[1::2] for nome in cab,dados: print(nome)
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, data): """ 插入一个数据项到二叉堆中 :param data: :return: """ # 完全二叉树中增加一个元素,即在队尾追加一个元素 self.heap_list.append(data) # 最大索引计数器(因为0被留空,所以最大索引即为列表长度) self.current_size += 1 # 上浮追加的元素,将其放在合适的位置上 self._perc_up(self.current_size) def _perc_up(self, i): """ 将小的节点向上升,直到其父节点值比之小结束 :param i: :return: """ while i // 2 > 0: if self.heap_list[i] < self.heap_list[i // 2]: self.heap_list[i], self.heap_list[i // 2] = self.heap_list[i // 2], self.heap_list[i] i //= 2 def find_min(self): """ 返回堆中最小项,最小项仍保留堆中(仅作查看,不删除) :return: """ # 堆顶元素即为最小元素,索引从1开始计 return self.heap_list[1] def del_min(self): """ 返回堆中的最小项,同时从堆中删除 :return: """ # 堆顶元素即为最小项,移走该节点后,原来的堆变成两个子堆,为了恢复堆结构 # 1、用最后一个节点来代替根节点,然后移走最后一个节点,此时堆成为了一个完整的完全二叉树,但其未必须仍然是一个堆(堆的有序性) # 2、为了保证新结构仍是一个堆,需要将新节点下沉(与上浮操作相反),以达到将最小节点移动到堆顶的目的 # 取出堆顶元素 data = self.heap_list[1] # 将最后一个节点值赋值给堆顶节点 self.heap_list[1] = self.heap_list[self.current_size] # 删除最后一个节点 # del self.heap_list[self.current_size] self.heap_list.pop() # 计数减一 self.current_size -= 1 # 执行下沉逻辑 self._perc_down(1) return data def _perc_down(self, i): while i * 2 <= self.current_size: # 查找小的子节点 mc = self._min_child(i) # 比较当前节点值与其较小子节点值,如果比之大,则交换 if self.heap_list[i] > self.heap_list[mc]: self.heap_list[i], self.heap_list[mc] = self.heap_list[mc], self.heap_list[i] # 循环交换,直到当前节点比之较小子节点小时停止 i = mc def _min_child(self, i): """ 返回较小子节点(直接左右子节点) :param i: :return: """ if i * 2 + 1 > self.current_size: # 没有右子节点,直接返回左子节点 return i * 2 else: # 否则有右子节点 if self.heap_list[i * 2] < self.heap_list[i * 2 + 1]: # 如果左子节点比右子节点小,返回左子节点 return i * 2 else: # 否则返回右子节点 return i * 2 + 1 def is_empty(self): """ 返回堆是否为空 :return: """ return self.current_size == 0 def size(self): """ 返回堆中数据项个数 :return: """ return self.current_size def build_heap(self, lst): """ 从一个列表构建一个新堆 :param lst: :return: """ if len(lst) == 0: return # 取列表中间一个元素,作为堆顶 i = len(lst) // 2 # 第0位将留空,所以最后一个节点的索引即为列表长度 self.current_size = len(lst) # 构建堆列表,前面拼接一个元素,值为0(任意) self.heap_list = [0] + lst # 对堆顶执行下沉操作(保证顺序) while i > 0: self._perc_down(i) i -= 1 heap = BinaryHeap() heap.insert(5) heap.insert(7) heap.insert(3) heap.insert(11) # 3 print(heap.find_min()) # 3 print(heap.del_min()) # 5 print(heap.del_min()) # 7 print(heap.del_min()) # 11 print(heap.del_min()) # True print(heap.is_empty()) heap.build_heap([4, 1, 7, 3, 9, 5, 2, 6, 8]) # 1 print(heap.find_min()) # 1 print(heap.del_min()) # 2 print(heap.del_min()) # 3 print(heap.del_min()) # False print(heap.is_empty()) # 6 print(heap.size())
"""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 MIT License Copyright (c) 2018. Victor I. Afolabi. All rights reserved. """ class DFS: # Goal node. goal = 'G' @staticmethod def recursive(graph, start, visited=None, toVisit=None): """Depth first search/traversal. Implemented using Stacks to keep track of visted nodes. Arguments: graph {dict} -- Graph elements. start {any} -- Start node. Keyword Arguments: visited {set} -- Keeping track of visited node. Stack data structure. (default: {None}) Returns: set -- Vistited nodes. """ # Visited set to keep track of visited node. visited = visited or [start] toVisit = toVisit or [start] vertex = toVisit.pop() if DFS.func(vertex): return True for child in graph[vertex]: if child not in visited: visited.append(child) toVisit.append(child) # Recursively visit child nodes. return DFS.recursive(graph, child, visited=visited, toVisit=toVisit) return False @staticmethod def iterative(graph, start): """Depth First Search/Traversal iterative implementation. Implementation using stack to keep track of visited nodes. Arguments: graph {dict} -- Graph elements. start {any} -- Start node. Returns: bool -- True if path is found, false otherwise. """ visited = [start] toVisit = [start] # Stack DS. while toVisit: # Take from the end of visited. vertex = toVisit.pop() if DFS.func(vertex): return True for child in graph[vertex]: if child not in visited: visited.append(child) toVisit.append(child) return False @staticmethod def func(vertex): print(vertex, end=' ') if vertex == DFS.goal: print('\nFound "{}"!'.format(DFS.goal)) return True return False if __name__ == '__main__': """ GRAPH ––––– A ----- B | | | | C ----- D --- E """ graph1 = { "A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D"], "D": ["E"], "E": ["D"], } # Set the Goal to 'E'. DFS.goal = 'E' # Depth first traversal. print('Recursive solution:') DFS.recursive(graph1, 'A') print('\n') print('Iterative Solution:') DFS.iterative(graph1, 'A') print('\n') """ GRAPH –––––– C --------- E | A / | G / | / S --B -- D --/ """ graph2 = { 'S': ['A', 'B'], 'A': ['S', 'B', 'C'], 'B': ['S', 'A', 'D'], 'C': ['A', 'E'], 'D': ['B', 'G'], 'E': ['C'], 'G': ['D'], } # Set the Goal to 'G' DFS.goal = 'G' # Depth first traversal. print('Recursive solution:') DFS.recursive(graph2, 'S') print('\n') print('Iterative Solution:') DFS.iterative(graph2, 'S') print('\n')
_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 -= 1 qy = int(input()) if qy in marble_numbers: print(f"{qy} found at {marble_numbers.index(qy) + 1}") else: print(f"{qy} not found")
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 def get_board(self): return self.__board def make_printable(self): c_gap = ' ----------- ' r_gap = ' | ' self.__print_board = c_gap + '\n' for l_board in self.__board: self.__print_board += r_gap for d in l_board: self.__print_board += d self.__print_board += r_gap self.__print_board += '\n' + c_gap + '\n' def is_space_available(self, pos: str): row1 = self.__board[0] row2 = self.__board[1] row3 = self.__board[2] if not pos.isdigit(): return False r1 = range(1, 4).count(int(pos)) and row1[int(pos) - 1] == str(pos) r2 = range(4, 7).count(int(pos)) and row2[int(pos) - 4] == str(pos) r3 = range(7, 10).count(int(pos)) and row3[int(pos) - 7] == str(pos) return r1 or r2 or r3 def is_full(self): board = self.__board for row in board: for elem in row: if elem.isdigit(): return False return True def place(self, marker: str, pos: str): if not (int(pos) >= 1 and int(pos) <= 9): return False for row in self.__board: if pos in row: row[row.index(pos)] = marker return True return False
#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_KEYS = \ [ 'Step1: 样本自动标记', 'Step2: 样本重标记', 'Step3: 训练', 'Step4: UI自动化探索结果' ] CHILD_ITEM_KEYS = \ [ ['路径', '开始自动标记'], ['路径', '样本修改', '开始重标记', '打包样本'], ['路径', '参数设置', '开始训练', '结果分析'], ['路径', '图分析', '覆盖率分析', "UI详细覆盖分析"] ] PATH_NAME_LIST = ['路径', 'path'] UI_USR_LABEL_NAME = 'Step2: 样本重标记' USR_LABEL_ITEM_NAME = '开始重标记' TRAIN_LOG_DIR = './data/log.txt' AUTO_LABEL = 0 USR_LABEL = 1 TRAIN = 2 EXPLORE_RESULT = 3 TRAIN_PARAMS = \ { "微调次数": 5 } int_Number_Key = \ { "微调次数" }
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.yaml' HEURISTIC_FILE_PREFIX = 'heuristic_face_recognizer' LIB_FACE_RECOGNITION_FILE_PREFIX = 'lib_face_recognition' ALLOWED_METHODS = ['lbph_machinelearning', 'heuristic', 'lib_face_recognition'] HEURISTIC_CERTAIN = .15
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 preco > 1000: totmais += 1 resp = ' ' while resp not in 'SN': resp = str(input('Quer Continuar [S/N]: ')).upper().strip()[0] print('-' * 40) if resp == 'N': break print(f'{"Fim do Programa":-^40}') print(f'O total de compra foi R${soma:.2f}') print(f'Temos {totmais} produtos que custam mais de R$1000.00') print(f'O produto mais barato foi a/o {prodmenor} que custa R${menor:.2f}')
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 mismo nombre. def miFuncion2(): var2 = 2 print("¿Conozco a la variable?", var2) var2 = 1 miFuncion2() print(var2) #La palabra reservada llamada "global" puede extender el alcance de una variable #incluyendo el cuerpo de las funciones para poder no solo leer los valores de las variables #sino también modificarlos. def miFuncion3(): global var3 var3 = 2 print("¿Conozco a aquella variable?", var3) var3 = 1 miFuncion3() print(var3) #Al cambiar el valor del parámetro este no se propaga fuera de la función #Esto también significa que una función recibe el valor del argumento, #no el argumento en sí. def miFuncion4(n): print("Yo obtuve", n) n += 1 print("Yo ahora tengo", n) varn = 1 miFuncion4(varn) print(varn) def miFuncionl(miLista1): print(miLista1) miLista1 = [0, 1] miLista2 = [2, 3] miFuncionl(miLista2) print(miLista2) def miFuncionl2(miLista1): print(miLista1) del miLista1[0] miLista2 = [2, 3] miFuncionl2(miLista2) print(miLista2)
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] return dp[m-1][n-1]
# ................................................................................................................. level_dict["bombs"] = { "scheme": "red_scheme", "size": (9,9,9), "intro": "bombs", "help": ( "$scale(1.5)mission:\nget to the exit!\n\n" + \ "to get to the exit,\nuse the bombs", ), "player": { "position": (0,-4,0), }, "exits": [ { "name": "exit", "active": 1, "position": (0,2,0), }, ], "create": """ world.addObjectAtPos (KikiBomb(), world.decenter (0,-4,2)) world.addObjectAtPos (KikiBomb(), world.decenter (0,-4,-2)) world.addObjectAtPos (KikiBomb(), world.decenter (-3,-2,0)) """, }
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. """ raise NotImplementedError def score(self, **kwargs): """ Used for teacher-forcing training, return the log_probability of <input,output>. """ raise NotImplementedError
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 from user. ''' instruction_PTR = 0 memory_PTR = memory_size // 2 memory = [0] * memory_size Output = "" while instruction_PTR < len(bf_code): ch = bf_code[instruction_PTR] if ch == '>': memory_PTR = (memory_PTR + 1) % memory_size; elif ch == '<': memory_PTR = (memory_PTR - 1) % memory_size; elif ch == '+': memory[memory_PTR] = memory[memory_PTR] + 1; elif ch == '-': memory[memory_PTR] = memory[memory_PTR] - 1; elif ch == '.': # chr(int) -> char converts int to a char with corresponding ASCII code out_ch = chr( memory[memory_PTR] ) Output = Output + out_ch elif ch == ',': # ord(char) -> int converts char to its corresponding ASCII code in_ch = input("Input 1 byte in form of a single character: ") memory[memory_PTR] = ord(in_ch[0]) elif ch == '[': if memory[memory_PTR] == 0: loops = 1 while loops > 0: instruction_PTR +=1 if bf_code[instruction_PTR] == '[': loops += 1 elif bf_code[instruction_PTR] == ']': loops -= 1 elif ch == ']': loops = 1 while loops > 0: instruction_PTR -=1 if bf_code[instruction_PTR] == '[': loops -= 1 elif bf_code[instruction_PTR] == ']': loops += 1 instruction_PTR -= 1 instruction_PTR +=1 print(Output) return Output #if len(sys.argv) >= 2: # bf_code = sys.argv[1] # interpret_bf_code(bf_code) if __name__ == "__main__": bf_test_code = input("Type in BrainFuck code: ") interpret_bf_code(bf_test_code)
# 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. def traverse_list(A): result = [] def traverse_list_rec(A, i, j): if i >= len(A) or j >= len(A[i]): return traverse_list_rec(A, i + 1, j) traverse_list_rec(A, i, j + 1) result.append(A[i][j]) traverse_list_rec(A, 0, 0) return result print(traverse_list(A)) # recursively traverse 2 dimensional list in order. def flatten(A): result = [] def flatten_recursive(A, i, j, result): if i == len(A): return if j == len(A[i]): flatten_recursive(A, i + 1, 0, result) return result.append(A[i][j]) flatten_recursive(A, i, j + 1, result) flatten_recursive(A, 0, 0, result) return result print(flatten(A))
# 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 motor speeds left and right. # A Pololu Maestro is used to send PWM signals to left and right motor controllers. # When using motor controllers, the maestro's speed setting can be used to tune the # responsiveness of the robot. Low values dampen acceleration, making for a more # stable robot. High values increase responsiveness, but can lead to a tippy robot. # Try values around 50 to 100. RESPONSIVENESS = 60 # this is also considered "speed" # These are the motor controller limits, measured in Maestro units. # These default values typically work fine and align with maestro's default limits. # Vaules should be adjusted so that center stops the motors and the min/max values # limit speed range you want for your robot. MIN = 4000 CENTER = 6000 MAX = 8000 class SimpleServo: # Pass the maestro controller object and the maestro channel numbers being used # for the left and right motor controllers. See maestro.py on how to instantiate maestro. def __init__(self, maestro, channel): self.maestro = maestro self.channel = channel # Init motor accel/speed params self.maestro.setAccel(self.channel, 0) self.maestro.setSpeed(self.channel, RESPONSIVENESS) # Motor min/center/max values self.min = MIN self.center = CENTER self.max = MAX # speed is -1.0 to 1.0 def drive(self, amount): # convert to servo units if (amount >= 0): target = int(self.center + (self.max - self.center) * amount) else: target = int(self.center + (self.center - self.min) * amount) self.maestro.setTarget(self.channel, target) # Set both motors to stopped (center) position def stop(self): self.maestro.setAccel(self.channel, self.center) # Close should be used when shutting down Drive object def close(self): self.stop()
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 plotgen.py. The list variables sortPlots, plotNames and lines are sorted identically in order to relate the individual variables. """ #------------------------------------------------------------------------------- # C O N S T A N T S #------------------------------------------------------------------------------- DAY = 24 HOUR = 3600 KG = 1000. g_per_second_to_kg_per_day = 1. / (DAY * HOUR * KG) kg_per_second_to_kg_per_day = 1. / (DAY * HOUR) #------------------------------------------------------------------------------- # P L O T S #------------------------------------------------------------------------------- # Names of the variables sortPlots = ['theta_l', 'r_t', 'theta_l_flux', 'r_t_flux', 'cloudliq_frac', 'r_c', 'w_var', 'w3', 'theta_l_var', 'r_t_var', 'covar_thetal_rt', 'wobs', 'U', 'V', 'covar_uw', 'covar_vw', 'u_var', 'v_var',\ 'QR', 'QR_IP', 'QRP2', 'QRP2_QRIP', \ 'Nrm', 'Nrm_IP', 'Nrp2', 'Nrp2_NrmIP', \ 'Ncm', 'Ncm_IP', 'Ncp2', 'Ncp2_NcmIP', \ 'Ngm', 'Ngm_IP', 'Ngp2', 'Ngp2_NgmIP', \ 'Qgm', 'Qgm_IP', 'Qgp2', 'Qgp2_QgmIP', \ 'Qim', 'Qim_IP', 'Qip2', 'Qip2_QimIP', \ 'Nim', 'Nim_IP', 'Nip2', 'Nip2_NimIP', \ 'Qsm', 'Qsm_IP', 'Qsp2', 'Qsp2_QsmIP', \ 'Nsm', 'Nsm_IP', 'Nsp2', 'Nsp2_NsmIP', \ 'MicroFractions', 'Buoy_Flux', \ 'uprcp', 'uprtp', 'upthlp', \ 'vprcp', 'vprtp', 'vpthlp', \ ] # settings of each plot: # plot number, plot title, axis label plotNames = [\ ['Liquid Water Potential Temperature, theta_l', 'thetal [K]'],\ ['Total Water Mixing Ratio, r_t', 'rtm / qt [kg/kg]'],\ ['Turbulent Flux of theta_l', 'wpthlp / thflux(s) [K m/s]'],\ ['Turbulent Flux of r_t', 'wprtp / qtflux(s) [(kg/kg) m/s]'],\ ['Cloud Liquid Fraction', ' [%/100]'],\ ['Cloud Water Mixing Ratio, r_c', 'rcm / qcl [kg/kg]'],\ ['Variance of w', 'wp2 / w2 [m^2/s^2]'],\ ['Third-order Moment of w', 'wp3 / w3 [m^3/s^3]'],\ ['Variance of theta_l', 'thlp2 / tl2 [K^2]'],\ ['Variance of r_t', 'rtp2 / qtp2 [(kg/kg)^2]'],\ ['Covariance of r_t & theta_l', 'rtpthlp [(kg/kg) K]'],\ ['Vertical Wind Component, w (subsidence)', 'wobs [m/s]'],\ ['Zonal Wind Component, u', 'um / u [m/s]'],\ ['Meridonal Wind Component, v', 'vm / v [m/s]'],\ ['Covariance of u & w', 'upwp / uw [m^2/s^2]'],\ ['Covariance of v & w', 'vpwp / vw [m^2/s^2]'],\ ['Variance of u wind', 'up2 / u2 [m^2/s^2]'],\ ['Variance of v wind', 'vp2 / v2 [m^2/s^2]'],\ # Rain Water Mixing Ratio ['Rain Water Mixing Ratio', 'qrm [kg/kg]'],\ ['Rain Water Mixing Ratio in Rain', 'qrm_ip [kg/kg]'],\ ['Domain-wide Variance\nof Rain Water Mixing Ratio', 'qrp2 [(kg/kg)^2]'],\ ['Within-rain Variance\nof Rain Water Mixing Ratio', 'qrp2_ip / qrm_ip^2 [-]'],\ #Rain Drop Number Concentration ['Rain Drop Concentration', 'Nrm [num/kg]'],\ ['Rain Drop Concentration in Rain', 'Nrm_ip [num/kg]'],\ ['Domain-wide Variance\nof Rain Drop Concentration', 'Nrp2 [(num/kg)^2]'],\ ['Within-rain Variance\nof Rain Drop Concentration', 'Nrp2_ip / Nrm_ip^2 [-]'],\ #Cloud Droplet Number Concentration ['Cloud Droplet Number Concentration', 'Ncm [num/kg]'],\ ['Cloud Droplet Number Concentration in Cloud', 'Ncm_ip [num/kg]'],\ ['Domain-wide Variance\nof Cloud Droplet Number Concentration', 'Ncp2 [(#/kg)^2]'],\ ['Within-cloud Variance\nof Cloud Droplet Number Concentration', 'Ncp2_ip / Ncm_ip^2 [-]'],\ #Graupel Number Concentration ['Graupel Number Concentration', 'Ngm [kg/kg]'],\ ['Graupel Number Concentration in Graupel', 'Ngm_ip [num/kg]'],\ ['Domain-wide Variance\nof Graupel Number Concentration', 'Ngp2 [(kg/kg)^2]'],\ ['Within-graupel Variance\nof Graupel Number Concentration', 'Ngp2_ip / Ngm_ip^2 [-]'],\ #Graupel Mixing Ratio ['Graupel Mixing Ratio', 'qgm [kg/kg]'],\ ['Graupel Mixing Ratio in Graupel', 'qgm_ip [kg/kg]'],\ ['Domain-wide Variance\nof Graupel Mixing Ratio', 'qgp2 [(kg/kg)^2]'],\ ['Within-graupel Variance\nof Graupel Mixing Ratio', 'qgp2_ip / qgm_ip^2 [-]'],\ #Cloud Ice Mixing Ratio ['Cloud Ice Mixing Ratio', 'qim [kg/kg]'],\ ['Cloud Ice Mixing Ratio in Cloud Ice', 'qim_ip [kg/kg]'],\ ['Domain-wide Variance\nof Cloud Ice Mixing Ratio', 'qip2 [(kg/kg)^2]'],\ ['Within-cloud-ice Variance\nof Cloud Ice Mixing Ratio', 'qip2_ip / qim_ip^2 [-]'],\ #Cloud Ice Number Concentration ['Cloud Ice Concentration', 'Nim [num/kg]'],\ ['Cloud Ice Number Concentration in Cloud Ice', 'Ni_ip [num/kg]'],\ ['Domain-wide Variance\nof Cloud Ice Number Concentration', 'Nip2 [(num/kg)^2]'],\ ['Within-cloud-ice Variance\nof Cloud Ice Number Concentration', 'Nip2_ip / Nim_ip^2 [-]'],\ #Snow Mixing Ratio ['Snow Mixing Ratio ', 'qsm [kg/kg]'],\ ['Snow Mixing Ratio in Snow', 'qsm_ip [kg/kg]'],\ ['Domain-wide Variance\nof Snow Mixing Ratio', 'qsp2 [(kg/kg)^2]'],\ ['Within-snow Variance\nof Snow Mixing Ratio ', 'qsp2_ip / qsm_ip^2 [-]'],\ #Snow Number Concentration ['Snow Number Concentration', 'Nsm [num/kg]'],\ ['Snow Number Concentration in Snow', 'Nsm_ip [num/kg]'],\ ['Domain-wide Variance\nof Snow Number Concentration', 'Nsp2 [(#/kg)^2]'],\ ['Within-snow Variance\nof Snow Number Concentration', 'Nsp2_ip / Nsm_ip^2 [-]'],\ ['Micro Fractions', '[%/100]'],\ ['Buoyancy flux', 'wpthvp / tlflux [K m/s]'],\ #['Liquid Water Path', 'lwp [kg/m^2]'],\ #['Surface rainfall rate', 'rain_rate_sfc[mm/day]'],\ #['Density-Weighted Vertically Averaged wp2', 'wp2 / w2 [m^2/s^2]'],\ #['Cloud Ice Water Path', 'iwp [kg/m^2]'],\ #['Snow Water Path', 'swp [kg/m^2]'],\ # buoyancy sub-terms for parameterization in upwp budget ['Covariance of u & rc', 'uprcp / urc [m^2/s^2]'],\ ['Covariance of u & rt', 'uprtp / urt [m^2/s^2]'],\ ['Covariance of u & thl', 'upthlp / uthl [m^2/s^2]'],\ # buoyancy sub-terms for parameterization in upwp budget ['Covariance of v & rc', 'vprcp / urc [m^2/s^2]'],\ ['Covariance of v & rt', 'vprtp / urt [m^2/s^2]'],\ ['Covariance of v & thl', 'vpthlp / uthl [m^2/s^2]'],\ ] # lines of each plot: # variable name within python, shall this variable be plotted?, variable name in SAM output, conversion thetal = [\ # variables of thetal ['THETAL', False, 'THETAL', 1., 0],\ ['THETA', False, 'THETA', 1., 0],\ ['TABS', False, 'TABS', 1., 0],\ ['QI', False, 'QI', 1./KG, 0],\ ['THETAL', True, 'THETAL + 2500.4 * (THETA/TABS) * QI', 1., 0],\ ] rt = [\ # variables of rt ['QI', False, 'QI', 1., 0],\ ['QT', False, 'QT', 1., 0],\ ['RT', True, '(QT-QI)', 1./KG, 0],\ ] thetalflux = [\ # variables of thetalflux ['TLFLUX', False, 'TLFLUX', 1., 0],\ ['RHO', False, 'RHO', 1., 0],\ ['WPTHLP_SGS', False, 'WPTHLP_SGS', 1., 0],\ ['THETALFLUX', True, '((TLFLUX) / (RHO * 1004.)) + WPTHLP_SGS', 1., 0],\ ] rtflux = [\ # variables of rtflux ['QTFLUX', False, 'TLFLUX', 1., 0],\ ['RHO', False, 'RHO', 1., 0],\ ['WPRTP_SGS', False, 'WPRTP_SGS', 1., 0],\ ['RTFLUX', True, '(QTFLUX / (RHO * 2.5104e+6)) + WPRTP_SGS', 1., 0],\ ] cloudliqfrac = [\ # variables of cloudliqfrac ['cloudliq_frac_em6', True, 'cloudliq_frac_em6', 1., 0],\ ] qcl = [\ # variables of qcl ['QCL', True, 'QCL', 1./KG, 0],\ ] wVar = [\ # variables of wVar ['WP2_SGS', False, 'WP2_SGS', 1., 0],\ ['W2', False, 'W2', 1., 0],\ ['WVAR', True, 'WP2_SGS + W2', 1., 0],\ ] w3 = [\ # variables of wVar ['WP3_SGS', False, 'WP3_SGS', 1., 0],\ ['W3', False, 'W3', 1., 0],\ ['W3', True, 'WP3_SGS + W3', 1., 0],\ ] thetalVar = [\ # variables of thetalVar ['THLP2_SGS', False, 'THLP2_SGS', 1., 0],\ ['TL2', False, 'TL2', 1., 0],\ ['THETALVAR', True, 'THLP2_SGS + TL2', 1., 0],\ ] rtVar = [\ # variables of rtVar ['RTP2_SGS', False, 'RTP2_SGS', 1., 0],\ ['QT2', False, 'QT2', 1., 0],\ ['RTVAR', True, '(QT2 / 1e+6) + RTP2_SGS', 1., 0],\ ] covarThetalRt = [\ # variables of covarThetalRt ['CovarThetaLRT', True, 'RTPTHLP_SGS', 1., 0],\ ] wobs = [\ # variables of wobs ['WOBS', True, 'WOBS', 1., 0],\ ] U = [\ # variables of U ['U', True, 'U', 1., 0],\ ] V = [\ # variables of V ['V', True, 'V', 1., 0],\ ] covarUW = [\ # variables of covarUV ['UPWP_SGS', False, 'UPWP_SGS', 1., 0],\ ['UW', False, 'UW', 1., 0],\ ['UW', True, 'UW + UPWP_SGS', 1., 0],\ ] covarVW = [\ # variables of covarVW ['VPWP_SGS', False, 'VPWP_SGS', 1., 0],\ ['VW', False, 'VW', 1., 0],\ ['VW', True, 'VW + VPWP_SGS', 1., 0],\ ] uVar = [\ # variables of uVar ['UP2_SGS', False, 'UP2_SGS', 1., 0],\ ['U2', False, 'U2', 1., 0],\ ['UVAR', True, 'UP2_SGS + U2', 1., 0],\ ] vVar = [\ # variables of vVar ['VP2_SGS', False, 'VP2_SGS', 1., 0],\ ['V2', False, 'V2', 1., 0],\ ['VVAR', True, 'VP2_SGS + V2', 1., 0],\ ] # Rain Water Mixing Ratio QR = [\ # variables of QR ['QR', True, 'QR', 1./KG, 0],\ ] QRIP = [\ # variables of QRIP ['qrainm_ip', True, 'qrainm_ip', 1., 0],\ ] QRP2 = [\ # variables of QRP2 ['qrainp2', True, 'qrainp2', 1., 0],\ ] QRP2_QRIP = [\ # variables of QRP2_QRIP ['qrainp2_ip', False, 'qrainp2_ip', 1., 0],\ ['qrainm_ip', False, 'qrainm_ip', 1., 0],\ ['QRP2_QRIP', True, '(qrainp2_ip / (np.maximum(np.full(n,1e-5),qrainm_ip)**2))', 1., 0],\ ] #Rain Drop Number Concentration Nrm = [\ # variables of Nrm ['NR', False, 'NR', 1., 0],\ ['RHO', False, 'RHO', 1., 0],\ ['NRM', True, '(NR * 1e+6) / RHO', 1., 0],\ ] Nrm_IP = [\ # variables of Nrm_IP ['nrainm_ip', True, 'nrainm_ip', 1., 0],\ ] Nrp2 = [\ # variables of Nrp2 ['nrainp2', True, 'nrainp2', 1., 0],\ ] Nrp2_NrmIP = [\ # variables of Nrp2_NrmIP ['nrainp2_ip', False, 'nrainp2_ip', 1., 0],\ ['nrainm_ip', False, 'nrainm_ip', 1., 0],\ ['Nrp2_NrmIP', True, '(nrainp2_ip / (np.maximum(np.full(n,1e-5),nrainm_ip)**2))', 1., 0],\ ] #Cloud Droplet Number Concentration Ncm = [\ # variables of Ncm ['NC', False, 'NC', 1., 0],\ ['RHO', False, 'RHO', 1., 0],\ ['NCM', True, '(NC * 1e+6) / RHO', 1., 0],\ ] Ncm_IP = [\ # variables of Ncm_IP ['ncloudliqm_ip', True, 'ncloudliqm_ip', 1., 0],\ ] Ncp2 = [\ # variables of Ncp2 ['Ncp2', True, 'Ncp2', 1., 0],\ ] Ncp2_NcmIP = [\ # variables of Ncp2_NcmIP ['ncloudliqp2_ip', False, 'ncloudliqp2_ip', 1., 0],\ ['ncloudliqm_ip', False, 'ncloudliqm_ip', 1., 0],\ ['Ncp2_NcmIP', True, '(ncloudliqp2_ip / (np.maximum(np.full(n,1e-5),ncloudliqm_ip)**2))', 1., 0],\ ] #Graupel Number Concentration Ngm = [\ # variables of Ngm ['NG', False, 'NG', 1., 0],\ ['RHO', False, 'RHO', 1., 0],\ ['NGM', True, '(NG * 1e+6) / RHO', 1., 0],\ ] Ngm_IP = [\ # variables of Ngm_IP ['ngraupelm_ip', True, 'ngraupelm_ip', 1., 0],\ ] Ngp2 = [\ # variables of Ngp2 ['ngraupelp2', True, 'ngraupelp2', 1., 0],\ ] Ngp2_NgmIP = [\ # variables of Ngp2_NgmIP ['ngraupelp2_ip', False, 'ngraupelp2_ip', 1., 0],\ ['ngraupelm_ip', False, 'ngraupelm_ip', 1., 0],\ ['Ngp2_NgmIP', True, '(ngraupelp2_ip / (np.maximum(np.full(n,1e-5),ngraupelm_ip)**2))', 1., 0],\ ] #Graupel Mixing Ratio Qgm = [\ # variables of Qgm ['QG', True, 'QG', 1./KG, 0],\ ] Qgm_IP = [\ # variables of Qgm_IP ['qgraupelm_ip', True, 'qgraupelm_ip', 1., 0],\ ] Qgp2 = [\ # variables of Qgp2 ['qgraupelp2', True, 'qgraupelp2', 1., 0],\ ] Qgp2_QgmIP = [\ # variables of Qgp2_QgmIP ['qgraupelp2_ip', False, 'qgraupelp2_ip', 1., 0],\ ['qgraupelm_ip', False, 'qgraupelm_ip', 1., 0],\ ['Qgp2_QgmIP', True, '(qgraupelp2_ip / (np.maximum(np.full(n,1e-5),qgraupelm_ip)**2))', 1., 0],\ ] #Cloud Ice Mixing Ratio # Note: redundant, could not find variable in sam Qim = [\ # variables of Qim ['QG', True, 'QG', 1./KG, 0],\ ] Qim_IP = [\ # variables of Qim_IP ['qcloudicem_ip', True, 'qcloudicem_ip', 1., 0],\ ] Qip2 = [\ # variables of Qip2 ['qcloudicep2', True, 'qcloudicep2', 1., 0],\ ] Qip2_QimIP = [\ # variables of Qip2_QimIP ['qcloudicep2_ip', False, 'qcloudicep2_ip', 1., 0],\ ['qcloudicem_ip', False, 'qcloudicem_ip', 1., 0],\ ['Qip2_QimIP', True, '(qcloudicep2_ip / (np.maximum(np.full(n,1e-5),qcloudicem_ip)**2))', 1., 0],\ ] #Cloud Ice Number Concentration Nim = [\ # variables of Nim ['NI', False, 'NI', 1., 0],\ ['RHO', False, 'RHO', 1., 0],\ ['NIM', True, '(NI * 1e+6) / RHO', 1., 0],\ ] Nim_IP = [\ # variables of Nim_IP ['ncloudicem_ip', True, 'ncloudicem_ip', 1., 0],\ ] Nip2 = [\ # variables of Nip2 ['ncloudicep2', True, 'ncloudicep2', 1., 0],\ ] Nip2_NimIP = [\ # variables of Nip2_NimIP ['ncloudicep2_ip', False, 'ncloudicep2_ip', 1., 0],\ ['ncloudicem_ip', False, 'ncloudicem_ip', 1., 0],\ ['Nip2_NimIP', True, '(ncloudicep2_ip / (np.maximum(np.full(n,1e-5),ncloudicem_ip)**2))', 1., 0],\ ] #Snow Mixing Ratio Qsm = [\ # variables of Qsm ['QSM', True, 'QS', 1./KG, 0],\ ] Qsm_IP = [\ # variables of Qsm_IP ['qsnowm_ip', True, 'qsnowm_ip', 1., 0],\ ] Qsp2 = [\ # variables of Qsp2 ['qsnowp2', True, 'qsnowp2', 1., 0],\ ] Qsp2_QsmIP = [\ # variables of Qsp2_QsmIP ['qsnowp2_ip', False, 'qsnowp2_ip', 1., 0],\ ['qsnowm', False, 'qsnowm', 1., 0],\ ['Qsp2_QsmIP', True, '(qsnowp2_ip / (np.maximum(np.full(n,1e-5),qsnowm)**2))', 1., 0],\ ] #Snow Number Concentration Nsm = [\ # variables of Nsm ['NS', False, 'NS', 1., 0],\ ['RHO', False, 'RHO', 1., 0],\ ['NSM', True, '(NS * 1e+6) / RHO', 1., 0],\ ] Nsm_IP = [\ # variables of Nsm_IP ['nsnowm_ip', True, 'nsnowm_ip', 1., 0],\ ] Nsp2 = [\ # variables of Nsp2 ['nsnowp2', True, 'nsnowp2', 1., 0],\ ] Nsp2_NsmIP = [\ # variables of Nsp2_NsmIP ['nsnowp2_ip', False, 'nsnowp2_ip', 1., 0],\ ['nsnowm_ip', False, 'nsnowm_ip', 1., 0],\ ['Nsp2_NsmIP', True, '(nsnowp2_ip / (np.maximum(np.full(n,1e-5),nsnowm_ip)**2))', 1., 0],\ ] MicroFractions = [\ # variables of MicroFractions ['Cloud_liq', True, 'cloudliq_frac_em6', 1., 0],\ ['Rain', True, 'rain_frac_em6', 1., 0],\ ['Cloud_ice', True, 'cloudice_frac_em6', 1., 0],\ ['Snow', True, 'snow_frac_em6', 1., 0],\ ['Graupel', True, 'graupel_frac_em6', 1., 0],\ ] Buoy_Flux = [\ # variables of Buoy_Flux ['TVFLUX', False, 'TVFLUX', 1., 0],\ ['RHO', False, 'RHO', 1., 0],\ ['Buoy_Flux', True, 'TVFLUX / (RHO * 1004)', 1., 0],\ ] lwp = [\ # variables of lwp ['CWP', True, 'CWP', 1./KG, 0],\ ] PREC = [\ # variables of lwp ['PREC', True, 'PREC', 1., 0],\ ] WP2_W2 = [\ # variables of WP2_W2 ['NS', True, 'NS', 0., 0],\ ] IWP = [\ # variables of IWP ['IWP', True, 'IWP', 1./KG, 0],\ ] SWP = [\ # variables of SWP ['SWP', True, 'SWP', 1./KG, 0],\ ] uprcp = [\ ['UPRCP', True, 'UPRCP', 1., 0],\ ] uprtp = [\ ['UPRTP', True, 'UPRTP', 1., 0],\ ] upthlp = [\ ['UPTHLP', True, 'UPTHLP', 1., 0],\ ] vprcp = [\ ['VPRCP', True, 'VPRCP', 1., 0],\ ] vprtp = [\ ['VPRTP', True, 'VPRTP', 1., 0],\ ] vpthlp = [\ ['VPTHLP', True, 'VPTHLP', 1., 0],\ ] lines = [thetal, rt, thetalflux, rtflux, cloudliqfrac, qcl, wVar, w3, thetalVar, rtVar, covarThetalRt, wobs, U, V, covarUW, covarVW, uVar, vVar,\ QR, QRIP, QRP2, QRP2_QRIP, \ Nrm, Nrm_IP, Nrp2, Nrp2_NrmIP, \ Ncm, Ncm_IP, Ncp2, Ncp2_NcmIP, \ Ngm, Ngm_IP, Ngp2, Ngp2_NgmIP, \ Qgm, Qgm_IP, Qgp2, Qgp2_QgmIP, \ Qim, Qim_IP, Qip2, Qip2_QimIP, \ Nim, Nim_IP, Nip2, Nip2_NimIP, \ Qsm, Qsm_IP, Qsp2, Qsp2_QsmIP, \ Nsm, Nsm_IP, Nsp2, Nsp2_NsmIP, \ MicroFractions, Buoy_Flux, \ uprcp, uprtp, upthlp, \ vprcp, vprtp, vpthlp, \ ]
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)): for t in range(length+1, len(data)): if sum[t] - sum[t-length-1] >= n: print(length+1) found = True # print(data[t], data[t-length]) break if found: break if not found: print("-1")
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 skip(self): return self.report['skip']
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. defaults)') print(' 4. Exit configuration') selection = input(f"{'/'.join(input_map)}> ") if selection not in input_map: raise Exception("Invalid selection") return input_map[selection] def main_service_menu(service): input_map = {'1': 'add', '2': 'remove'} print('\nDo you want to:') print(f' 1. Set up a new {service} service') print(f' 2. Remove a {service} service') selection = input(f"{'/'.join(input_map)}> ") if selection not in input_map: raise Exception("Invalid selection") return input_map[selection] def default_service_menu(): input_map = {'1': 'compute', '2': 'storage'} print('\nDo you want to:') print(f' 1. Change default compute service') print(f' 2. Change default storage service') selection = input(f"{'/'.join(input_map)}> ") if selection not in input_map: raise Exception("Invalid selection") return input_map[selection]
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 def __str__(self): if self.top == None: return 'Stack is empty' else: output = '' while self.top != None: output += str(self.top) + '\n' self.top = self.top.next return output def push(self, value): if not self.top: self.top = Node(value) else: node = Node(value) node.next = self.top self.top = node def pop(self): if self.top == None: return None else: output = self.top self.top = self.top.next return output def peek(self): if self.top == None: return None else: return self.top.value def isEmpty(self): return self.top == None class Queue: def __init__(self , node=None): self.front= node self.rear = node def __str__(self): if self.front == None: return 'Queue is empty' else: output = '' while self.front != None: output += str(self.front) + '\n' self.front = self.front.next return output def enqueue(self, value): node = Node(value) if self.rear == None: self.rear = node self.front = node else: self.rear.next = node self.rear = node def dequeue(self): if self.front == None: return None else: output = self.front self.front = self.front.next return output def isEmpty(self): return self.front == None def peek(self): if self.front == None: return None else: return self.front.value class TNode: def __init__(self, value=None): self.value = value self.left = None self.right = None def __str__(self): return str(self.value) class BinaryTree: def __init__(self): self.root = None def pre_order(self): """"traverse tree recursively""" def traverse(root): # print the root node print(root.value) # traverse left & right subtree if root.left is not None: traverse(root.left) if root.right is not None: traverse(root.right) traverse(self.root) def in_order(self): """"traverse tree recursively""" def traverse(root): # print the root node # traverse left & right subtree if root.left is not None: traverse(root.left) print(root.value) if root.right is not None: traverse(root.right) traverse(self.root) def post_order(self): """"traverse tree recursively""" def traverse(root): # print the root node # traverse left & right subtree if root.left is not None: traverse(root.left) if root.right is not None: traverse(root.right) print(root.value) traverse(self.root) def pre_order_iterative(self): """traverse tree iteratively""" stack = Stack() stack.push(self.root) while not stack.isEmpty(): node = stack.pop() print(node.value) if node.value.right: stack.push(node.value.right) if node.value.left: stack.push(node.value.left) def breadth_First(self): """traverse tree breadth first""" queue = Queue() queue.enqueue(self.root) while not queue.isEmpty(): node = queue.dequeue() print(node.value) if node.left is not None: queue.enqueue(node.left) if node.right is not None: queue.enqueue(node.right) class BinarySearchTree(BinaryTree): def add(self, value): """Adds a value to the BST""" if self.root is None: self.root = TNode(value) else: current = self.root while current: if value < current.value: if current.left is None: current.left = TNode(value) return current = current.left else: if current.right is None: current.right = TNode(value) return current = current.right def contains(self, value): """Returns True if value is in the BST, False otherwise""" current = self.root while current: if current.value == value: return True if current.value > value: current = current.left else: current = current.right return False if __name__ == "__main__": # tree = BinaryTree() # tree.root = TNode("a") # tree.root.left = TNode("b") # tree.root.right = TNode("c") # tree.root.right.left = TNode("d") # tree.pre_order_iterative() # tree.pre_order() # tree.in_order() # tree.post_order() tree = BinarySearchTree() tree.add(20) tree.add(15) tree.add(10) tree.add(16) tree.add(30) tree.add(25) tree.add(35) print("pre_order") tree.pre_order() print("in_order") tree.in_order() print("post_order") tree.post_order() print("If tree contains value= 20 =>" ,tree.contains(20)) print("If tree contains value= 45 =>",tree.contains(45))
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: TreeNode) -> int: self.result = 0 self.dfs(root) return self.result def dfs(self, root): if root == None: return 0, 0 if root.left == None and root.right == None: return 0, 0 rootL, rootR = 0, 0 if root.left == None: rootL = 0 else: l, r = self.dfs(root.left) rootL = r + 1 if root.right == None: rootR = 0 else: l, r = self.dfs(root.right) rootR = l + 1 self.result = max(self.result, rootL, rootR) return rootL, rootR node1 = TreeNode(1) node2 = TreeNode(2) node3 = TreeNode(3) node4 = TreeNode(4) node5 = TreeNode(5) node6 = TreeNode(6) node7 = TreeNode(7) node8 = TreeNode(8) node1.right = node2 node2.left = node3 node2.right = node4 node4.left = node5 node4.right = node6 node5.right = node7 node7.right = node8 s = Solution() result = s.longestZigZag(node1) print(result)
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() continuar = str(input('Continuar ? [S/N]')).strip().upper()[0] while continuar not in 'SN': continuar = str(input('Continuar ? [S/N]')).strip().upper()[0] if continuar in 'N': break print('-=-' * 30) print(f'{"N°":<4} {"Nome":<30} {"Média":<15}') print('-' * 60) for a in alunos: for n in range(0, len(a[1])): media = (a[1][0] + a[1][1]) / 2 print(f'{cont:<4} {a[0]:<30} {media:>5.2f}') cont += 1 print('-' * 60) while True: mostrar = int(input('Mostrar Notas de qual aluno? (999 interrompe): ')) if mostrar == 999: break if mostrar in range(0, len(alunos)): print(f'Notas de {alunos[mostrar][0]} {alunos[mostrar][1]}') else: print('Opção Invalida') print('-' * 60) print('Finalizando...') print('Volte sempre!')
#!/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__(*args, **kwargs) def test_echo(self, test_string): ''' echo test ''' response, status_code = self.__agent__.Util.post_v1_util_echo( sessionToken=self.__session__, keyManagerToken=self.__keymngr__, echoInput={"message": test_string} ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response def create_datafeed(self): ''' create datafeed ''' response, status_code = self.__agent__.Datafeed.post_v4_datafeed_create( sessionToken=self.__session__, keyManagerToken=self.__keymngr__ ).result() # return the token self.logger.debug('%s: %s' % (status_code, response)) return status_code, response['id'] def read_datafeed(self, datafeed_id): ''' get datafeed ''' response, status_code = self.__agent__.Datafeed.get_v4_datafeed_id_read( sessionToken=self.__session__, keyManagerToken=self.__keymngr__, id=datafeed_id ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response def send_message(self, threadid, msgFormat, message): ''' send message to threadid/stream ''' # using deprecated v3 message create because of bug in codegen of v4 ( multipart/form-data ) response, status_code = self.__agent__.Messages.post_v3_stream_sid_message_create( sessionToken=self.__session__, keyManagerToken=self.__keymngr__, sid=threadid, message={"format": msgFormat, "message": message} ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response def read_stream(self, stream_id, since_epoch): ''' get datafeed ''' response, status_code = self.__agent__.Messages.get_v4_stream_sid_message( sessionToken=self.__session__, keyManagerToken=self.__keymngr__, sid=stream_id, since=since_epoch ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
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 += c print(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): mph = kph * CONVERSION_FACTOR print(kph, '\t', format(mph, '.1f'))
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('输入第一个数字: ')) + float(input('输入第二个数字: '))))
# 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 State (Case) Class # class CredCase(object): def __init__(self,credit,itemCount,items): # Initialize: self.credit = int(credit) # credit amount self.itemCount = int(itemCount) # item count self.items = list(map(int,items.split())) # item values list self.cost = -1 # total cost self.solution = [] # output list def trySolution(self,indices): cost = self.items[indices[0]] + self.items[indices[1]] if (cost <= self.credit) and (cost > self.cost): self.cost = cost self.solution = [x+1 for x in indices] # # Read Input File # with open(ifile) as f: cases = int(f.readline()) for n in range(0,cases): case = CredCase(f.readline(),f.readline(),f.readline()) caselist.append(case) # # Conduct Algorithm # for n in range(0,cases): case = caselist[n] for i in range(0,case.itemCount): for j in range( (i+1) , case.itemCount ): case.trySolution( [i,j] ) if case.credit == case.cost: break if case.credit == case.cost: break # # Write Output File # with open(ofile,'w') as f: for n in range(0,cases): case = caselist[n] casestr = 'Case #'+str(n+1)+': ' casestr = casestr+str(case.solution[0])+' '+str(case.solution[1])+'\n' checkstr = 'Check: Credit='+str(case.credit) checkstr += ' Cost='+str(case.cost) checkstr += ' Item'+str(case.solution[0])+'=' checkstr += str(case.items[case.solution[0]-1]) checkstr += ' Item'+str(case.solution[1])+'=' checkstr += str(case.items[case.solution[1]-1])+'\n' f.write(casestr) #f.write(checkstr)
""" -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 None head = ListNode(list_node[0]) p = head for i in range(1, len(list_node)): p.next = ListNode(list_node[i]) p = p.next return head class Solution: # 返回合并后列表 def Merge(self, pHead1, pHead2): # write code here p = merge = ListNode(0) while pHead1 and pHead2: if pHead1.val <= pHead2.val: merge.next = pHead1 pHead1 = pHead1.next else: merge.next = pHead2 pHead2 = pHead2.next merge = merge.next merge.next = pHead1 or pHead2 return p.next def printList(self, head): p = head ret = list() while p: ret.append(p.val) p = p.next return ret if __name__ == "__main__": list_node1 = [1, 3, 4, 6, 12] list_node2 = [2, 7, 9, 10, 13] head1 = createListNode(list_node1) head2 = createListNode(list_node2) s = Solution() print(s.printList(head1)) print(s.printList(head2)) m = s.Merge(head1, head2) ret = s.printList(m) print(ret)
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))] prod = 1 for i in range(len(nums)): before_i[i] = prod prod *= nums[i] # scan from left to right to find products after i after_i = [i for i in range(len(nums))] prod = 1 for i in range(len(nums) - 1, -1, -1): after_i[i] = prod prod *= nums[i] return [before_i[i] * after_i[i] for i in range(len(nums))] # Version 2: save extra space, Time: O(n), Space: O(1) class Solution: def productExceptSelf(self, nums): """ :type nums: List[int] :rtype: List[int] """ products = [i for i in range(len(nums))] # scan from left to right to find products before i prod = 1 for i in range(len(nums)): products[i] = prod prod *= nums[i] # scan from left to right to mutiply products after i prod = 1 for i in range(len(nums) - 1, -1, -1): products[i] *= prod prod *= nums[i] return products
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__': #These "asserts" using only for self-checking and not necessary for auto-testing assert most_frequent([ 'a', 'b', 'c', 'a', 'b', 'a' ]) == 'a' assert most_frequent(['a', 'a', 'bi', 'bi', 'bi']) == 'bi' print('Done')
# 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('Digite um numero [999 para parar]: ')) if n == 999: break s += n c += 1 print(f'A soma dos numeros eh: {s}') print(f'A quantidade de numero digitada foi: {c}')
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): # """Test that the dataset class works. # # To run this test directly, issue this command from the root directory: # python -m test.test_dataset # """ # file_name = 'api_data-2018.03.19-v29-SAS.xlsx' # # def setUp(self): # """Set up: (1) Put Flask app in test mode, (2) Create temp DB.""" # # Continue from here next time # # 1 set up the test # import tempfile # app = create_app() # # TODO: Will this work? # self.db_fd, app.config['DATABASE'] = tempfile.mkstemp() # app.testing = True # self.app = app.test_client() # with app.app_context(): # # 2. new dataset object # new_dataset = Dataset( # file_path=TEST_STATIC_DIR + TestDataset.file_name) # # 3. write to db # db.session.add(new_dataset) # db.session.commit() # # def test_dataset(self): # """Create a new entry in 'dataset' table and read data.""" # # 4. read from the db # dataset_from_db = Dataset.query\ # .filter_by(dataset_display_name=TestDataset.file_name).first() # # # 5. make assertions # self.assertTrue(dataset_from_db.ID != '') # self.assertTrue(dataset_from_db.data != '') # self.assertTrue(dataset_from_db.dataset_display_name == # 'api_data-2018.03.19-v29-SAS.xlsx') # self.assertTrue(type(dataset_from_db.upload_date) == # datetime.date.today()) # self.assertTrue(dataset_from_db.version_number == 'v29') # self.assertTrue(dataset_from_db.dataset_type in # ('data', 'metadata', 'full')) # self.assertTrue(dataset_from_db.is_active_staging is False) # self.assertTrue(dataset_from_db.is_active_production is False) # # def tearDown(self): # """Tear down: (1) Close temp DB.""" # # 5: remove the stuff we wrote to the db # os.close(self.db_fd) # os.unlink(self.app.config['DATABASE']) # # # # TODO: Use this example from tutorial for the above test # class TestDB(unittest.TestCase): # """Test database functionality. # # Tutorial: http://flask.pocoo.org/docs/0.12/testing/ # """ # # def setUp(self): # """Set up: (1) Put Flask app in test mode, (2) Create temp DB.""" # import tempfile # from manage import initdb # self.db_fd, app.config['DATABASE'] = tempfile.mkstemp() # app.testing = True # self.app = app.test_client() # with app.app_context(): # initdb() # # def tearDown(self): # """Tear down: (1) Close temp DB.""" # os.close(self.db_fd) # os.unlink(app.config['DATABASE']) # # def test_empty_db(self): # """Test empty database.""" # resp = self.app.get('/') # assert b'No entries here so far' in resp.data
#!/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[mi]: hi = mi-1 else: lo = mi+1 else: if nums[mi] < target <= nums[hi]: lo = mi+1 else: hi = mi-1 return -1 sol = Solution() nums = [] nums = [4,5,6,7,0,1,2] nums = [3,1] target = 1 for target in nums: print(sol.search(nums, target))
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 DAYS_OF_WEEK = [ "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" ] if min_new > 59: min_new -= 60 hr_new += 1 hr_new_period = hr_new while hr_new > 12: hr_new -= 12 while hr_new_period > 11: hr_new_period -= 12 period = "PM" if period == "AM" else "AM" periods_later += 1 if periods_later % 2 != 0: if initial_period == "PM": periods_later += 1 else: periods_later -= 1 days_later = periods_later / 2 new_time = f"{hr_new}:{str(min_new).zfill(2)} {period}" if day: day_index = DAYS_OF_WEEK.index(day.title()) new_day_index = int((day_index + days_later) % 7) new_time += f", {DAYS_OF_WEEK[new_day_index]}" if days_later == 1: new_time += " (next day)" if days_later > 1: new_time += f" ({int(days_later)} days later)" return new_time
# 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", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety", "Hundred"] thousands = ["" , "Thousand", "Million", "Billion"] def printer(remainder): res_print = "" # Handle zero case if remainder == 0: return " " # Get the hundreds digit if remainder >= 100: res_print += str( under_twenty[int(remainder/100)]) + " Hundred " # Get tens and ones digit, accounting for zero tens = remainder%100 # Under 20 is a special case due to english diction if tens < 20: res_print += under_twenty[tens] + " " elif tens < 100: res_print += under_hundred_above_twenty[ int(tens/10) - 2 ] + " " res_print += under_twenty[tens%10] + " " return res_print # Handle edge case if num == 0: return "Zero" # We subdivide the number into every thousands res = "" thousand_count = 0 # 123000 has the same start as 123, thus we keep dividing by 1000 while float(num / 1000.0) > 0.00001: # Use a helper function to determine the suffix, and add it to the beginning suffix = printer(num%1000) if suffix != " ": res = printer(num % 1000) + thousands[thousand_count] + " " + res # Update the thousand_count thousand_count +=1 # Update num and round it num = int(num/1000) res = res.split() res = " ".join(res) return res.strip() z = Solution() num = 1000001000 print(z.numberToWords(num))