text
stringlengths
37
1.41M
# importar no shell interativo def separar_palavras(palavra): """Essa função irá separar palavras para nós.""" palavras = palavra.split() return palavras def ordenar_palavras(palavras): """Ordena palavras.""" return sorted(palavras) def imprime_primeira_palavra(palavras): """Imprime a prime...
from sys import argv script, nome_arquivo = argv print("Nós apagaremos o arquivo %r." % nome_arquivo) print("Se você não quiser, aperte CTRL-C (^C).") print("Se você não se importa, aperte ENTER.") input("?") print("Abrindo o arquivo...") arquivo = open(nome_arquivo, "w") print("Apagando o arquivo. Tchau!") arquiv...
def soma(a, b): print("Somando %d + %d" % (a, b)) return a + b def subtracao(a, b): print("Subtraindo %d - %d" % (a, b)) return a - b def multiplicacao(a, b): print("Multiplicando %d * %d" % (a, b)) return a * b def divisao(a, b): print("Dividindo %d / %d" % (a, b)) return a / b print("Vamos fazer algumas o...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 20 13:46:38 2020 @author: Hank.Da """ """ pesudocode: define find_sroot using number and epsilon as arguments initiate step = square(epsilon) initiate numGuess = 0 initiate root = 0 while (absolute numb...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 20 18:05:03 2020 @author: Hank.Da """ """ Pesudocode: function implement """ def max(a, b): if a > b: return a else: return b # Program to print out the largest of two numbers entered by the user # Uses two func...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 8 14:32:39 2020 @author: Hank.Da """ """ #pseudocode: ask user enter three int numbers if the number is odd number: then put the number in list find the largest number in the list by compare current number and temporary largest number ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 15 14:36:09 2020 @author: Hank.Da """ """ Pesudocode : prompt user to enter an integer print Times enterd number for num1 in range 1 : 20 +1 print print num1 and num1 multiply enterd number """ num_in...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 6 13:14:38 2020 @author: Hank.Da """ def main(): input_currency =float(input('plz type in amount of TWD to exchange to EUR: ')) print("input_currency : ", str(input_currency) , "TWD") if input_currency>=0: #TWD to EUR e...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 22 16:02:04 2020 @author: Hank.Da """ """ Pesudocode: function implement """ # Look for prime numbers in a range of integers for number in range(2, 20): for i in range(2, number): if number % i == 0: print(number, 'eq...
''' code to minimize dfa ''' import json import sys ''' function to print dfa optimally ''' def print_dfa(dfa): print("states : ") for i in dfa['states'] : print(i) print("transition :") for s in dfa['transition_function'] : print("old state : {0} , input : {1} and next state : ...
# Authors: Tom Lambert (lambertt) and Yuuma Odaka-Falush (odafaluy) import matrix def main(): """Executes the main program with predefined values.""" experiment = "3.2B - B" # allowed are "3.1B", "3.2B - B", "3.2B - A" # The types to use for the experiments dtypes = ["float16", "float32", "...
import scipy.sparse def get_matrix(n): size = (n-1)*(n-1) result = scipy.sparse.dok_matrix((size, size)) for block in range(0, n - 1): for i in range(0, n - 1): result[(block * (n-1)) + i, (block * (n-1)) + i] = 4 if i > 0: result[(block * (n-1)) + i, (block...
def load_data(): with open('day_1/input.txt') as data: return [int(mass) for mass in data] def total_fuel(mass): final_mass = 0 while True: mass = mass // 3 - 2 if mass > 0: final_mass += mass else: return final_mass def sum_of_fuel(): ma...
import random suits = ["Hearts", "Diamonds", "Spades", "Clubs"] card_value = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"] suit = suits[random.randint(0,3)] card = card_value[random.randint(0,12)] print(card + " of " + suit)
## types of inheritance 1. simple inheritance 2. multi level inheritance 3. multiple inheritance class A: def feature1(self): print("Feature 1 working") class B: def feature2(self): print("Feature 2 working") class C(B): def feature3(self): print("Feature 3 working")...
class Person: def __init__(self): self.name = 'Sara' self.age = 20 def compare(self, other): if self.age == other.age: print("They are same") else: print("They are not same") p1 = Person() p2 = Person() p1.compare(p2) if p1.age == p2....
""" Solving mazes with generic search (without numpy) See 'Classic Computer Science Problems in Python', Ch. 2 """ from enum import Enum from collections import namedtuple import random from math import sqrt class Cell(str, Enum): empty = " " blocked = "X" start = "S" goal = "G" path = "...
""" Example using a graph comprising the top 15 metro areas in the US to illustrate the Jarnik algorithm for finding the minimum spanning tree of a weighted graph. See Classic Computer Science Problems in Python, Ch. 4 """ import sys sys.path.append('..') from cities import top_15_metro_areas_in_US_weighted_by_dista...
from Read_write_workbook import read_from_xlsx, write_to_xlsx from googletrans import Translator def translate_de_to_en(): filename = input('Excel table name to be read: ') column = input('Column letter to be read: ') start_row = int(input('First row number to be read: ')) end_row = int(input(...
from tkinter import * import scheduler, DisplayTasksUI, DTS def createWhitelistWindow(tkinterRoot): # This creates the new window for the whitelist menu master = Toplevel() master.title("Create whitelist") # Initialise the colours in variables black = "black" white = "white" # L...
""" BASICS Computes the SHA256 checksum of a file """ import hashlib # Computes the SHA 256 checksum of a file given its name # Based on https://gist.github.com/rji/b38c7238128edf53a181 def sha256_checksum(filename, block_size=65536): sha256 = hashlib.sha256() with open(filename, 'rb') as f: for ...
prompt = "The '#' character can be used to write single-line comments. Use this to write a comment of your own!" def TEST(student_input, student_output): problems = "" if "#" not in student_input: problems = problems + "You must use the '#' character to write at least one comment." ...
prompt = "Declare a variable named <strong>my_boolean</strong> and assign it a value of <strong>False</strong>." def TEST(student_input, student_output): problems = "" returns = [VALIDATE_VAR("my_boolean", "bool", False)] for thing in returns: if thing != True: problems...
import random min = 1 max = 6 turn=0 user_sum=0 play="Y" while(user_sum<20) : turn+=1 if(turn!=1): print() print("Turn "+str(turn)) user_input="r" turn_sum=0 flag=0 while(user_input!="h"): print("Roll or hold? (r/h): ",end="") user_input=input() if(user_input=...
""" 多个子进程 """ from multiprocessing import Process import os,sys import time def func01(): time.sleep(3) print("小泽一号") print(os.getpid(),"------",os.getppid()) def func02(): time.sleep(2) print("小泽二号") print(os.getpid(),"------",os.getppid()) def func03(): time.sleep(4) sys.exit("小泽四号") ...
#!/usr/bin/env python import getpass true_name = 'liuyueming' true_passwd = 'pwd' input_name = input('Please input your name:') input_passwd = input('Please input your password:') if input_name==true_name and input_passwd==true_passwd: print("Welcome",input_name) else: print("Login failure")
def is_palindrome(n): #str(n)把整数转换成字符串使用切片法反转 #例如s='123'则s[::-1]='321' #如果反转后与反转前是一致则返回True return str(n)==str(n)[::-1] #打印1-1999之间所有回数 print(list(filter(is_palindrome,range(1,2000))))
def _odd_iter(): n=1 while True: n=n+2 yield n def _not_divisible(n): def f(x): return x%n>0 return f def primes(): yield 2 it=_odd_iter() while True: n=next(it) yield n it=filter(_not_divisible(n),it) for n in primes(): if n<100: ...
class Bucketlist(object): """Enable the user perform various operations on the bucketlist e.g create bucketlist and add bucketlist item """ def __init__(self, title): self.title = title self.titles = [] self.bucketDict = {} self.items = [] def create(self): ...
print('Cálculo da área de um círculo') PI = 3.14 raio = int(input('Digite o raio do círculo: ' )) area = PI * raio**2 print('A área do círculo é:', area, 'cm2')
# -*- coding: utf-8 -*- """ Created on Wed Jan 22 15:52:51 2020 @author: ojhag """ class Queue: def __init__(self): self.arr = [] def isEmpty(self): return self.arr == [] def enqueue(self,item): self.arr.insert(0, item) def dequeue(self): ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 26 10:24:42 2019 @author: owner """ class Person(object): def __init__(self, name, add): self._Name = name self._Address = add def getName(self): return self._Name def setName(self, name): s...
####################################################### # Implement a program to check, given two strings # # if they are one edit (or zero edits) away. # # EXAMPLE # # pale, ple -> true # # pales, pale -> true ...
################################################################# # Implement an algorithm to delete a node in the middle # # (i.e., any node but the first and last node, not necessarily # # the exact middle) of a singly linked list, given only # # access to that node. Do not print anything ...
user_string = input("Enter your String :: ") output = "" for letter in user_string: if letter in "aeiou": output = output+"P" else: output = output+letter print(output)
# for i in range(3): # print("hello world") # lst = ['xdoramming','programming','helloWorld'] # for i in lst: #1st iteration # print(i) # lst = [["xdoramming","Programming"],["mukesh","Films"]] # for i,j in lst: # print(j) # dictionary = {'name':'priyanshu', # 'channelName':'...
a=input() is_palindrom="" for i in a: is_palindrom=i+is_palindrom print(a==is_palindrom)
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next from heapq import heappush, heapify, heappop c...
# in an array arr[0] <= arr[1] >= arr[2] <= arr[3] >= arr[4] .... class Solution(object): def wiggle(self, nums, l): for i in range(0, l, 2): if i + 1 < l and nums[i] > nums[i + 1]: temp = nums[i] nums[i] = nums[i + 1] nums[i + 1] = temp ...
# if matrix is """ [[1 2 3] [4 5 6] [7 8 9]] diagonally go up, 1 diagonally go down 2 4 diagonally move up 7 5 3 then down 6 8 then up 9 answer = [1,2,4,7,5,3,6,8,9] """ class Solution(object): def findDiagonalOrder(self, matrix): row = len(matrix) if row < 1: return [] ...
# binary tree - serialize # 1 # /\ # 2 3 # / # 4 -1 -1 5 # class Node: def __init__(self, data=None, left=None, right=None): self.data = data self.left = left self.right = right class Tree: def __int__(self, head=None): self.head = head def serialize(treeHead): ...
# https://leetcode.com/problems/string-to-integer-atoi/submissions/ class Solution(object): def myAtoi(self, s): l = len(s) if l < 1: return 0 i = 0 while i < l and s[i] == ' ': i += 1 if i == l: return 0 j = i sighns = ...
# add all numbers in a bst, add the values that fall in [low,high] # here i checked every node, but ideally, if a node value is less than low, no need to check the left branch, as all values in left will be even lessar # https://leetcode.com/problems/range-sum-of-bst/ # Definition for a binary tree node. # class Tree...
''' 8) Faça um Programa que leia 20 números inteiros e armazene-os num vetor. Armazene os números pares no vetor PAR e os números IMPARES no vetor impar. Imprima os três vetores. ''' vetor=[] vetorpar=[] vetorimpar=[] i=0 while i<20: print() print("Este é o número",i+1,"de 20.") numero=eval(input("Insir...
''' Exercício 1: faça um algoritmo que solicite ao usuário números e os armazene em um vetor de 30 posições. Crie uma função que recebe o vetor preenchido e substitua todas as ocorrência de valores positivos por 1 e todos os valores negativos por 0.  ''' vet = [0]*30 for i in range(30): print("Posição"...
''' 6) Desenvolva um gerador de tabuada, capaz de gerar a tabuada de qualquer número inteiro entre 1 a 10. O usuário deve informar de qual numero ele deseja ver a tabuada. A saída deve ser conforme o exemplo abaixo: Tabuada de 5: 5 X 1 = 5 5 X 2 = 10 ... 5 X 10 = 50 ''' tabuada=int(input("Insira um valor i...
''' 1) Faça um algoritmo para ler a idade de 5 pessoas e informar qual foi a maior idade informada. ''' maior=0 x=0 for x in range(5): print() print("Esta é a idade",x+1,"de 5.") idade=int(input("Insira uma idade: ")) if idade>maior: maior=idade print() print("A maior idade é:",maior,".")
''' 5)apos calcular o IMC informe, o de acordo com o sexo informe a situação de acordo com a tabela a seguir: Condição IMC em Mulheres IMC em Homens abaixo do peso < 19,1 < 20,7 no peso normal 19,1 - 25,8 20,7 - 26,4 marginalmente acima do peso 25,8 - 27,3 26,4 - 27,8 acima do peso ideal 27...
''' 2)Faça um algoritmo para converter valores de fahrenheit celsius ''' resposta="sim" while resposta=="sim": fahr=float(input("Informe a temperatura em Fahrenheit: ")) celsius=(fahr-32)/1.8 print("A temperatura em Celsius é %2.2f"%(celsius)) resposta=input("Deseja inserir mais uma temperatura em...
x0 = 0 y0 = 0 j = 0 x1 = 0 y1 = 0 x2 = 0 def showled(x: number, y: number, dir: number): pass def on_forever(): showled(0, 0, 0) showled(4, 0, 1) showled(0, 4, 2) showled(4, 4, 3) basic.forever(on_forever) def on_forever2(): global x0, y0, j, x1, y1, x2 x0 = 4 y0 = 0 for i in range...
# -*- coding: utf-8 -*- """ Created on Sat Oct 5 21:28:09 2019 @author: laksh """ l=[1,4,2,7,4,8] print(max(l[2:5])) print(l) print(min(l[2:5]))
# -*- coding: utf-8 -*- """ Created on Thu Oct 17 11:02:39 2019 @author: laksh """ for i in range(int(input())): n=int(input()) l=[] for j in range(n): #l.append([]) l.append(str(input())) print(l) print(sorted(l)) break
# Implementation of Matrix Chain Multiplication in Python # Time Complexity: O(n^3) # Space Complexity: O(n^2) from math import inf def matrixChain(arr): n = len(arr) dp = [[0]*n for i in range(n)] # dp[i, j] = Minimum number of scalar multiplications needed to multiply arr[i..j] # chain length for length in ra...
from math import factorial as fact def factorial(numStr): try: n = int(numStr) r = str(fact(n)) except: r = 'Error!' return r def decToBin(numStr): try: n = int(numStr) r = bin(n)[2:] except: r = 'Error!' return r def binToDec(numStr): try: ...
class Menu (object): def mostrarMenu(self): print("\nIngresar opcion:\n" "\t1 - Ver listado de cuentas \n" "\t2 - Ver cuentas por titular \n" "\tq - salir \n") key = input() self.procesarOpcion(key) def procesarOpcion(self, key): i...
""" Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. Solution: ...
""" // Time Complexity : O(nlogn), where n is the number of elements in the array // Space Complexity : O(n) // Did this code successfully run on Leetcode : not on leetcode // Any problem you faced while coding this : No """ # Python program for implementation of Quicksort # This function is same in both iterative...
#!/usr/bin/env python # -*- coding: utf-8 -*- # q/quit to quit, ENC_message to print encoded "message", otherwise decodes message # To type an encoded message, use type your message while holding the option key # (this makes it type in weird unicode characters), letters will be automatically # lowercased due to an ov...
# <QUESTION 1> # Given a list of items, return a dictionary mapping items to the amount # of times they appear in the list # Note: the order of this dictionary does not matter # <EXAMPLES> # one(['apple', 'banana', 'orange', 'orange', 'apple', 'apple']) → {'apple':3, 'orange':2, 'banana':1} # one(['tic', 'tac', 'to...
import requests import sys import glob import csv import os from zipfile import ZipFile from datetime import datetime DATE=sys.argv[1] MONTH=sys.argv[2] YEAR=sys.argv[3] url = "https://www.nseindia.com/content/historical/EQUITIES/%s/%s/cm%s%s%sbhav.csv.zip" % (YEAR, MONTH, DATE, MONTH, YEAR) fileZip = "Zip%s%s%s.zip...
"""This module defines the `Space` class.""" import abc import random import typing import numpy from . import dataset from . import metric class Space(abc.ABC): """This class combines a `Dataset` and a `Metric` into a `MetricSpace`. We build `Cluster`s and `Graph`s over a `MetricSpace`. This class provid...
myVar = input("What if your answer to my 1st question? (yes/no) ") if myVar == "yes": myNextVar = input("What id your answer to my 2nd question? (yes/no) ") if myNextVar == "yes": print("Good your paying attention.") elif myNextVar == "no": print("Come on man pay attention") else: ...
#ben shade #Counts_to_twenty this program count to 20 print("this counts to 20") number = 0 while number < 21: print(number , end = " " ) number += 1
import abc class StorageManagerInterface(abc.ABC): """ Interface for a file storage manager of our time series Methods ------- store: Stores a given time series `t` into the storage manager by index size: Returns the length of the time series in storage by index ...
# The 3-sum problem. def has_three_sum(nums, t): nums.sort() for n in nums: if has_two_sum(nums, t - n): return True return False def has_two_sum(nums, t): i, j = 0, len(nums) - 1 while i < j: cur_sum = nums[i] + nums[j] if cur_sum < t: i += 1 ...
# Is an anonymous letter constructible? def is_letter_constructable(str_m, str_l): dict_m = {} for c in str_m: if c not in dict_m: dict_m[c] = 1 else: dict_m[c} += 1 for c in str_l: if c not in dict_m: return False else: dict...
# Find the nearest repeated entries in an array. import sys def find_nearest_repetition(p): words = {} ret = sys.maxint for i in range(len(p)): cur_word = p[i] if cur_word in words: ret = min(ret, i - words[cur_word]) words[cur_word] = i return ret
# Test palindromicity. def is_palindrome(s): i, j = 0, len(s) - 1 while i < j: while (not s[i].isalnum() and i < j): i += 1 while (not s[j].sialnum() and i < j): j -= 1 if s[i] != s[j]: return False i += 1 j -= 1 return True
# Test for palindromic permutations. def can_form_palindrome(s): c2cnt = {} for c in s: if c in c2cnt: c2cnt[c] += 1 else: c2cnt[c] = 1 odd_cnt = 0 for v in c2cnt.values(): if v % 2 != 0: odd_cnt += 1 if odd_cnt > 1: ...
# Find the first key greater than a given value in a BST. class TreeNode: def __init__(v=None, l=None, r=None): self.v = v self.l = l self.r = r def find_first_greater(t, k): sub_t, ret = t, None while sub_t: if sub_t.v > k: ret = sub_t.v sub_t = sub_...
# Find the majority element. def majority_search(iter_str): cand = None cur_str, cnt_cand = next(iter_str, None), 0 while cur_str: if cnt_cand == 0: cand = cur_str cnt_cand = 1 elif cur_str == cand: cnt_cand += 1 else: cnt_cand -= 1 ...
def find_maxsum_subarray(nums): min_sum, cur_sum, max_sum = 0, 0, 0 for n in nums: cur_sum += n if cur_sum < min_sum: min_sum = cur_sum if cur_sum - min_sum > max_sum: max_sum = cur_sum - min_sum return max_sum
# recursive, O(n) space def calc_fibonacci_recursive(n): f_dict = {} if n < 2: return n elif n not in f_dict: f_dict[n] = (calc_fibonacci_recursive(n - 2) + calc_fibonacci_recursive(n - 1)) return f_dict[n] # iterative, O(1) space def calc_fibonacci_iterative(n): ...
from __future__ import division from collections import defaultdict from math import log import csv # create function to train # it takes data data is a dict: (words) -> lang # from tuple of language words -> to language def train(data): # 2 dicts with 0 as default values # classes are languages, we classify...
#The main purpose of this file is to determine the best word using the spaces #on the board, and to calculate what the score would be for a specific #word placement on a certain part of the board, after we define the specific #spaces on the board that correspond to "special" tiles, and the scores we would #get for...
""" Exercício 2: Nova busca : até o momento nossa estrutura consulta elementos através da posição. Nesta atividade será necessário criar uma função chamada def index_of(self, value) , onde ela será responsável por consultar na lista a existência do valor informado e retornar a posição da primeira ocorrência. Caso o val...
# Exercício 2 Suponha que se está escrevendo uma função para um jogo de batalha # naval. Dado um array bidimensional com n linhas e m colunas, e um par de # coordenadas x para linhas e y para colunas, o algoritmo verifica se há um # navio na coordenada alvo. Por exemplo: entrada = [ 0, 0, 0, 0, 1,...
# ❗ Importe arquivo books.json no mongo antes de responder próximas questões. # 🦜 mongoimport --db library books.json # Exercício 6 Escreva um programa que se conecte ao banco de dados library e # liste os livros da coleção books para uma determinada categoria recebida por # uma pessoa usuária. Somente o título dos...
# Exercício 3: Faça um programa que, dado um valor n qualquer, # tal que n > 1, imprima na tela um quadrado feito de asteriscos # de lado de tamanho n. Por exemplo: def draw_square(n): for row in range(n): print(n * "*") draw_square(10)
# Exercício 2: Faça um programa que, dado um valor n qualquer, tal que n > 1, # imprima na tela um triângulo retângulo com 5 asteriscos de base. Por exemplo: def draw_triangle(n): for row in range(1, n + 1): print(row * '*') draw_triangle(15)
""" Quais elementos da lista A também ocorrem na lista B? Ou seja, qual interseção entre lista """ listA = [1, 2, 3, 4, 5, 6] listB = [4, 5, 6, 7, 8, 9] # resposta: [4, 5, 6] # O(n + m) def instersection(listA, listB): # criar uma dict da listA seen_in_a = {} for item in listA: if item not in s...
""" Exercício 1: Pilhas - Baseado nos conhecimentos adquiridos neste bloco, implemente uma pilha utilizando a Deque como a estrutura interna. Sua pilha deve conter as operações: push, pop, peek e is_empty Para este desafio, é necessário efetuar o import da classe Deque e utilizar seus métodos de acesso para simular uma...
# Exercício 6 # Dado um array de doces candies e um valor inteiro extra_candies, onde o # candies[i] representa o número de doces que a enésima criança possui. Para # cada criança, verifique se há uma maneira de distribuir doces extras entre # as crianças de forma que ela possa ter o maior número de doces entre elas. #...
# CRIANDO ENTIDADE USER class User: def __init__(self, name, email, password): """Método construtor da classe User. Note que o primeiro parâmetro deve ser o `self`. Isso é uma particularidade de Python, vamos falar mais disso adiante!""" self.name = name self.email ...
# Exercício 6 # Escreva uma função que identifique o único número duplicado em uma lista. # Retorne o número duplicado em O(n). # Exemplos de entrada e saída: entrada = [1, 3, 2, 4, 5, 1] # saída: 1 # Exercício 7 # Sua trajetória no curso foi um sucesso e agora você está trabalhando para a # Trybe! Em um determinado ...
""" Separe as palavras de acordo com sua letra inicial text = ['ana', 'ama', 'joao', 'que', 'ama', 'jose', 'mas', 'jose', 'nao', 'ama', 'ana'] reposta: a: ['ana', 'ama', 'ama', 'ama', 'ana'] j: ['joao', 'jose', 'jose'] q: ['que'] m: ['mas'] n: ['nao'] """ text = [ "ana", "ama", "joao", "que", "am...
""" Exercício 1: Aprimorando a classe Lista : nossa classe Lista atende as principais operações que essa TAD nos oferece, mas que tal melhorarmos? Para isso, você deve adicionar os seguintes métodos: a. A operação clear nos permite remover todos os Nodes da lista; b. A operação __get_node_at nos permite acessar o Node ...
from exercicio1 import fizzbuzz def test_fizzbuzz_should_return_list_of_numbers(): assert fizzbuzz(2) == [1, 2] def test_fizzbuzz_divisible_by_three_should_be_fizz(): assert fizzbuzz(3)[-1] == "Fizz" def test_fizzbuzz_divisible_by_five_should_be_buzz(): assert fizzbuzz(5)[-1] == "Buzz" def test_fizz...
# Exercício 1: Lembra do exercício da TV que já abstraímos? Hoje vamos # implementar ele, porém com algumas modificações. Veja o diagrama abaixo: # Atributos: # volume - será inicializado com um valor de 50 e só pode estar entre 0 e 99; # canal - será inicializado com um valor de 1 e só pode estar entre 1 e 99; # tama...
# Exercício 5 Em um software gerenciador de servidores, precisamos verificar o # número de servidores que se comunicam. Os servidores estão representados como # um array bidimensional onde o valor 1 representa um computador e 0 a ausência # do mesmo. Dois servidores se comunicam se eles estão na mesma linha ou mesma # ...
NAME = input("Insira seu nome: ") for letter in NAME: print(letter)
''' 8.4 Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort a...
import re fname = 'regex_sum_702244.txt' file = open(fname , 'r') print('Sum :', sum([int(number for number in re.findall('[0-9]+' , file.read()))])) numbers = list() total_num = list() for line in file : line = line.rstrip() numbers = re.findall('[0-9]+' , line) for num in numbers : try : ...
def computepay(hrs, rate) : if (hrs <= 40) : pay = hrs * rate else : pay = (40 * rate) + ((hrs - 40) * (rate * 1.5)) return pay hours = input("Enter hours : ") rate_per_hour = input("Enter the Rate : ") try: hrs = float(hours) rate = float(rate_per_hour) except : print("Inval...
a=2 for a in range(1,4): print("praveen",a) for b in range(1,4): print("praveen",b)
# -*- coding: utf-8 -*- """ Created on Sun Oct 25 23:24:12 2020 @author: Yung """ import random class game: def __init__(self): #variable initialization self.choices = ["rock", "paper", "scissors"] #valid input/choices self.yes = ["yes", "y"] self.no = ["no", "n"] self.play...
j=input() i=0 for a in range (len(j)): if(j[a].isdigit() or j[a].isalpha() or j[a]==' '): continue else: i+=1 print(i)
''' This program deletes a node in the linked list. @author: Asif Nashiry ''' from deleteNodeLinkedList import LinkedList import random # number of elements in the list numOfData = 15 aList = LinkedList() # create a list with random numbers for i in range(numOfData): data = random.randint(1, 30) aList.insert...
import sqlite3 import os import datetime class Db_sql(object): def __init__(self,form): self.form = form def db_select(self): # 获取提交的表单数据! # form = request.form # 提取名称、日期 food_name = self.form.get('food_name').strip() start_date = self.get('start_date...
#!/usr/bin/env python3 import argparse import sys class ownParser(argparse.ArgumentParser): def error(self, message): sys.stderr.write('error: %s\n\n' % message) self.print_help() sys.exit(1) def magical_tree(height): for level in range(1,height+1): for spaces in range(1,heigh...