text
stringlengths
37
1.41M
def fact(n): f=1 for i in range(1,(n+1)): f=f*i return f for i in range(1,6): print ("Factorial of ", i , " is ", fact(i))
#Задача 5. Вариант 11. #Напишите программу, которая бы при запуске случайным образом #отображала имя одного из девяти оленей Санта Клауса. #Крутова Дарья #15.09.2016 import random oleni = ['Dasher', 'Prancer', 'Vixen', 'Comet', 'Cupid', 'Donder', 'Blitzen', 'Rudolph'] olen = random.ch...
class Employee: num_of_employee = 0 raise_amount =1.04 #class variable def __init__(self, firstName, lastName, pay): #constructor # instance variables self.firstName = firstName self.lastName = lastName self.pay = pay self.email = firstName + '.' + lastName + '@company.com' Employee.num_of_employee +...
# This file will play a tic tac toe game def main(): tic_tac_toe() if __name__ == '__main__': main() # functions are need def tic_tac_toe(): curr_board = initial_board() # This will generate a board print_board(curr_board) lst_pl1 = [] lst_pl2 = [] while win is False: player1 =...
""" Python code to demonstrate naive method to compute zip """ def my_zip(lst1, lst2): new_list = [] for x in range(0, len(lst1)): new_list.append((lst1[x], lst2[x])) return new_list def my_zip2(lst1, lst2): return list(map(lambda x, y: (x, y), lst1, lst2)) def my_zip3(lst1, lst2): ...
def my_range(start: int, end: int = None, step: int = None): """ Python code to demonstrate naive method to compute range """ if step is None: step = 1 if end is None: start = 0 end = start if type(end) != int or type(start) != int or type(step) != int: raise ...
# -*- coding: utf-8 -*- """ Created on Mon Sep 10 22:28:07 2018 @author: hashimoto """ import pandas as pd xls_input = pd.read_excel('第3表.xls', skiprows=3, # 先頭3行無視 skip_footer=2, # 末尾2無視 parse_cols='W,Y:AJ', index_col...
class MyBase: coeff = 2 def __init__(self,x): self.x = x def mult(self): return self.coeff * self.x class MyDeriv(MyBase): coeff = 3 def __init__(self, x, y): super().__init__(x) self.y = y def mult2(self): ret...
# Simulador de Árbitro de Barramento # Entradas n_perifericos = int(input('Insira a quantidade de perifericos: ')) perifericos = [] print('\nInforme quais são os perfirecos:') for i in range(0,n_perifericos): perifericos.append(int( input() )) periferico_prioridade = {} print('\nInforme a prioridade de cada ...
inteiro = int(input("Digite um inteiro:")) if inteiro % 3 == 0 and inteiro % 5 == 0: print("FizzBuzz") else: print(inteiro)
import math class Bhaskara: ## Functions def delta(self, a, b, c): return int((b ** 2 - 4 * a * c)) # Inputs def main(self): a = float(input('Digite "a":')) b = float(input('Digite "b":')) c = float(input('Digite "c":')) print(self.calcula_raizes(a, b, c)) ...
def ordenada(lista): ordem = True for index in range(len(lista)-1): if lista[index] > lista[index + 1]: ordem = False return ordem
inteiro = int(input("Digite um número inteiro: ")) i = 1 if inteiro > 1: for i in range(2, inteiro): if (inteiro % i) == 0: print("não primo") break else: print("primo") else: print("não primo")
import math a = float(input('Digite "a":')) b = float(input('Digite "b":')) c = float(input('Digite "c":')) delta = b**2 - 4*a*c def raiz1(a,b,delta): raiz = (-b + math.sqrt(delta)) / (2 * a) return raiz def raiz2(a,b,delta): raiz = (-b - math.sqrt(delta)) / (2 * a) return raiz if delta == 0: pr...
import math class Triangulo: def __init__(self, a, b, c): self.a = a self.b = b self.c = c def retangulo(self): if math.sqrt(self.a**2 + self.b**2) == self.c: return True return False # t = Triangulo(1, 3, 5) # print(t.retangulo()) # # deve devolver Fal...
from dna import DNA import random import math class Population(): def __init__(self, strength, mutation_rate, aim): self.strength = strength self.mutation_rate = mutation_rate self.aim = aim self.population = [] def get_strength(self): return self.strength def get...
class Grunts: """Modeling a Grunt enemy.""" def __init__(self, name, rank, type, armor_color, shield, grenade_count, shield_strength, health_points, points, *weapon): """Establish the attributes of a Grunt.""" self.name = name.title() self.rank = rank.title() se...
import os import random from .Game import Game class TicTacToe(Game): def __init__(self): """ TicTacToe Game """ super(TicTacToe, self).__init__() self.playerLetter = 'X' self.computerLetter = 'O' @staticmethod def clear(): """ Clear console/terminal """ i...
import json import time """ Miscellaneous functions unrelated to making the tree """ def loadWords(filepath): """ loads words from filepath """ with open(filepath) as f: return json.load(f) def possibleWords(substr, word_list): """ given a substring, returns a list of all possible words with that sub...
# Uses python2 import sys def binary_search(array, x): high = len(array) - 1 # Offset to handle zero indexed array low = 0 while low <= high: mid = (low + high) / 2 if x == array[mid]: return mid elif x < array[mid]: high = mid - 1 elif x > array[mi...
# Uses python2 import sys """ A natural subproblem in this case is the following: C(n) is the minimum number of operations required to obtain n from 1 (using the three primitive operations). How to express C(n) through C(n/3), C(n/2), C(n - 1)? QUESTION How many operations required to go from C(n - 1) to C(n)? ANSW...
class Queue: def __init__(self): self.items = [] self.consumerTime = 0 self.producerTime = 0 self.graphTime = 0 self.numberOfItemsSent = 0 self.numberOfItemsConsume = 0 def isEmpty(self): return len(self.items) < 3 def enqueue(self, item): se...
import math p1 = math.radians(float(input("Enter latitude 1: "))) m1 = math.radians(float(input("Enter longtitude 1: "))) p2 = math.radians(float(input("Enter latitude 2: "))) m2 = math.radians(float(input("Enter longtitude 2: "))) R = 6372.8 dp = p2 - p1 dm = m2 - m1 a = (math.sin(dp/2))**2 + math.cos(...
# 3.1 (Validating User Input) Modify the script of Fig. 3.3 to validate its inputs. For any # input, if the value entered is other than 1 or 2, keep looping until the user enters a correct # value. Use one counter to keep track of the number of passes, then calculate the number # of failures after all the user’s inp...
#Insertion sort import random def sort(array): for i in range(len(array)): valueToInsert = array[i] holePos = i while(holePos > 0 and valueToInsert < array[holePos - 1]): array[holePos] = array[holePos - 1] holePos = holePos - 1 array[holePos] = valueToInsert return array def main(): print '***********...
# 집합 (set) # 집합 (set) 자료형 (순서x, 중복x) #선언 a = set([]) print(type(a)) b = set([1, 2, 3, 4]) c = set([1, 4, 5, 6]) d = set([1, 2, 'pen', 'cap', 'Plate']) e = {'foo', 'bar', 'baz', 'fodd', 'qux'} #-> 키없이 나열하면 셋임! f = {42, 'foo', (1, 2, 3), 3.141234} print('a - ', type(a), a) print('b - ', type(b), b) print('c - ', type(...
# while문 customer = '토르' index = 5 while index >= 1: print('{0}, 커피가 준비 되었습니다. {1} 번 남았어요.'.format(customer, index)) index -= 1 if index == 0: print('커피 아웃입니다.') customer = '아이언맨' index = 1 while True: print('{0}, 커피가 준비 되었습니다. 호출 {1} 회.'.format(customer, index)) index += 1 customer = '...
# 표준 입출력 import sys print('python', 'java', sep=' vs ') print('python', 'java', sep=' , ', end='?') # end : 문장의 끝 부분을 변경 & 문장 한 줄로 붙임 print(' 무엇이 더 재밌을까요?') print('python', 'java', file=sys.stdout) # 표준 출력 print('python', 'java', file=sys.stderr) # 표준 에러 # 시험 성적 scores = {'수학':0, '영어':50, '코딩':100} for subject, sc...
# chapter03-01 # 숫자형 # 파이썬 지원 자료형 """ int : 정수 float : 실수 complex : 복소수 bool : 불린 str : 문자열 (시퀀스) list : 리스트 (시퀀스) tuple : 튜블(시퀀스) set : 집합 dict : 사전 """ # 데이터 타입 str1 = "Python" bool = True str2 = 'Anaconda' float_v = 10.0 # 10 == 10.0 false int_v = 7 list = [str1, str2] print(list) dict = { "name": "Machine L...
# First Option with one string #data="Hello Python" #print(data) # Second option # We can store a string in double quotes in whole single quote string and vise versa #myURL='www."gmail".com' #print(myURL) # now Three quotes"""- for the multiple line #myURL=""" # This is my python program # website is "www.pytho...
# syntax # for i in range(10, 5, -2): # print(i) # taking input from user number = input("Please enter the number : ") for i in range(10, 0, -1): print(int(number)*i)
list1=[23, 33.4, "Testing", 55, 66, "World"] # Here I am fetching by index #print(list1[1]) # Range of Index # print(list1[3:5]) # We are going to give starting index #print(list1[2:]) # We are going to give End index #print(list1[:4]) # Update any data in list #list1[3]=100 #print(list1[3]) # insert a value # li...
#i = 5 # initialize the value #while (i < 10): # Run this loop till its meets criteria # print(i) # Printing the value # i += 1 # to increment the value and its similar to i=i+1 # number for the user number=input("Please enter the number : ") i=1 while (i<10): print(int(number)* i) i+=1
import numpy as np import random def create_board(): return np.zeros((3,3)) def place(board, player, position): if board[position] == 0: board[position] = player board = create_board() place(board, 1, (0, 0)) def possibilities(board): return list(zip(np.where(board == 0)[0], np.where(board == 0)...
num1=int(input("Enter 1st no.")) num2=int(input("Enter 2nd no.")) num3=int(input("Enter 3rd no.")) if(num1>num2 and num1>num3): print("{0} is greatest.".format(num1)) elif(num2>num1 and num2>num3): print("{0} is greatest.".format(num2)) else: print("{0} is greatest.".format(num3))
n = input () flag = 0 while n > 1: if n % 2 == 0: n /= 2 else: print "NIE" flag = 1 break if flag == 0: print "TAK"
def Combo(nums, target): res = [] nums.sort() dfs(nums, target, 0, [], res) return res def dfs(nums, target, index, path, res): if target <0: return if target == 0: res.append(path) else: for i in range(index, len(nums)): if i > 0 and nums[i] == nums...
def plus_one(num): flag = 1 for i in num: if i != 9: flag = 0 if flag == 1: num[0] = 1 for i in range(1,len(num)): num[i]=0 num.append(0) return num def plusone(num): number = 0 for digit in num: number = number*10 + digit ret...
from BST import Binary_Tree def level_order(r): stack = [] stack.append(r.root) answer =[[r.root.value]] count = 1 while stack: temp = stack.pop(0) if temp.left: stack.append(temp.left) if temp.right: stack.append(temp.right) count = count -1 ...
def steal_values(num): choose={} for i in range(len(num)): val = num[i] if i>0 and i <len(num)-1 and val > num[i+1] + num[i-1]: choose[i] = val elif i ==0 and val > num[i+1]: choose[i] = val elif i == len(num)-1 and val > num[i-1]: choose[i] = ...
def first_missing_positive(num): num.sort() for i in range(0,len( num)): if num[i] <=0: continue if num [ i] != num[i-1]+1: return num[i-1]+1 return -1 print(first_missing_positive([0,-1,2,3]))
def rotate_list(num,k): result = num[k:] + num[:k] return result print(rotate_list([1,2,3,4,5],2))
class ListNode(object): def __init__(self, x): self.val = x self.next = None def addTwoNumbers( l1, l2): l1 = l1[::-1] l2 = l2[::-1] for i in range(max(len(l2),len(l1))): if l2[i] and l1[i]: answ[i] = l2[i] + l1[i] elif l2[i]: ...
class ListNode(object): def __init__(self, x): self.val = x self.next = None def swapPairs(head): prev_head = ListNode(-1) prev_head = head.next while head!=None and head.next!=None: temp = head.next.next head.next.next = temp.next swap = head.next swap...
class ListNode(object): def __init__(self, x): self.val = x self.next = None def mergeKLists(l): merge =[] for i in l: while i: merge.append(i.val) i = i.next merge.sort() merged_list = ListNode(-1) prev = ListNode(-1) prev.next = merged_li...
''' 30th Jan 2021''' ''' A multi-player dice game ''' ''' You can choose howevermany players you want to play in the game ''' ''' One Edge case when all values are the same still needs to be resolved''' import random def find_winner(arr): l = len(arr) win_val = 0 for i in range(0, l): if arr[i] < ...
import math import string import sys l = [] l.c def read_file(filename): try: fp = open(filename) L = fp.readlines() except IOError: print "Error opening the file", filename sys.exit() return L def get_words_from_string(line): """ Return a list of the words in th...
#author:ChaozhuangZHANG #complexity:o(nlogn) #language:python #description of the question: ''' A peak element is an element that is greater than its neighbors. Given an input array where num[i] ≠ num[i+1], find a peak element and return its index. ''' class Solution(object): def findPeakElement(self, nums): ...
''' Домашнее задание ко второму уроку ''' ''' Задача 1 Вывести на экран циклом пять строк из нулей, причем каждая строка должна быть пронумерована. ''' # i = 1 # while i<6: # print(i, '00000000000000000000') # i=i+1 ''' Задача 2 Пользователь в цикле вводит 10 цифр. Найти количество введеных пользователем цифр...
inputs = [line.rstrip('\n') for line in open("inputs/03.txt")] def one(): intersects = [] for string in inputs: half = len(string) // 2 one = string[:half] two = string[half:] intersects.append([element for element in one if element in two]) counter = 0 ...
""" 쉽게 설명한 병합 정렬 입력: 리스트 a 출력: 정렬된 리스트 """ def merge_sort(a): n = len(a) # 종료 조건: 정렬할 리스트의 자료 개수가 한 개 이하이면 정렬할 필요 없음 if n <= 1: return a # 그룹을 나누어 각각 병합 정렬을 호출하는 과정 mid = n // 2 # 중간을 기준으로 두 그룹으로 나눔 group_1 = merge_sort(a[:mid]) # 재귀 호출로 첫 번째 그룹을 정렬 group_2 = merge_sort(...
def main(): """ 元组中的元素是无法修改的,事实上我们在项目中尤其是多线程环境 中可能更喜欢使用的是那些不变对象 (一方面因为对象状态不能修改,所以可以避免由此引起的不必要的程序错误,简单的说就是一个不变的对象要比可变的对象更加容易维护; 另一方面因为没有任何一个线程能够修改不变对象的内部状态,一个不变对象自动就是线程安全的, 这样就可以省掉处理同步化的开销。一个不变对象可以方便的被共享访问)。 所以结论就是:如果不需要对元素进行添加、删除、修改的时候,可以考虑使用元组,当然如果一个方法要返回多个值,使用元组也是不错的选择。 元组在创建时间和占用的空间上面都优...
#!/usr/bin/env python3 __author__ = 'luoshun' class Student(object): #可读属性 @property def score(self): return self.__score #可写属性 @score.setter def score(self,value): self.__score = value #可读属性 @property def age(self): return 2015-self.__score s = Student() print('input your score') s1=input() s.score = in...
import csv # The DictWriter and The DictReader is not covered # In this example def write_csv(data, filename): if filename[-4:] != '.csv': filename += '.csv' if type(data) not in (type([]), type(())): print(type(data)) raise TypeError with open(filename, 'w', newli...
#!/usr/bin/env python3 """ Bradley N. Miller, David L. Ranum Problem Solving with Algorithms and Data Structures using Python Copyright 2005 Updated by Roman Yasinovskyy, 2017 """ class Deque: """Queue implementation as a list""" def __init__(self): """Create new deque""" self._items = [] ...
"""Unit testing for inheritance """ import unittest class InheritanceTesting(unittest.TestCase): def test_methods(self): class Base(object): def myfunc(self): return "Base.myfunc" def stuff(self): return "Base.stuff" self.myfunc() ...
#!/usr/bin/env python3 """ Bradley N. Miller, David L. Ranum Problem Solving with Algorithms and Data Structures using Python Copyright 2005 Updated by Roman Yasinovskyy, 2017 """ from pythonds3.trees.binary_heap import BinaryHeap class PriorityQueue(BinaryHeap): """ This implementation of binary heap takes ...
import unittest class ExceptionTest(unittest.TestCase): def test_finally(self): finally_ran = False try: pass finally: finally_ran = True self.assertTrue(finally_ran) finally_ran = False try: raise Exception() except: pass else: self.assertFalse(True, "'else' should not fire if except...
"""Unit test for biwise operators""" import unittest class OperatorsTest(unittest.TestCase): def test_bitwise_and(self): self.assertEqual(5&7, 5) x = 5 x &= 7 self.assertEqual(x, 5) self.assertEqual(0b1111 & 0b0001, 0b0001) self.assertEqual(0O7740 & 0O7400, 0O7400) ...
# Bradley N. Miller, David L. Ranum # Solución de problemas con algoritmos y estructuras de datos usando Python # Copyright 2014 # #arbolBinario.py class ArbolBinario: def __init__(self,objetoRaiz): self.clave = objetoRaiz self.hijoIzquierdo = None self.hijoDerecho = None def inse...
# simple one-to-one RNN experiment that takes in a word and learns to predict the next word but # without a continuing state # quick tutorial: https://pytorch.org/tutorials/beginner/nlp/sequence_models_tutorial.html # difference between LSTM and LSTMCell: https://stackoverflow.com/questions/57048120/pytorch-lstm-vs-lst...
nome = raw_input('digite o seu nome: ') idade = int(raw_input('digite a sua idade: ')) print 'Bom dia, ' + nome + '! ' + 'Ano passado voce tinha ' + str(idade-1) + ' anos!'
entrada = raw_input() numerosComoString = entrada.split(" ") numeros = [int(numero) for numero in numerosComoString] c, n = numeros print c % n
n = int(raw_input('digite um numero: ')) if ((n%2)==0): print str(n) + ' e par!' else: print str(n) + ' e impar!' if (n>10): print str(n) + ' e maior que 10!' elif (n<10): print str(n) + ' e menor que 10!' else: print str(n) + ' e igual a 10!' temp = int(raw_input('Entre com a temperatura: ')) if temp...
# coding : utf-8 import sqlite3 class ChessBoard(object): """docstring for ChessBoard""" def __init__(self, arg): super(ChessBoard, self).__init__() self.arg = arg def printBoard(chessbook): # 1|2|3 # 4|5|6 # 7|8|9 print "{0}|{1}|{2}\n{3}|{4}|{5}\n{6}|{7}|{...
import sys import numpy as np intToPlayer = {0: ' ', 1: 'X', 2: 'O'} def main(): sys.stdout.write("Let's play tic-tac-toe!\n") game() def game(): board = np.zeros((3, 3), dtype=int) hasWon = isWinScenario(board) while not hasWon: turn(1, board) print_board(board); hasWon =...
l = range(5) print l print l * 5 l[0] = 1 print l print l[2] print l[2L] l[:] = l l = range(5) while l: print l.pop() l = range(7, -1, -2) print sorted(l) print l l = range(5) l[0] = l print l for i in xrange(-10, 10): l2 = range(5) l2.insert(i, 99) print i, l2 for i in xrange(-5, 4): l3 = rang...
#Exception Handling # Divide by zero try: x = 5/0 except: print("Error dividing by zero") # Summary: "Try" lets you run code that might be contain an error, "except" lets you catch the error. # Handling number conversion errors try: x = int("fred") except: print("Error converting fred to a number") #...
#!/usr/bin/env/python for name in ("Manny!", "Moe!", "Jack!"): print 'Hi ya ', name for name in ("Manny!", "Moe!", "Jack!"): print 'Hi ya ', name
#!/usr/bin/env python3 from heapq import * class max_heap1(): def __init__(self): self.l = [] def heappush(self, item): heappush(self.l, -item) def heappop(self): x = heappop(self.l) return -x def heapsize(self): return len(self.l) def heappeek(self): ...
#!/usr/bin/env python3 def power(base, exp): res = 1 orig_base=base orig_exp = exp while exp: print(base, exp, res) if exp & 1: res = res * base base *= base exp = exp >> 1 print("Power(", orig_base,",",orig_exp,"):", res) power(3, 7)
#!/usr/bin/env python3 def find_minimum(arr): n = arr.size() if(n==1): return arr.get(0) if(n==2) { return Math.min(arr.get(0), arr.get(1)); } if(n==3) { return Math.min(arr.get(0), Math.min(arr.get(1), arr.get(2))...
#!/usr/bin/env python3 def second_smallest(A): cur = 0 potential = float('inf') while cur < len(A): l = left(cur) r = right(cur) if A[l] == A[cur]: equal_node = l other_node = r else: equal_node = r other_node = l if...
#!/usr/bin/env python3 def wildcard(s, res, idx): if idx == len(s): print(res) return #for i in range(idx, len(s)): i = idx cur_char = s[i] if cur_char == '?': wildcard(s, res+'0', i+1) wildcard(s, res+'1', i+1) else: res += cur_char wildcard(s...
#!/usr/bin/env python3 """ Given an array of n elements, where each element is at most k positions away from its target position, write an algorithm that sorts in O(n log k) time Input : arr[] = {6, 5, 3, 2, 8, 10, 9}, k = 3 Output : arr[] = {2, 3, 5, 6, 8, 9, 10} Input : arr[] = {10, 9, 8, 7, 4, 70, 60, 50}, k = 4...
#!/usr/bin/env python """ Stack class """ class Stack: def __init__(self): self.stack = [] print "Created stack" def push(self, elem): self.stack.append(elem) def pop(self): elem = 0 try: elem = self.stack.pop() except IndexError: ...
#!/usr/bin/env python3 def count_coin_change(T, D): n = len(D) res = [[0] * (T+1) for _ in range(n+1)] for i in range(n, -1, -1): for t in range(T+1): if i == n: res[i][t] = 0 elif t == 0: res[i][t] = 1 else: prin...
#!/usr/bin/env python3 class Node: def __init__(self, data): self.data = data self.left = None self.right = None def serialize(node, output): if not node: output.append(-1) return output.append(node.data) serialize(node.left, output) serialize(node.right, ...
#!/usr/bin/env python3 class Vertex: def __init__(self, label): self.label = label self.nbrs = [] def add_edge(self, node): self.nbrs.append(node) def explore(node, seen, comp): if node.label in seen: return seen.add(node.label) comp.append(node.label) for nb...
#!/usr/bin/env python3 def missing_elem_xor(a, k): n = len(a) xor_nums = 0 for i in range(k+1): xor_nums ^= i for i in range(n): xor_nums = a[i] ^ xor_nums print("missing_elem_xor:", xor_nums) def missing_elem_set(a, k): s = set() n = len(a) for i in range(n): ...
#!/usr/bin/env python3 from operator import itemgetter def getMergedIntervals(a1): # # Write your code here. # #a = sorted(a1, key=itemgetter(0)) a = sorted(a1, key=lambda x: x[0]) #print(a1) #a1.sort(key=lambda x: x[0]) #a = a1 #print(a) st, end = a[0] op = [] for st1...
#!/usr/bin/env python3 from tree_creation import print_level_tree class Node: def __init__(self, data): self.data = data self.left = None self.right = None def bst_sorted_arr(l, st, end): if st > end: return None mid = st + (end - st)//2 root = Node(l[mid]) root....
#!/usr/bin/env python3 from collections import deque from random import randint class Vertex: def __init__(self, data): self.data = data self.neighbors = [] def add_edge(self, a): self.neighbors.append(a) def dfs(node): seen = set() print("in dfs") def _dfs(node...
#!/usr/bin/env python3 def alternate(l): n = len(l) pi, ni = 0, 0 pos_list = [0] * n neg_list = [0] * n for i in range(n): if l[i] >= 0: pos_list[pi] = l[i] pi += 1 else: neg_list[ni] = l[i] ni += 1 i, j, k = 0, 0, 0 while i...
#!/usr/bin/env python3 class Node: def __init__(self, data): self.data = data self.prev = None self.next = None def printlist(head): print("List: [", end = '') while head: print(head.data, end=",") head = head.next print("]") n1 = Node(1) n2 = Node(2) n3 = Node...
f1 = str(input('Digite uma frase: ')).strip().lower() print('A letra A aparece {} vezes na frase.'.format(f1.count('a'))) print('A primeira letra A aparece na posição {}'.format(f1.find('a')+1)) print('A última letra A aparece na posição {}'.format(f1.rfind('a')+1))
maior = 0 menor = 0 for c in range(1, 6): peso = float(input(f'Peso da {c}° pessoa:')) if c == 1: maior = peso menor = peso else: if c > peso: maior = peso if c < peso: menor = peso print(f'O maior peso é {maior}Kg') print(f'O menor peso é {menor}Kg')
d1 = float(input('Quanto dinheiro você tem na carteira? R$')) s = d1 / 5.38 print('Com R${} você pode comprar US${:.2f}'.format(d1, s))
dist = int(input('Qual a distância da viagem? ')) print('Você está prestes a começar uma viagem de {}Km'.format(dist)) if dist > 200: print(f'O preço de sua viagem será de R${dist * 0.45:.2f}') else: print(f'O preço de sua viagem será de R${dist * 0.5:.2f}')
aluno = dict() aluno['nome'] = str(input('Nome: ')) aluno['média'] = float(input(f'Média de {aluno["nome"]}: ')) print('=-=' * 30) print(f'- nome é igual a {aluno["nome"]}') print(f'- média é igual a {aluno["média"]}') if aluno["média"] >= 7: print('- situação é igual a aprovado') if aluno["média"] >= 5 and aluno["...
valor = float(input('Qual o valor do imóvel? R$')) salario = float(input('Qual seu salário mensal? R$')) finan = int(input('Em quantos anos pretende financiar? ')) prest = valor / (finan * 12) max = salario * 0.3 print('Para pagar uma casa de R${:.2f} em {} anos, '.format(valor, finan), end='') print('o valor da presta...
n1 = int(input('Digite um número: ')) n2 = int(input('Digite outro número: ')) n3 = int(input('Digite mais um número: ')) n4 = int(input('Digite o último número: ')) tupla = (n1, n2, n3, n4) print(f'Você digitou os valores {tupla}') print(f'O valor 9 apareceu {tupla.count(9)} vezes.') if 3 in tupla: print(f'O valor...
n1 = str(input('Digite seu nome completo: ')).strip().capitalize() print('Muito prazem em te conhecer!') nome = n1.split() print('Seu primeiro nome é {}.'.format(nome[0])) print('Seu último nome é {}.'.format(nome[len(nome) - 1].capitalize()))
largura = float(input('Largura da parede: ')) altura = float(input('Altura da parede: ')) lxa = largura * altura print('Sua parede tem dimensão de {}x{} e sua área é de {}m².'.format(largura, altura, lxa)) print('Para pintar essa parede, você precisará de {}l de tinta'.format(lxa / 2))
user = input("Enter a string of positive integers seperated by spaces: ") print() num = user.split() t = 0 while t <len(num): num[t] = int(num[t]) t+= 1 for n in num: print(n*'*')
import unittest # m > 0, n > 0 def divide(m:int, n:int) -> int: i = 0 while m >= n: m -= n i += 1 return i class TestFunc(unittest.TestCase): def test1(self): m, n = 4, 2 self.assertEqual(divide(m, n), m//n) def test2(self): m, n = 213210909, 324324 ...
# Question 11:Write a program that accepts a sentence and calculate the number of letters and digits. # Suppose the following input is supplied to the program: # i/p: Hello Priya 1287 # o/p: LETTERS 10 # DIGITS 4 str=raw_input("enter string") d=l=0 for c in...
# Question 6: Write a program that takes inputs from user their name and their age. And display the year in which they will turn 100 years old import time import datetime Name=raw_input("Enter your Name:") Age=int(input("Enter your Age:")) #print '/n'Prac print 'Hi %s ,Your present Age is %d'%(Name,Age) #print '/...
"""Simulated Weather Data.""" import datetime import json import random LOCATIONS = ['Hitchin Weather Station', 'Ashwell', 'FBP Langford', 'Grosvenor Court', 'St. Martins, Isles of Scilly', 'Boswedden House'] class Sample: """Simulated weather sta...
import sys from histogram import Histogram class Listogram(list, Histogram): ''' Histogram Implemented with list of lists ''' def __init__(self, file=None): ''' Initializes new listogram instance ''' super(Listogram, self).__init__() ## inits new instance of listogram (list) #* Add type/token count to...