text
stringlengths
37
1.41M
"""15. Faa um Programa que pergunte quanto voc ganha por hora e o nmero de horas trabalhadas no ms. Calcule e mostre o total do seu salrio no referido ms, sabendo-se que so descontados 11% para o Imposto de Renda, 8% para o INSS e 5% para o sindicato, faa um programa que nos d: . salrio bruto. a. quanto pagou ao INS...
"""19. Faa um Programa que leia um nmero inteiro menor que 1000 e imprima a quantidade de centenas, dezenas e unidades do mesmo. o Observando os termos no plural a colocao do "e", da vrgula entre outros. Exemplo: o 326 = 3 centenas, 2 dezenas e 6 unidades o 12 = 1 dezena e 2 unidades Testar com: 326, 300, 100, 320, 310...
"""11. As Organizaes Tabajara resolveram dar um aumento de salrio aos seus colaboradores e lhe contraram para desenvolver o programa que calcular os reajustes. o Faa um programa que recebe o salrio de um colaborador e o reajuste segundo o seguinte critrio, baseado no salrio atual: o salrios at R$ 280,00 (incluindo) : a...
a = input("Digite a nota 1: ") b = input("Digite a nota 2: ") media = (float(a)+float(b))/2 if media==10: print("Aprovado com Distino") elif media>=7: print("Aprovado") else: print("Reprovado")
a = input("Digite um numero: ") b = input("Digite um numero: ") if a > b: print ("O maior numero digitado foi o",a) else: print ("O maior numero digitado foi o",b)
#!/usr/bin/python3 import os import sys import gradient_descent import random from collections import defaultdict vector_list = gradient_descent.theta def compute_vector(matrix_list, vector_list): alist = [] for row in range(len(matrix_list)): temp = 0 for col in range(len(matrix_list[row])): temp += flo...
#!/usr/bin/python3 import os import sys import random from collections import defaultdict def derivative_of_cost_function(x, y, dict_len, slope, segment): func = float(segment + float(slope * x)) segment_val = float(func - y) slope_val = (float(func - y) * x) print ("Segment Val: %d :: Slope Val: %d" % (segmen...
from random import randint while True: print('There is a random number between 1 - 100') random_number = randint(0, 100) guess = int(input('Guess the number > ')) if guess == random_number: print('WoW you won :D') break elif guess < random_number: print('Too low :(')...
"""Euler Problem #23: A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is le...
"""By replacing the 1st digit of the 2-digit number *3, it turns out that six of the nine possible values: 13, 23, 43, 53, 73, and 83, are all prime. By replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit number is the first example having seven primes among the ten generated numbers, yielding ...
"""Euler Problem #22: Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name s...
"""Euler Problem #26: A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given: 1/2 = 0.5 1/3 = 0.(3) 1/4 = 0.25 1/5 = 0.2 1/6 = 0.1(6) 1/7 = 0.(142857) 1/8 = 0.125 1/9 = 0.(1) 1/10 = 0.1 Where 0.1(6) means 0.166666..., and has a 1-digit...
"""Euler Problem #33: The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s. We shall consider fractions like, 30/50 = 3/5, to be trivial examples. There are exactly four non...
"""Euler Problem #20: n! means n × (n − 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100!""" from functools import reduce def fact(n): factorial = 1 while n ...
def text_convert(input) -> str: """ input: raw scraped html """ return "" if input is None else input.get_text().strip() def text_sanitizer(input) -> str: """ input: a string input Remove all the newlines, whitespaces from string """ return input.replace('\n', '...
import unittest from challenge import Solution class TestSingleNumber(unittest.TestCase): def setUp(self): self.sut = Solution() def test_a_1(self): input = [0, 1, 0, 3, 12] expected_output = [1, 3, 12, 0, 0] self.sut.moveZeroesCounting(input) self.assertEqual(input, ...
""" For example, given the array [−2,1,−3,4,−1,2,1,−5,4], the contiguous subarray [4,−1,2,1] has the largest sum = 6. """ class Solution: # @param A, a list of integers # @return an integer def maxSubArray(self, A): sum = max_sum = A[0] if len(A) > 1: for i in range(1, len(A)): ...
chars=['A','B','C'] fruit=('apple','banana','mango') dict={'name':'Aditi','ref':'python','branch':'cse'} print('element:',end='') for item in chars: print(item,end='') for item in enumerate(chars): print(item) for itwm in zip(chars,fruit): print(item,end='') for key,value i...
#-*- encoding=utf-8 -*- __author__ = 'Nobody' str1 = raw_input("请输入第一个字符串") str2 = raw_input("请输入第一个字符串") if(str1 is None or str2 is None): print "不是变位词" if(len(str1) != len(str2)): print "不是变位词" str1 = list(str1) str2 = list(str2) str1.sort() str2.sort() str1 = "".join(str1) str2 = "".join(str2) #网上借鉴的一行搞定...
#!/usr/bin/python3 # 文件名:read.py str = input("请输入文件名:") print("你输入的内容是:",str) f=open(str,"w") f.write("Python测试写文件内容\r\n很简单的操作方式!!") f.close() # 关闭 strA = input("是读取写入的内容:") strA = strA.lower() if strA == "yes" or strA == 'y': f=open(str,'r') strContent = f.read() print("写入文件'{0}'的内容为'{1}'".format(str,strContent)...
#!/usr/bin/python3 # 文件名:json3.py """ JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于ECMAScript的一个子集。 Python3 中可以使用 json 模块来对 JSON 数据进行编解码,它包含了两个函数: json.dumps(): 对数据进行编码。 json.loads(): 对数据进行解码。 在json的编解码过程中,python 的原始类型与json类型会相互转换,具体的转化对照如下: """ import json # Python字典类型转换为JSON对象 data = { 'no':1, 'name':'Runo...
#!/usr/bin/python3 # 文件名:time5.py """ Python 程序能用很多方式处理日期和时间,转换日期格式是一个常见的功能。 Python 提供了一个 time 和 calendar 模块可以用于格式化日期和时间。 时间间隔是以秒为单位的浮点小数。 每个时间戳都以自从1970年1月1日午夜(历元)经过了多长时间来表示。 Python 的 time 模块下有很多函数可以转换常见日期格式。如函数time.time()用于获取当前时间戳, 如下实例: """ ''' Calendar模块有很广泛的方法用来处理年历和月历,例如打印某月的月历: ''' import calendar cal = calen...
def getInfo(): print("witaj w programie kalkulator") def dodawanie(a,b): return a+b getInfo() print('podaj a') a = int(input()) print('podaj b') b = int(input()) print(dodawanie(a,b))
# for creating convert-command for combining sevreal unown images into one text = input("What should be assembled?\n") pngs = "" for letter in text.lower(): if letter == " ": letter = "\\" + letter pngs += "unowns/201unown_" + letter + ".png " print(f"convert {pngs}+append unown.png")
## Jocelyn Huang ## Sentiment Analysis Project ## 02.06.2014 ## Read from text file import string import sys def removePunctuation(s): s = s.replace("-", " ") s = s.replace(".", " ") s = s.replace("/", " ") removal = {ord(char): None for char in string.punctuation} s = s.translate(removal).lower() re...
class TreeNode: def __init__(self, value): self.value = value class Tree: def __init__(self, value): self.children = [] self.value = TreeNode(value) def add_child(self, value): self.children.append(Tree(value)) # For each node calc height of left tree, height of right tre...
#Convert Python Linked List Class to Array #Make LL class class LinkedList: def __init__(self, value): print('initialzied linked list') self.value = value self.next = None def add_node(self, value): self.next = LinkedList(value) test = LinkedList(10) test.add_node(20) def list_to_array(linked_...
import math def merge_sort(arr, start=0, end=None): if (end is None): end = len(arr)-1 if (end-start < 1): return [arr[start]] # Split into smaller subsections midpoint_index = int(math.floor((start + end)/2)) left = merge_sort(arr, start, midpoint_index) right = merge_sort(arr...
class Node: def __init__(self, value): self.value = value class Tree: def __init__(self, value): self.children = [] self.node = Node(value) def add_child(self, value): self.children.append(Tree(value)) my_tree = Tree(10) my_tree.add_child(100) my_tree.add_child(50) def...
from typing import Counter class Node: def __init__(self, value): self.value = value self.left = None self.right = None class Queue: def __init__(self): self.front=None self.rear=None def enqueue(self,value): node=Node(value) if self.is_empty(): ...
class Node(object): def __init__(self, data:int): self.data = data self.next = None class LinkedList(object): def __init__(self): self.head = None def push(self, new_data:int): new_node = Node(new_data) new_node.next = self.head self.head = new_n...
''' Author: Touchette Project One: Queue and Stack using a LinkedList implementation Completion Date: 2018-01-28 This is the queue file that will take the DoubleLinkedList implementation and produce a queue capable of enqueuing and dequeueing items in a fitrst-in, first-out manner. ''' import sys import DoubleLinkedLi...
''' Author: Touchette Project Three: Calculate Rolling Median Completion Date: 2018-02-25 A class that implements a calculator to keep tracking of the rolling median of a continuous input of numbers. ''' import sys import heapq class RollingMedianCalc(): def __init__(self): ''' Initialize the max...
import heapq x = [5,2,8,1,6,7,4,9] heapq.heapify(x) print(x) heapq.heappush(x,2) print(x) print(heapq.heappop(x)) print(x) print (heapq.heappushpop(x, 5)) print(x) #Used to get n largest elements in heap print(heapq.nlargest(4,x)) #Used to get n smallest elements in heap print(heapq.nsmallest(4,x))
print "Type the filename again:" file_again = raw_input("> ") # assign txt_again to open the file that was provided in last step txt_again = open(file_again) # print out the file that was provided. print txt_again.read()
import csv from pprint import pprint ### PART 1 ##################################################################### # Step 1. load employees first ################################################## ''' Load employees.csv and parse data into one main list, called list. Then, parse list into two more lists, em...
from random import randrange ## CONSTANTS ## ##Art by Hayley Jane Wakenshaw - https://www.asciiart.eu/animals/dogs DOG_LEFT = """ __ o-''|\_____/) \_/|_) ) \ __ / (_/ (_/ """ DOG_RIGHT = """ __ (\_____/|''-o ( (_|\_/ \ __ / \_) \_) """ ##Art by Joan Stark ...
class Card(): def __init__(self, name): self.name = name self.value = self.getValueFromName(name) def getValueFromName(self, name): if len(name) == 3: return 10 else: try: return int(name[0]) except: if name[0...
#!/usr/bin/env python # gcd_start.py # Find the greatest common denominator of two numbers # using Euclid's algorithm def gcd(a, b): while (b != 0): t = a a = b b = t % b return a #try out the function with a few examples print(gcd(60,96)) print(gcd(20,8))
class Transaction(object): '''Holds information about transactions to be stored in the blockchain''' def __init__(self, tx_id, u_from, u_to, amnt): self.tx_id = tx_id self.u_from = u_from self.u_to = u_to self.amnt = amnt def varify(self, state): print("varifying tra...
def isIn(char, aStr): ''' char: a single character aStr: an alphabetized string returns: True if char is in aStr; False otherwise ''' #Base case: If aStr is emply, we did not find the char. if aStr == '': return False #Base case: If aStr is of length 1, just see if the...
def uniqueValues(aDict): ''' aDict: a dictionary returns: a sorted list of keys that map to unique aDict values, empty list if none ''' uniqueVals = [] for key in aDict.keys(): subaDict = aDict.copy() del subaDict[key] uniqueValue=True for compKe...
class PuzzleInfo: def __init__(self): self.puzzleQuestions = {} self.puzzleAnswers = {} self.puzzleQuestions["1"] = "You meet two inhabitants: Zoey and Mel. Zoey tells you that Mel is a knave. Mel says, `Neither Zoey nor I are knaves.'" self.puzzleQuestions["2"] = "You meet...
import matplotlib.pyplot as plt from matplotlib.widgets import Slider, Button, RadioButtons import numpy as np import math import random # defaults center = (0, 0) radius = 1 dot_size = 0.01 # play with these num_dots0 = 10 num_dots_min = 10 num_dots_max = 300 factor0 = 2 factor_min = 2 factor_max = 200 function0 =...
def reverse(st): return ' '.join(reversed(st.split())) print(reverse("Hi There"))
print("CDV") print(10) ''' komentarz blokowy ''' #potegowanie komentarz jednej lini potega = 2 ** 10 print (potega) #pobieranie danych z klawiatury name=input() nazwisko=input() print("Twoje imie: "+name) print("Twoje imie: "+name+", nazwisko: "+nazwisko) ''' Uzytkownik podaje nazwy z klawiatury swój wiek, Twój wiek: ...
from decorations import Decorations import pygame as pg class Castle(Decorations): def __init__(self, model, x=0, y=0, width = 200, height = 200): """ Initialize the castle decoration with a reference to the model, a x and y position, and a size defined by width and height """ # load the im...
class Items: def __init__(self, model, image, x=0, y=0): """ Initialize the item class with a reference to the model, an image, and a position (defined by x and y) """ # initialize the model for interactions between items self.model = model # set the image self.image...
""" MDST Workshop 1 - Python Basics Starter Code """ # Add any imports you need here: import random import base64 def part1(num): """ Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate (i.e. "even" or "odd") message to the user. """ if num % 2 == 0:...
#!/usr/bin/python # -*- coding: utf-8 -*- # @Time  : 2019/7/20 14:12 # @Author : wangyong # @Desc : 编码转换 import re import binascii def split1(str): t = '' for i in range(int(len(str) / 2)): t += str[2 * i:2 * (i + 1)] + ' ' t = t.upper() return t def split2(str): t = str.upper() p ...
#!/usr/bin/python # -*- coding: UTF-8 -*- # 文件名:dict_json_test.py class Student: name = '' age = 0 def __init__(self, name, age): self.name = name self.age = age # 对象转换成Dict字典 def object_to_dict(obj): dict = {} dict.update(obj.__dict__) return dict # 对象列表转换为Dict字典列表 def li...
from flight_function import calculator print("="*38) print("Welcome To our Flight Fair Calculator") print("="*38,"\n") print("Our Flight Numbers") print("_"*38) print("001: Delhi to Mumbai") print("002: Delhi to Kanyakumari") print("003: Delhi to Orrisa") print("004: Delhi to Bihar") print("_"*38) # number of children...
#https://www.hackerrank.com/challenges/whats_your_name/problem def print_full_name(a, b): string = f"Hello {a} {b}! You just delved into python." return print(string) if __name__ == '__main__': first_name = input() last_name = input() print_full_name(first_name, last_name)
# https://www.hackerrank.com/challenges/py_set_union/problem # Enter your code here. Read input from STDIN. Print output to STDOUT a = input() set_a = set(map(int, input().split())) b = input() set_b = set(map(int, input().split())) print(len(set_a.union(set_b)))
class And(object): """docstring for And""" def __init__(self, owning_particle): super(And, self).__init__() self.owning_particle = owning_particle def collide(self, another_particle): if self.owning_particle.contents and another_particle.contents: another_particle.con...
m = int(input()) while(m > 0): str = input() if (len(str) > 10): es = len(str[1:-1]) print('{}{}{}'.format(str[0], es, str[-1])) else: print(str) m = m-1
# Matis Maamets ITT20 # 09.02.2021 # Kodutöö2 #kuidagi ümbernurga lahendus tundub tahaks paremat viisi teada. ringid = int(input("Mitu ringi? ")) tulemus = int(0) a=int(0) if ringid<0: print("hoopis lammas?") else: while ringid-2>=a: tulemus = int(tulemus+a+2)...
def tree_arraysum(arr): if len(arr) < 2: return '' left = 0 right = 0 depth = 1 i_start = 1 i_end = 2 i_mid = 2 i = 1 while i < len(arr): if arr[i] == -1: pass elif i < i_mid: left += arr[i] else: right += arr[i] if i == i_end: i_start = i_end + 1 ...
# take a list of characters and reverse characters in place def reverse_in_place(chars): # if len == 0 or 1, no swap # key off of the first half if len(chars) < 2: return chars for i in range(0, len(chars)//2): target = len(chars) - 1 - i chars[i], chars[target] = chars[target]...
# [ ] create, call and test fishstore() function # then PASTE THIS CODE into edX # Created May 6, 2020 def fishstore(fish, price): output = "Fish Type: " + fish + " costs $" + price return output fish_entry = input("enter fish name: ") price_entry = input("enter fish price (no symbols): ") print(fishstore(f...
import color_contrast_calc as calc import color_contrast_calc.sorter as sorter color_names = ['red', 'yellow', 'lime', 'cyan', 'fuchsia', 'blue'] colors = [calc.color_from(c) for c in color_names] # Sort by hSL order. An uppercase for a component of color means # that component should be sorted in descending order. ...
__author__ = 'Dreyke Boone' import sqlite3 # function to update a row in db def update_row(): db_file = 'products_db.sqlite' # name of database file row_selection = '' while row_selection != 'q': row_selection = input("Enter a game title to display and update information or press q to quit: ")...
# try: (예외가 발생할 수 있는 가능성이 있는 코드) # except: (예외가 발생했을 때 실행할 코드) try: print(float(input("> 숫자를 입력해주세요: ")) ** 2) except: print("숫자를 입력해주세요") # pass 키워드를 사용하기도 한다. # pass 키워드 사용시 프로그램은 종료되지 않되 계속 반복된다. list_input_a = ["52", "273", "32", "스파이", "283"] list_number = [] for item in lis...
# 소수점이 없는 숫자(정수) # 소수점이 있는 숫자(정수 < 실수) # 존재하지 않는 수 = 허수(정수 < 실수 < 복소수) # Python에서는 숫자의 나눗셈을 할때 float형인지 int형인지 크게 신경을 안써도 된다.(대부분 float형으로 반환) # 연산자 : *, +, **(제곱), %, //(몫) # print함수의 경우 숫자를 출력하기 위해서는 "" 가 필요없지만, 문자열의 출력을 위해선 ""가 필요하다. print("기본적인 연산") print(15, "+", 4, "=", 15+4) print(15, "-", 4, "=", 15-4)...
# 리스트 평탄화 : 2차원 리스트를 1차원 리스트로 만드는것 def flatten(data): output = [] for item in data: if type(item) == list: output += flatten(item) else: #output.append(item) output += [item] example = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print("원본", example) print("변환...
class Student: def __str__(self): return "{} {}살".format(self.이름, self.나이) def __init__(self, 이름, 나이): # class 생성자(선언자) print("객체가 생성되었습니다.") self.이름 = 이름 self.나이 = 나이 def __del__(self): print("객체가 소멸되었습니다.") def output(self): print(self.이름, ...
#Question 36 #This problem was asked by Dropbox. #Given the root to a binary search tree, find the second largest node in the tree. #Answer 36 #create node class class Node: #iniate with data def __init__(self, data): self.data = data #has a lef and right self.left = No...
#Question 35 #This problem was asked by Google. #Given an array of strictly the characters ‘R’, ‘G’, and ‘B’, segregate the values of the array so that all the Rs # come first, the Gs come second, and the Bs come last. You can only swap elements of the array. #Do this in linear time and in-place. #For exa...
#Question 45 #This problem was asked by Two Sigma. #Using a function rand5() that returns an integer from 1 to 5 (inclusive) with uniform probability, #implement a function rand7() that returns an integer from 1 to 7 (inclusive). #Answer 45 from random import randint def rand5(): return randin...
#This problem was asked by Google. #The area of a circle is defined as πr^2. Estimate π to 3 decimal places using a Monte Carlo method. #Hint: The basic equation of a circle is x2 + y2 = r2. from random import random radius = 2 def estimate_pi(num_random_tests): pi_counter = 0 rsquared = radius...
class Fila(): def __init__(self): self.fila = [] def isEmpty(self): return self.lenght() == 0 def lenght(self): return len(self.fila) def peek(self): return self.fila[0] def enqueue(self,item): self.fila.append(item) def dequeue(self): if not(self.isEmpty()): sel...
import pandas as pd data = { 'apples': [3, 2, 0, 1], 'oranges': [0, 3, 7, 2] } price = pd.DataFrame(data) print (price)
class LibraryException(Exception): pass class BookValidatorException(LibraryException): pass class BookValidator: def validate_isbn (self, book): """ Check if the isbn is valid isbn = 978-92-95055-02-5(example) An isbn consist of 13 digits (in 5 elements) ->Prefix: can only...
def recursive_backtracking(set, num): if num < 0: return if len(set) == 0: if num == 0: yield [] return for solution in recursive_backtracking(set[1:], num): yield solution for solution in recursive_backtracking(set[1:], num - set[0]): yield [set[0]] ...
n = int(input()) if not n>0: print('Wrong Input') else: r = int(input()) if n<r: print('Wrong Input') else: if n==r: print(1) mul = n for q in range(r-1): mul*=n-1 n-=1 print(mul)
# given integral number n, create a dictionary with the function that creates the squre of our n # integral is a number assigned to a function print('Enter an int: ') n = int(input()) d = dict() for i in range(1, n+1): d[i] = i**2 print(d)
""" Find the greatest difference between list items. Given a list, return the largest difference between individual items. """ def max_difference(ls): """Return the greatest difference between any two list items.""" low = ls[0] high = ls[0] for item in ls: if item < low: low = ite...
''' Programa que solicita que usuario escreva uma frase, pede para o usuario digitar uma letra e faz uma busca dessa letra na frase escrita mais quantidade de vezes de sua ocorrencia. ''' phrase = input('Digite sua frase: ') letter = input('Digite a letra da qual deseja saber seu index: ') qtd = 0 for i, c in enumer...
a=int(input('Enter')) b=int(input('Enter')) print('Subtraction value is:-',a-b)
"""A collection of helper display functions using a pyplot backend.""" import matplotlib.pyplot as plt from matplotlib.cm import gray from math import sqrt, floor import numpy as np def show_image(pixels, shape): """Display the provided pixels in the provided shape.""" shaped_matrix = np.reshape(pixels, shap...
''' Every value in a program has a specific type. Integer (int): represents positive or negative whole numbers like 3 or -512. Floating point number (float): represents real numbers like 3.14159 or -2.5. Character string (usually called “string”, str): text. Written in either single quotes or double quotes (as long as ...
# for letter in ("debabrata"): # print("The letter is", letter) # for num in (10,20,30,40): # print(num) # count = 0 # for i in range (4): # while i<=2: # if i==2: # break # count = count+10 # i=i+1 # else: # count = count+1 # else: # count = (count+20)...
""" Воин Создать класс воина, создать 2 или больше объектов воина с соответствующими воину атрибутами. Реализовать методы, которые позволять добавить силы воину, улучшить оружие. Реализовать возможность драки 2х воинов с потерей здоровья, приобретения опыта (можно магические методы, можно кастомные). """ clas...
print("Welcome to the Love Calculator!") name1 = input("What is your name? \n") name2 = input("What is their name? \n") # coginate name combinedname = name1 + name2 t = combinedname.count("t") r = combinedname.count("r") u = combinedname.count("u") e = combinedname.count("e") total = t+r+u+e l = combinedname.count("...
# =====This part is using colorgram to extract colors from the image. ====# import colorgram colors = colorgram.extract("brighter_dots.jpg", 60) color_list = [] for color in colors: new_color = color.rgb r = new_color[0] g = new_color[1] b = new_color[2] color_list.append((r, g, b)) print(color_l...
list=["late","wind","2017","6.4"] tinylist=["good","day"] print(list) print(list[2:]) print(list[1:3]) print(list[1:-2]) print(list[0]) print(list+tinylist) del list[0] print(list[0]) print(len(list)) listCompose=list+tinylist; listCompose.append('I am OK') listCompose.sort() sub=['sub1','sub2'] listCompose.append(sub)...
nota1 = float(input("Digite a nota 1: ")) nota12 = float(input("Digite a nota 1: ")) nota2 = float(input("Digite a nota 2: ")) nota22 = float(input("Digite a nota 2: ")) media1 = ((nota1 + nota12) / 2) media2 = ((nota2 + nota22) / 2) print(media1) print(media2) #http://pt.stackoverflow.com/q/186098/101
n1 = input ("informe um número ") n2 = input ("informe um número ") soma = int(n1) + int(n2) print ("O resultado da soma de", soma) #https://pt.stackoverflow.com/q/87584/101
l = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] num = int(input("Choose a number: ")) new_list = [] for i in l: if i < num: new_list.append(i) print(new_list) #https://pt.stackoverflow.com/q/359133/101
def main(): ocorrencia = 0 numeroReal = int(input("Digite um número inteiro positivo:\n")) numero = numeroReal digito = int(input("Digite um dígito para que analisemos sua ocorrência no número anteriormente digitado:\n")) while numero != 0: if (numero % 10 == digito): ocorrencia ...
class op(): def __init__(self,num1,num2): self.x = num1 self.y = num2 def soma(self): return self.x + self.y def somadez(self): return self.soma() + 10 conta1 = op(1, 2) print(conta1.soma()) print(conta1.somadez()) #https://pt.stackoverflow.com/q/442138/101
n1 = input('Qual é o seu bolo favorito?') if n1.lower() == 'bolo de chocolate': print('teste123') #https://pt.stackoverflow.com/q/339306/101
def maximum(lista): max = float('-inf') for item in lista: try: valor = int(item) if valor > max: max = valor except: pass return max print(maximum(['4', '07', '08', '2017', '364', '355673087875675'])) print(maximum(['4', '07', '08', '355673087875675', 'a', '2017'])) #https://pt.stackoverflow.com...
x = input("True ou False...? ").lower() if x == 'true': print("Você escolheu True") elif x == 'false': print("Você escolheu False") else: print("Você não escolheu True ou False") #https://pt.stackoverflow.com/q/170784/101
print("Insira dois valores para serem comparados:") valor1 = float(input("\nEscreva um número:")) valor2 = float(input("\nEscreva outro número:")) print("\nConfirme os números que você inseriu digitando 'sim':\n", valor1, "\n", valor2) if input() == "sim": if valor1 > valor2: print("O primeiro valor é maior...
n1 = int(input()) n2 = int(input()) count = 0 for c in range(n1, n2): if c % n1 == 0: count += 1 print('O numero {} tem {} multiplos menores que {}.'.format(n1, count, n2)) #https://pt.stackoverflow.com/q/449499/101
num_lidos = int(input('Digite a quantidade de números: ')) maior = 0 qnt = 0 for num in range(0, num_lidos): num = int(input('Digite o valor: ')) if num > maior: maior = num qnt = 1 elif num == maior: qnt += 1 print(f'Maior valor = {maior}') print(f'Quantidade de vezes que o maior nú...
def soma(a, b): x = a + b y = 'qualquer coisa' if x > 5: return x else: return y def soma(a, b): x = a + b y = 'qualquer coisa' yield x yield y def soma(a, b): x = a + b y = 'qualquer coisa' return (x, y) #https://pt.stackoverflow.com/q/331155/101
print('Sistema de nota escolar') nome = input('Qual seu nome: ') final = 0 for bimestre in range(1, 5): print(f'{bimestre}o. bimestre') nota1 = float(input('Primeira nota: ')) nota2 = float(input('Segunda nota: ')) nota3 = float(input('Terceira nota: ')) nota4 = float(input('Quarta nota: ')) med...
while True: n = input('Texto errado, digite tudo em maiúscula: ') if n.isupper(): print('Texto correto') break #https://pt.stackoverflow.com/q/433623/101