text
stringlengths
37
1.41M
class test: x = 1 def __init__(self, y): self.y = y def change_x(self, x): self.x = x def get_x(self): return self.x def get_y(self): return self.y test1 = test(1) print(test1.get_x()) print(test1.x) print(test1.change_x(2)) print(test1.get_x()...
# word_count.py # =================================================== # Implement a word counter that counts the number of # occurrences of all the words in a file. The word # counter will return the top X words, as indicated # by the user. # =================================================== import re from hash_map ...
import math #This is a practice for 100 days python challenge: #BMI calculator #BMI vaule # int, int -> int def BMI_cal( weight, height): BMI = weight/(height ** 2) return Print_check(int(BMI)) def Print_check(BMI): if(BMI == 28): print("Your BMI is "+ BMI + ", you are silightly overweight") elif(B...
import numpy as np import cv2 import math ''' Convert PNG or JPG photos or scans of page spreads of a book input image of book 'spread'. Format file name "P00001.png" incrementing with fixed filename length, padded zero output: JPG grayscale, processed and cropped ''' def main(argv): src_dir = "raw" tgt_dir = "pro...
#!/bin/python def nextMove(n,r,c,grid): move = "" x,y = 0,0 for i in range(len(grid)): if 'p' in grid[i]: (x,y)=i,grid[i].index('p') if x!=r: if x>r: move="DOWN" elif x<r: move="UP" elif x==r: if y>c: move="RIGHT" elif y<c: move="LEFT" return move n = input() r,c = [int(i) for i in raw...
# TensorFlow and tf.keras import tensorflow as tf from tensorflow import keras # Helper libraries import numpy as np import matplotlib.pyplot as plt if __name__ == '__main__': print(tf.__version__) fashion_mnist = keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = fashion_...
import math x, y = 0, 0 while True: s = input().split() if not s: break if s[0] == "up": x += s[1] if s[0] == "down": x -= s[1] if s[0] == "left": y += s[1] if s[0] == "right": y -= s[1] dist = round(math.sqrt(x ** 2 + y ** 2)) print(dist)
# Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically. ss = input().split() dict = {} for i in ss: dict.setdefault(i, ss.count(i)) dict = sorted(dict.items()) for i in dict: print(i[0], i[1])
# Write a program that accepts a sentence and calculate the number of letters and digits. l = input() letter, digit = 0, 0 for i in l: if ("a" <= i and i <= "z") or ("A" <= i and "Z"): letter += 1 if "0" <= i and i <= "9": digit += 1 print("LETTERS ",letter) print("DIGITS ",digit)
class Graph(): def __init__(self, adj): self.adj = adj self.size = len(adj) self.entered = [False] * self.size self.left = [False] * self.size def explore(self, index): if self.entered[index] and not self.left[index]: return False if self.left[index] ...
import math name = input("whats your name?") last_name=input("whats your last name?") a = float (input("type the first lessons:")) b = float (input("type the second lessons:")) c = float (input("type the third lessons:")) x = a + b + c average=x/3 if average >= 17 : print( name,last_name,"great") ...
""" Arsh recently found an old rectangular circuit board that he would like to recycle. The circuit board has R rows and C columns of squares. Each square of the circuit board has a thickness, measured in millimetres. The square in the r-th row and c-th column has thickness Vr,c. A circuit board is good if in each ...
import unittest from gs1.GTIN import GTIN class GTINTest(unittest.TestCase): ''' Unit Tests for a GTIN ''' def setUp(self): pass def test_create_gtin(self): ''' Test the creation of the GTIN Abstract class ''' gtin = GTIN() self.assertIsInst...
import numpy as np import matplotlib.pyplot as plt def sigmoid(x): return 1 / (1 + np.exp(-x)) def softmax(x): e_x = np.exp(x) return e_x / np.sum(e_x) #Define network architecture class ShallowNN: def __init__(self, num_input, num_hidden, num_output): self.W_h = np.zeros((num_hidden, num_inp...
# https://github.com/TU-Zhekun/TP1_EconomicSimulation import random from abc import ABC, abstractmethod import numpy namelist = range(1000) person_dict = dict.fromkeys(namelist, 0) # start with an uniform initialization (every individual has the same wealth) def initialization(namelist, wealth): person_dict = ...
# t = [1, 2, 3, 4, 5] # a = t[0] + t[3] # b = t[-1] # c = t[3:] # a = a + t[-2] # # # abc = ['a', 'b', 'c', 'd', 'e'] # print(abc[3]) # print(abc[-3:]) liste = [1, 4, 1, 2, 1, 5, 3, 1, 12] a = len(liste) b = liste[0] liste.append(0) c = len(liste) d = liste[-1] liste.extend([2, 9, 1]) while liste.count(1) > 0: li...
# tick tack toe game # create a 2d list for winning combinations # take user input put it in list and compare 2 list. list_win = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]] board = [" ", " ", " ", " ", " ", " ", " ", " ", " "] player1 = "X" player2 = "O" def print_patte...
# -*- coding: utf-8 -*- """ Created on Thu Sep 21 15:11:48 2017 @author: ZHENGHAN ZHANG """ ''' Author: Harry Zhenghan Zhang This program is a game It is an interactive nonogram puzzle solver called the Pythonogram You should enter the coordinates of the space where you think there should be an '*' The pattern...
import random alu1 = str(input('primeiro aluno ')) alu2 = str(input('segundo aluno ')) alu3 = str(input('terceiro aluno ')) alu4 = str(input('quarto aluno ')) alu5 = str(input('quinto aluno ')) alu6 = str(input('quinto aluno ')) lista = [alu1, alu3, alu4, alu5, alu6] random.shuffle(lista) print(lista)
salario = float(input('qual o salario? ')) print('O salário com 10% de almento é {}' .format(salario + (salario * 0.1)))
n1 = float(input('entre com a primeira nota ')) n2= float(input('entre com a segunda nota ')) print('a media entre as notas {} e {} é {:.1f}' .format(n1, n2, (n1 + n2) / 2))
''' Created on Feb 11, 2016 @author: chogg ''' import numpy as np import matplotlib.image as image from matplotlib.image import BboxImage from matplotlib.transforms import Bbox # def plot_wind_data(ax, so, time_nums): # print('this is the length of time for wind',len(so.wind_time)) # #i need to go home _-_ # ...
import pickle def Q_A(data_dict): #Question: How many data points (people) are in the dataset? print "Number of people in the dataset:",len(data_dict) #Question: For each person, how many features are available?? print "Number of feature for each person:",len(data_dict.itervalues().next()) #Ques...
class LinkedList: def __init__(self, value): self.value = value self.next = None def removeDuplicatesFromLinkedList(linkedList): seenVals = set() temp = linkedList prev = temp while(temp.next != None): if temp.value in seenVals: temp = temp.next prev ...
def URLify(str, lenght): str = str.replace(" ", "%20") return str def palindromePerm(str): pass # def OneWay(str1, str2): # strLengthDif = abs(len(str1) - len(str2)) # #same length case # if(strLengthDif == 0): # if(str1 == str2): # return True # else: # ...
#!/usr/bin/env python3.6 import re from palindrome import Palindrome def add_palindrome(palindrome): new_palindrome= Palindrome(palindrome) return new_palindrome def save_palindrome(palindrome): palindrome.save_palindrome() def display_palindromes(): return Palindrome.display_palindromes() def main(...
''' key = {"name":"laowang","age":33,"sex":"nan","shengao":180,"tizhong":"60kg"} print(key) print(key.values()) for i in key.values(): print(i) ''' list = [{"上海":{"面积":"100平米","人口":"200W"},"北京":{"面积":"70平米","人口":"150W"},"南京":{"面积":"300平米","人口":"999W"}}] for i in list: for d,f,g in i.items(): for k,l,c i...
# Movement functions for navigating game board in Aliens board game simulation from random import choice, randint from time import sleep import marines_aliens as ma def print_board(board): """Print out a 2d array for visual purposes""" for row in board: print(row) # ---------------------------------- SPAWNING FUN...
""" Tic Tac Toe Player """ import math from copy import deepcopy import random X = "X" O = "O" EMPTY = None def initial_state(): """ Returns starting state of the board. """ return [[EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY]] def player(board): "...
class Node: def __init__(self, data, prev=None, next=None): self.data, self.prev, self.next = data, prev, next def __repr__(self): p = str(self.prev.data) if self.prev else '|' n = str(self.next.data) if self.next else '|' return '%s => %d => %s' % (p, self.data, n) def getHea...
# def intersect(a, b, p, q): # ax, bx = min(a[0], b[0]), max(a[0], b[0]) # px, qx = min(p[0], q[0]), max(p[0], q[0]) # if bx < px or ax > qx: # return False # ay, by = min(a[1], b[1]), max(a[1], b[1]) # py, qy = min(p[1], q[1]), max(p[1], q[1]) # if by < py or ay > qy: # return F...
import random import time import unittest from algorithms.sorts import insertion_sort, selection_sort, quick_sort, bubble_sort, merge_sort, bucket_sort def unsorted(): return [1, 3, 2, 4, 5, 7, 6, 8, 0, 9] def sorted(): return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] def measure_time_random(sort): array = [ran...
#Floyd-Warshall program # This program uses Floyd-Warshall program to compute all pair shortest path. # Runtime is O(n^3). import math # make a initial graph D0 = [ [0, 3, 8, math.inf, -4 ], [math.inf, 0, math.inf, 1, 7 ], [math.inf, 4, 0, math.inf, math.inf ], [2, math.inf, -5, 0, math.inf ], ...
# !/usr/bin/eny python3 # - * -coning: utf-8 -*- _author_ = '谭华锦' '''' 变量的作用域scope: 1.全局作用域 函数以外的区域都是全局作用域 在全局作用域中定义的变量都是全局变量 2.函数作用域,也称为局部作用域 ''' a = 5 # 全局变量 if True: c = 5 # 全局变量 def fn(): b = 5 # 局部变量 def fn1(): x = 4 def fn2(): x = 3 print(x) print('*' * 80) #...
# !/usr/bin/eny python3 # - * -coning: utf-8 -*- _author_ = '谭华锦' # 查看函数的帮助信息 help(print) help(abs) # 数学运算 print(abs(-5)) a = (21, 43, 54, 56, 6, 87, 9, 560) print(max(a)) print(max(21, 43, 54, 56, 6, 87, 9, 560)) # 类型转化 print(int('123')) print(str(123)) print(float('13.4')) print(bool(9)) # 判断数据类型 a = 'abc' print(...
# !/usr/bin/eny python3 # -*- coning: utf-8 -*- __author__ = '谭华锦' from tkinter import * class GetSum: def __init__(self): window = Tk() window.title('累加') frame1 = Frame(window) frame1.pack() label = Label(frame1, text='Enter first number:') labe2 = Label(frame1, ...
# !/usr/bin/eny python3 # - * -coning: utf-8 -*- _author_ = '谭华锦' # 空函数 def empty(): pass # 使用pass # 函数的返回值 def f1(): name = 'tanhuajian' age = 20 sex = 'male' return name, age, sex # print(f1()) #返回值是一个tuple a, b, c = f1() print(a, b, c) # 递归函数 def cale(x, y): # 常规方法 ''' if y==0...
# -*- coding: utf-8 -*- from __future__ import division import numpy as np def softmax(x): e = np.exp(x - np.max(x)) # prevent overflow if e.ndim == 1: return e / np.sum(e, axis=0) else: return e / np.array([np.sum(e, axis=1)]).T # ndim = 2 def sigmoid(x): return 1. / (1 + np.exp(-...
class Node(object): def __init__(self, value: int): self.value = value self.left = None self.right = None class OneDimentionTree(object): def __init__(self): self.root = None def make_tree(self, point_list: list): point_list.sort() def _make_tree(point_lis...
class TopologocalSort(object): def __init__(self, g: list): self.g = g self.node_num = len(g) def breadth(self): indegree = [0] * self.node_num for edges in self.g: for edge in edges: indegree[edge] += 1 sort_ans = [] queue = [] ...
def order_even_first_odd_last(nums: list) -> None: nums_len = len(nums) index = -1 for i in range(nums_len): if nums[i] % 2 == 0: index += 1 nums[index], nums[i] = nums[i], nums[index] def order_even_first_odd_last_v2(nums: list) -> None: i, j = 0, len(nums) - 1 w...
def selection_sort(numbers): len_numbers = len(numbers) for i in range(len_numbers): min_idx = i for j in range(i + 1, len_numbers): if numbers[min_idx] > numbers[j]: min_idx = j numbers[i], numbers[min_idx] = numbers[min_idx], numbers[i] return numbers
import string import numpy as np import re def is_numeric(input_val): """Checks if a given input value is numeric. Parameter: --------- int_val: ideally an integer or float, but can be objects of any type. Returns: ------- True, if int_val can be converted to...
class Interval(): def __init__(self, start, end): self.start = start self.end = end def print_interval(self): print('[' + str(self.start) + ', ' + str(self.end) + ']', end = '')
def sieve_of_erastosthenes(n): # Create a boolean array of entries a True value means the number is prime prime = [True for i in range(n+1)] p = 2 while (p * p <= n): # Check if the current number is prime if prime[p - 1] == True: # Update all multiples of p starting from p^2...
# list of products products = ['table', 'chair', 'sofa', 'bed', 'lamp'] # list of prices prices = [50, 20, 200, 150, 10] # iterator of tuples - containing each tuple a product and its price print(zip(products, prices)) # <zip at 0x1ab80c8b788> # to visualize the iterator we have to convert it into a list print(list(...
# ask the user to input a name name = input('Enter your name: ') # use the name in the following greeting print('Hello {}'.format(name)) # Hello Amanda
# open a file in reading mode f = open('reading_lines.txt', 'r') first_line = f.readline() print(first_line) # First line second_line = f.readline() print(second_line) # Second line third_line = f.readline() print(third_line) # Third line # close the file to avoid running out of file handles f.close()
a = [5,10,15,20,25] def findFirsLast(): b = [a[0],a[-1]] return b print(findFirsLast())
p1 = { "name": "Huy", "Hours": 30, "VND per hour": 50 } p2 = { "name": "Quan", "Hours": 20, "VND per hour": 40 } p3 = { "name": "Duc", "Hours": 15, "VND per hour": 35 } person = [p1, p2, p3] print(person) t = 0 for h in person: print("Gio lam cua", h["name"], h["Hours"]) l ...
from random import randint x = randint(0,100) cloud = ''' .-~~~-. .- ~ ~-( )_ _ / ~ -. | \ \ .' ~- . _____________ . -~ ''' if x < 30: print("Rainy") elif x < 60: print(cloud) else: print("Sunny")
filename = 'alice.txt' try: with open(filename, encoding="utf-8") as f_obj: contents = f_obj.read() except FileNotFoundError: msg = "Sorry, the file " + filename + " does not exist." print(msg) else: words = contents.split() num_words = len(words) print(num_words)
print("Tell me two numbers and I'll add them together for you") print("Enter 'q' to quit") while True: try: spam = input("\nYour first number: ") if spam == 'q': break spam = int(spam) egg = input("\nYour second number: ") if egg == 'q': break egg = int(egg) except ValueError: print...
import unittest from city_functions import get_city_country class CitiesTestCase(unittest.TestCase): """Tests for 'city_functions.py""" def test_city_country(self): """Do cities like 'Santiago, Chile' work?""" city_country = get_city_country('santiago', 'chile') self.assertEqual(city_country, 'Santiago, Chi...
filename = 'programming_poll_results.txt' with open(filename, 'a') as file_object: prompt = "\nCould you tell use why you like programming?" prompt += "\nWrite 'no' if you don't want to answer.\t" active = True while active: response = input(prompt) if response == 'no': active = False else: ...
# more letter case practice and white space manipulation persons_name = "Butthead McGee" print("Fuck off, " + persons_name) another_name = "face of bogue" print(another_name.upper()) print(another_name.lower()) print(another_name.title()) quote_one = 'Dorothy remarked to her dog, “Toto, I\'ve got a feeling we\'re no...
from collections import OrderedDict # ~ favorite_languages = OrderedDict() # ~ favorite_languages['jen'] = 'python' # ~ favorite_languages['sarah'] = 'c' # ~ favorite_languages['edward'] = 'ruby' # ~ favorite_languages['phil'] = 'python' # ~ for name, language in favorite_languages.items(): # ~ print(name.title() +...
#purpose: to provide a single call to get the ip and port of a system by Name def getAddr(name): import json jfile = open('/var/www/NewControl/config/systems.json', 'r') #reads the json file storing all systems and passports jsonList = json.loads(jfile.read()) #parses the json into something useable system = jsonL...
class Counties: def __init__(self): print("Construction Counties") def is_bay_area(self, city): if (city == "san francisco" or self.is_san_mateo_county(city) or self.is_santa_clara_county(city) or self.is_marin_county(city) or self.is_napa_county(city) or self.is_solano_county(ci...
""" Populates the games table of the database """ import urllib.request from bs4 import BeautifulSoup from datetime import datetime from time import sleep import constants import psycopg2 def parse_game_titles(text_data): """ Retrieves all the info associated with each game from input text :param tex...
while True: L, R = input().split() L = int(L) R = int(R) if L == 0 and R == 0: break print(L + R)
# -*- coding: utf -8 -*- while True: K = int(input()) if (K == 0): break N, M = input().split() N = int(N) M = int(M) for i in range(K): X, Y = input().split() X = int(X) Y = int(Y) if (X == N or Y == M): print('divisa') elif (X > N and Y > M): print('NE') elif (X > N and Y < M): pr...
#!/usr/bin/env python3 import exp def fermat_test(base, prime): p1 = prime - 1 if exp.fast(base, p1, prime) == 1: return True else: return False def get_s_d(n): d = n - 1 s = 0 while not (d & 1): # addig megyünk amíg páratlan nem lesz d = d >> 1 # osztás kettővel s = s + 1 # megszámoljuk hányszor...
diccionario = dict() #Constructor diccionario["nombre"] = 'Misael' diccionario["edad"] = 26 diccionario['sexo'] = 'Masculino' print(diccionario) cuenta = dict() names = ['Juan', 'Lara', 'Juan', 'Brainy', 'Anush', 'Juan', ] for name in names: cuenta[name] = cuenta.get(name, 0) + 1 #if name not in cuenta: ...
import sys cookbook = { "sandwich": { "ingredients": ["ham", "bread", "cheese", "tomatoes"], "meal": "lunch", "prep_time": 10, }, "cake": { "ingredients": ["flour", "sugar", "eggs"], "meal": "dessert", "prep_time": 60, }, "salad": { "ingredi...
import sys list = sys.argv[1:] str = ' '.join(list).swapcase()[::-1] print(str)
bucket_list = ['sand', 'water', 'gravel', 'rocks', 'sea water', 'dirt', 'grass', 'air', 'sticks', 'leaves'] print(bucket_list) print(len(bucket_list)) print(bucket_list[0]) print(bucket_list[1]) bucket_list.append('fish') print(bucket_list[-1]) bucket_list[2] = 'stones' print(bucket_list)
import sys phrase = sys.argv if (len(phrase) > 2): print("ERROR") elif (len(phrase) == 1) : exit elif(phrase[1].isnumeric()) : num = int(phrase[1]) if (num == 0): print("I'm Zero") elif (num % 2 ): print("I'm Odd") else: print("I'm Even") else: print("ERROR")
class Pokemon: sound="sound" def __init__(self,name,level): if name=="": raise ValueError("name cannot be empty") if level<=0: raise ValueError("level should be > 0") self._name=name self._level=level def __str__(self): return "{} {} {...
from math import sqrt def linear(message): nums = message.split() try: a = float(nums[0]) b = float(nums[1]) c = float(nums[2]) d = float(nums[3]) except IndexError: return "Ви ввели недостатню кількість цифр" except ValueError: return "Треба вводити циф...
# -------------- # Importing header files import numpy as np import pandas as pd from scipy.stats import mode import warnings warnings.filterwarnings('ignore') #Reading file #Original var = bank_data bank = pd.read_csv(path) #Code starts here #Step 1 - Seggregating the Categorical and Numerical co...
num = input() while True: print("****** 홍익 대학교 과일 판매머신 V01 ******") print("1. orange : 1000 원") print("2. strawberry : 2500 원") print("3. peach : 1500 원") print("4. mango : 2000 원") print("5. grape : 2000 원") if int(num) == 1 p...
menu = ["orange", "strawberry", "peach", "mango", "grape", "종료"] price = [1000,2500,1500,2000,2000] while True: print("****** 홍익 대학교 과일 판매머신 V03 ******") for num in range(6): print("%d.%s"%(num,menu[1])) print("=======================================") num = int(input("구매 번호를 입력하세요 ( 1~6 )")) if num ...
for a in range(2,10): print("# %d 단" %a,end=" ") print("") print("="*78) for gu1 in range(2,10): for gu2 in range(2,10): print("%dx%d = %2d"%(gu2,gu1,gu2*gu1),end=" ") print("") print("-"*78)
class WriteToFile: # Here will be the instance stored. file = "" file_path = "resource/" directory = "" file_name = "" def __init__(self,directory,file_name): self.directory = directory self.file_name = file_name def write_to_file(self,log_item): if self.file == ""...
import numpy as np from sklearn.cross_validation import train_test_split import matplotlib.pyplot as plt from sklearn import linear_model from sklearn import datasets np.set_printoptions(threshold = 5) iris = datasets.load_iris() iris_X = iris.data iris_Y = iris.target ar_train, ar_test = train_test_split(iris_X, tes...
### calculate sum of squared integers from 1 to n ### using for loop def sum_sq(n): s = 0 for i in range(1, n + 1): s = s + i**2 return s def sum_sq2(n): s = 0 for i in range(1, n + 1): s = s + pow(i, 2) return s print(sum_sq(2)) print(sum_sq(5)) print(sum_sq(10...
from random import randint from time import sleep print('Game Pedra/Papel/Tesoura\n[1] - Pedra\n[2] - Papel\n[3] - Tesoura') jog = int(input('Escolha sua opção [1, 2 ou 3]: ')) pc = randint(1,3) opcoes = ['Pedra', 'Papel', 'Tesoura'] print('Pedra...') sleep(1) print('Papel...') sleep(1) print('Tesoura...') if pc == ...
from time import sleep def contagem(inicio, final, passo): print(f'Contagem de {inicio} até {final} de {passo} em {passo}:') sleep(1) if inicio < final: for i in range(inicio, final+passo, passo): print(f'{i} ', end='') else: for i in range(inicio, final-passo, -passo): print(f'{i} ', end=...
num = input('Informe um número: ') print('Analisando o número {}'.format(num)) print('Unidades: {}'.format(num[len(num)-1])) print('Dezenas: {}'.format(num[len(num)-2])) print('Centenas: {}'.format(num[len(num)-3])) print('Milhares: {}'.format(num[len(num)-4]))
from datetime import date menores = 0 maiores = 0 for i in range(1, 8): nascimento = int(input('Data de nascimento da {}ª pessoa: '.format(i))) idade = date.today().year - nascimento if idade < 18: menores += 1 else: maiores += 1 print('Temos {} pessoa(s) menores e {} pessoa(s) maiores de idade.'.f...
numeros = [[],[]] for i in range(1, 8): numero = int(input(f'Insira o {i} número: ')) if numero%2 == 0: numeros[0].append(numero) else: numeros[1].append(numero) print('-'*40) numeros[0].sort() numeros[1].sort() print(f'Os valores pares digitados foram: {numeros[0]}') print(f'Os valores ímpares digitad...
from random import randint while True: pc = randint(0,10) numero = int(input('Insira um número: ')) total = numero+pc palpite = str(input('A soma será Par ou Ímpar? [P/I]: ')).strip().upper()[0] if total%2 == 0: if palpite == 'P': print(f'Ganhou!\nVocê: {numero}\nComputador: {pc}\nTotal:{total} ->...
total = quantidade = maior = menor = 0 controle = True while controle: numero = int(input('Insira um número: ')) total += numero quantidade += 1 if quantidade == 1: maior = numero menor = numero elif numero > maior: maior = numero elif numero < menor: menor = numero opcao = str(input('D...
from random import randint print('-=-'*9) print('Acerte o número de 0 á 5') print('-=-'*9) num = int(input('Adivinhe o número sorteado: ')) sorteado = randint(0,5) if num == sorteado: print('Acertou! Você colocou {} e foi sorteado {}.'.format(num, sorteado)) else: print('Errou! Você colocou {} e foi sorteado {}....
dados = [] while True: novo_dado = int(input('Digite um valor: ')) dados.append(novo_dado) opcao = str(input('Deseja continuar [S/N]: ')).strip().upper()[0] if opcao == 'N': break dados.sort(reverse=True) print(f'Você digitou {len(dados)} valor(es).') print(f'Os valores em ordem decrescente são: {da...
num1 = float(input('Digite o primeiro valor: ')) num2 = float(input('Digite o segundo valor: ')) num3 = float(input('Digite o terceiro valor: ')) menor = num1 maior = num1 if num2 <= menor: menor = num2 else: maior = num2 if num3 <= menor: menor = num3 else: maior = num3 print('O menor valor é {:.0f}.'.form...
salario = float(input('Qual o salário do funcionário? R$ ')) reajuste = salario*0.15 print('O funcionário que ganhavara R$ {:.2f}, com 15% de aumento, passa a receber {:.2f}' .format(salario, reajuste+salario))
matriz = [] vetor = [] pares = coluna = linha = 0 for i in range(0, 3): for k in range(0, 3): n = int(input(f'Insira um valor para [{i}][{k}]: ')) vetor.append(n) if n%2 == 0: pares += n if k == 2: coluna += n if i == 1: linha += n matriz.append(vetor[:]) vetor.clear() ...
def analise(*valores): maior = 0 for value in valores: if value == 0: maior == value elif value > maior: maior = value print('-'*30) print(f'Foram analisados {len(valores)} valores.') print(f'O maior valor é: {maior}.') analise(4,3,4,5,2,0) analise(1,7,9,20) analise(2,8) analise(5)
def dobro(preco, show_cifrao): resultado = preco*2 if show_cifrao: return cifrao(resultado) else: return resultado def metade(preco, show_cifrao): resultado = preco/2 if show_cifrao: return cifrao(resultado) else: return resultado def porcentagem(preco, porcentagem, reduzir=False, show_c...
def weight_on_planets(): #Get the user input for his/her weight print("What do you weigh on earth?", end = '') userWeight = input() userWeight = float(userWeight) # Calculations marsWeight = (userWeight * 0.38) jupiterWeight = (userWeight * 2.34) print(" \n" + "On Mars you would weigh...
import readline from builtins import input as dumb_input from time import strptime def year_type(value): return strptime(value, '%Y').tm_year def input(prompt, convert_to = str, enum = None, maxretry = 3): prompt, convert_to = make_prompt(prompt, convert_to, enum) for i in range(maxretry): try: ...
""" Module defines various decorators we can assign to given module functions so that we have a nice pluggable interface for expanding the bots abilities and functions in a way that doesn't actually mean we have to hack apart the core bot code. """ def pubmsg(): """ Decorator :return: """ def ad...
""" Se dau trei numere. Să se afişeze aceste numere unul sub altul, afişând în dreptul fiecăruia unul dintre cuvintele PAR sau IMPAR. Exemplu : Date de intrare : 45 3 24 Date de ieşire : 45 impar 3 impar 24 par. """ a=int(input("Introduceti primul numar:")) b=int(input("Introduceti al doilea numar:")) c=int(input("I...
favorite_pizzas = ['pepperoni', 'sausage', 'deep dish'] # Prints the names of all the pizzas. for pizza in favorite_pizzas: print(pizza) print("\n") # Prints a sentence about each pizza. for pizza in favorite_pizzas: print(f"I really love {pizza} pizza!") print("\nI really love pizza!")
rivers = { 'nile': 'egypt', 'amazon': 'brazil', 'mississippi': 'America' } for name, river in rivers.items(): print(f"The {name.title()} river runs through {river.title()}.") print() print("Countries:") for country in rivers.values(): print(country.title()) print() print("Rivers:") for name...
from rich import print from rich.console import Console from rich.table import Table import or_player from or_player import player oxen_total = 0 food_total = 0 clothes_total = 0 bullets_total = 0 parts_total = 0 def oxen(): while True: print("\n[cyan italic]There are 2 oxen in a yoke;\n\ I recommend at ...
def make_sandwich(*items): """Make a sandwich with the given items.""" print("\nLet's make a sandwich") for item in items: print(f" ...adding {item} to your sandwich.") print("Your sandwich is ready!") make_sandwich('roast beef', 'chicken', 'lettuce', 'tomato') make_sandwich('turkey', 'cheddar...
# Course: CS 30 # Period: 1 # Date Created: 21/01/29 # Date last Modified: 21/01/29 # Name: Jack Morash # Description: Creates a simple multiple choice menu for direction and actions # Defines a formatted menu for directions def print_directions(): print(30 * "-", "DIRECTIONS", 30 * "-") print("1. North\n2. ...