text
stringlengths
37
1.41M
""" Найдите все натуральные числа, принадлежащие отрезку [101 000 000; 102 000 000], у которых ровно три различных чётных делителя. В ответе перечислите найденные числа в порядке возрастания. """ # a lot of time of execution for i in range(101000000, 102000000 + 1): divider = 0 for j in range(2, i // 2 + 1): ...
""" Найдите все натуральные числа, принадлежащие отрезку [35 000 000; 40 000 000], у которых ровно пять различных нечётных делителей (количество чётных делителей может быть любым). В ответе перечислите найденные числа в порядке возрастания. """ def is_prime(n): d = 2 while d * d <= n: if n % d == 0: ...
""" Логическая функция F задаётся выражением: ¬((x \/ y) → (z /\ w)) /\ (x → w). Дан частично заполненный фрагмент, содержащий неповторяющиеся строки таблицы истинности функции F. Определите, какому столбцу таблицы истинности соответствует каждая из переменных w, x, y, z. zxyw """ k = 0, 1 print('x y z w F') for x in...
""" Рассматривается множество целых чисел, принадлежащих числовому отрезку [8800; 55535], которые удовлетворяют следующим условиям: − произведение разрядов больше 35; − один из разрядов равен 7. Найдите наибольшее из таких чисел и их количество. Для выполнения этого задания можно написать программу или воспользоваться ...
""" Задание 15 (№779). Обозначим за (n & m) поразрядную конъюнкцию чисел n и m. Так, например, 6>10 & 10>10 = 2>10 (0110>2 & 1010>2 = 0010>2). Найдите минимальное натуральное значение параметра A, при котором выражение истинно при любом значении х. После ">" - основание """ def k(n, m): return n & m for A in ra...
# for c in 'Hello': # print(c) items = ['foo', 'bar', 'baz'] for (index, elem) in enumerate(items): items[index] += elem + '!' print(items) # ['foofoo!', 'barbar!', 'bazbaz!'] # Должен был вернуть: ['foo!', 'bar!', 'baz!'] """ Встроенная в Python функция enumerate() применяется для итерируемых коллекций (с...
""" № 633, Джобс 02.11.2020 У исполнителя Калькулятор три команды, которым присвоены номера: 1. прибавь 1 2. умножь на 2 3. возведи в квадрат Сколько есть программ, которые число 5 преобразуют в число 154? 8966 """ k = [0] * (154 + 1) k[5] = 1 for n in range(5, 154 + 1): if (n + 1) <= 154: k[n + 1] += k[n]...
x = int(input()) L = 0 M = 0 while x > 0: L += 1 if (x % 10) > M: M = x % 10 x = x // 10 print('X=', x) print(L) print(M)
""" (x /\ ¬y) \/ (x ≡ z) \/ w """ print('x y z w F') k = 0, 1 for x in k: for y in k: for z in k: for w in k: F = (x and not y) or (x == z) or w if not F: print(x, y, z, w, F)
""" Задание 22 (№1375). Ниже записана программа. Получив на вход число x, эта программа печатает два числа L и M. При каком наибольшем значении x после выполнения программы на экран будет выведено два числа 3, а затем 7. """ x = int(input()) L, M = 0, 0 while x > 12: L += 1 x //= 4 M = x if L > M: L, M = M,...
""" № 503, Джобс 19.10.2020 Ниже на четырех языках программирования записан алгоритм. Получив на вход натуральное десятичное число x, этот алгоритм печатает число S. Сколько существует чисел x, не превышающих 500, при вводе которых результате работы программы на экране будет выведено число 13. """ # x = int(input()) # ...
from math import sqrt start, end = 268312, 336492 def isPrime( x ): if x <= 1: return False d = 2 while d*d <= x: if x % d == 0: return False d += 1 return True count = 0 mi = 1e10 for i in range(start, end+1): for x in [2]+list(range(3,round(sqrt(i))+1,2)): if i % x == 0...
####################################### # EXERCICIO 022 # ####################################### '''CRIE UM PRIGRAMA QUE LEIA O NOME COMPLETO DE UMA PESSOA E MOSTRE: O NOME COM TODAS AS LETRAS MAIUSCULAS O NOME COM TODAS AS LETRAS MINUSCULAS QUANTAS LETRAS TEM O NOME (SEM CONSIDERAR OS ESPAÇO...
########################################### # EXERCICIO 028 # ########################################### '''ESCREVA UM PROGRAMA QUE FAÇA O COMPUTADOR PENSAR UM NUMERO INTEIRO ENTRE 0 E 5 E PEÇA PARA O USUARIO TENTAR DESCOBRIR QUAL FOI O NUMERO ESCOLHIDO PELO COMPUTADOR. O PROGRAMA DEVERÁ ESCR...
########################################### # EXERCICIO 096 # ########################################### ''' Faça um programa que tenha uma função chamada área(), que receba as dimensões de um terreno retangular (largura e comprimento) e mostre a área do terreno. ''' from time import sleep f...
########################################### # EXERCICIO 100 # ########################################### ''' Faça um programa que tenha uma lista chamada números e duas funções chamadas sorteia() e somaPar(). A primeira função vai sortear 5 números e vai colocá-los dentro da lista e a segunda...
########################################### # EXERCICIO 065 # ########################################### '''CRIE UM PROGRAMA QUE LEIA VARIOS NUMEROS PELO TECLADO. NO FINAL DA EXECUÇÃO, MOSTRE A MEDIA ENTRE TODOS OS NUMEROS E QUAL FOI O MAIOR E O MENOR VALOR DIGITADO. O PROGRAMA DEVE PERGUNTAR...
########################################### # EXERCICIO 064 # ########################################### '''CRIE UM PROGRAMA QUE LEIA VARIOS NUMEROS PELO TECLADO. O PROGRAMA SÓ VAI PARAR QUANDO O USUARIO DIGITAR O VALOR 999, QUE É A CONDIÇÃO DE PARADA. NO FINAL MOSTRE QUANTOS NUMEROS FORAM DO...
# -------------------------------------------------# # EXERCICIO 16 # # -------------------------------------------------# # crie um programa que lei um numero real qualquer # do teclado e mostre na tela sua proção inteira. # ex: digite 6.123 e a parte inteira é 6 '''from math import...
# -------------------------------------------------# # EXERCICIO 11 # # -------------------------------------------------# # Faça um programa que leia a largura e a altura de uma parede # em metros, calcule sua area, e a quantidade de tinta # necessaria para pinta-la, sabendo que cada...
########################################### # EXERCICIO 102 # ########################################### """ Crie um programa que tenha uma função fatorial() que receba dois parâmetros: o primeiro que indique o número a calcular e outro chamado show, que será um valor lógico (opcional) indica...
########################################### # EXERCICIO 052 # ########################################### '''FAÇA UM PROGRAMA QUE LEIA UM NUMERO INTEIRO E DIGA SE ELE É OU NÃO UM NUMERO PRIMO''' import time n = int(input('DIGITE UM NUMERO E VEJA SE É PRIMO...:')) cont = 0 for c in range(1,n+1)...
# -------------------------------------------------# # EXERCICIO 13 # # -------------------------------------------------# # Faça um algoritmo que leia o salario de um funcionario # e mostre seu novo salario com 15% de aumento salario = float(input('Digite se salario...: R$ ')) novo ...
# -------------------------------------------------# # EXERCICIO 08 # # -------------------------------------------------# # Faça um programa que leia um valor em metros # e exiba convertido em centimetro e milimetros mt = float(input('digite um distancia em metros...:')) mm = mt * 1...
#!/usr/bin/env/python3 #-*- coding:utf-8 -*- #用正则表达式实现类似strip()方法的功能,可以去掉一个字符串首尾的指定字符,默认为空格。 import re def rstrip(text, char=' '): ''' 匹配字符串中首尾的指定字符并将其去掉,如果没有找到指定的字符则返回原字符串 text:原字符串 char:要去掉的字符串,默认为空格 ''' string=re.compile(r'^(%s)*|(%s)*$'%(char,char)) print(string.sub('',text)) text=' sfdlfjsl sdfsd...
from .quick_sort import quick_sort class TestQuickSort: def test_sort_unsorted_list(self): a = [2,4,1,6,8,5,3,7] quick_sort(a) assert a == [1,2,3,4,5,6,7,8] def test_sort_sorted_list(self): a = [1,2,3,4,5,6,7,8] quick_sort(a) assert a == [1,2,3,4,5,6,7,8] ...
import numpy as np import matplotlib.pyplot as plt import pandas as pd from matplotlib.colors import ListedColormap # NOT WORKING def plot_kNN(x, y, classifier, k): cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#00AAFF']) cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#00AAFF']) x = pd.DataFram...
inp_int = int(input("Enter a number: \n")) inp_bool = int(input('Enter 0/1 : \n')) i = 0 while i<inp_int: if inp_bool== True: print("*"*(i+1)) i+=1 elif inp_bool== False: print("*"*inp_int) inp_int-=1
def check_prime(n): for i in range(2, n): if n % i == 0: return False return True def nth_prime(limit): num = 2 repeats = 0 loop = True while loop: if check_prime(num): repeats += 1 if repeats == limit: break if num == 2: ...
""" Board module """ from battleship.area import Area from battleship.ship import Ship class Board: """ """ def __init__(self, size): """ :param size: tuple (10, 10) """ self.size = size self.areas = self.init_area(self.size) self.ships = [] def init_...
from tkinter import * import tkinter as tk #import requests # import tinker as a whole and after import tkinter as tk # adding functionality to our app base = Tk() # we configure our app title and dimensions and background colour base.title("Weather App Group 6") base.configure(bg="#9bd7e8") base.geometry("580x480")...
# sets are un indexed , unordered , unchangeable a_set = {"apple", 4, "banana", "cherry", True} print("apple" in a_set) b_set = {"pear", 20, 4} b_set.add(False) print(b_set) # return the union of sets without duplicated values people = [('Ann', 30), ('Moses', 25), ('Elijah', 10), ('Dan', 40), ('Timothy', 15)] pr...
# # def replace_func(s, t, n): # # string -s, target -t, new -n # # return # # # replace_func() # string like "hello world" # target like world # new word like guys def replace_func(s, t, n): # convert our string to a list as we split it s = s.split() print(s) print(type(s)) for i in s:...
''' 1. define a function called "String_Encoder": takes parameters s with the following value "It's a rainy day" 2. print the string backwards 3. replace "a" with "z" 4. return the encoded string ''' # s = "I's a rainy day" # # a = (s[::-1]) # print(a) def string_encode(s): a = "" for iterator in range(...
def sum(): x = 5 y = 2 print(x + y) # run the function sum() # functions with parameters def return_sum(a, b): return a + b print(type(return_sum(2, 2))) c = 5 + return_sum(2, 2) print(c)
#Nyeko Samuel def fib(n): a, b = 0, 1 for i in range(n): print(a) ''' - this solution only works when variables are initialized on the same line because it overwrites a instead of swaping using temp - initializing the standard way would not work ...
# from tkinter import * # import tkinter as tk # Create a dictionary that prints out keys and values. # cities = {1: 'jinja', 2: 'Kampala', 3: 'Gulu', 4: 'Entebbe'} # # for city in cities: # print(city, ' ', cities[city]) # # Create a class function of your top 3 Music Artist. # # Create a for loop that only pri...
# import os # import pickle # # file_name1 = input('请输入源文件地址:') # str1 = input('请输入需要打印的对话者一名字:') # str2 = input('请输入需要打印的对话者二名字:') # # def search_file(file_name1, str1, str2 ): # aa = [] # bb = [] # f1 = open(file_name1) # f2 = open('boy_1.txt','wb') # f3 = open('girl_1.txt','wb') # for each_li...
#imports the time module import time #create a list of all the questions question = ["How many episodes of No Game No Life are there currently? ", "What do Sora and Shiro call themselves? ", "What is the opening theme to No Game No Life called? ", "In the beginning scene of episode 1, how many was the highest amount o...
def isThree(n): if(n == 3): print("This is three") return True else: print("This is not three") return False
# Bubble sort algorithm def bubbleSort(dataset): # TODO: start with the array length and decrement each time for i in range(len(dataset) - 1, 0, -1): for j in range(i): if dataset[j] > dataset[j+1]: pass else: temp = dataset[j] da...
# # Read and write files using the built-in Python file methods # def main(): # Open a file for writing and create it if it doesn't exist #file = open("text.txt", "w+") #plus means create the file if not exists # Open the file for appending text to the end file = open("text.txt", "r") # write some lines...
import requests import sys url = "https://api.github.com/users/" githubname = input("enter the githubname please:") response_repos = requests.get(url + githubname + "/repos") repos=response_repos.json() try: for i in range(len(repos)): print(repos[i]["name"]) except KeyError: sys.stderr.write("N...
''' Images and Filters Program By: Spencer Milbrandt Created: 10/22/13 Last Modified: 10/27/13 This program imports GIF files that are in the same directory as the graphics_main.py file. From there the GIF file can go through filters that the user inputs. The program consists of a robust textual interface and allow...
""" """ # make sure to import things that you need... def main(): import math # rbr is the rabbit birth rate without predation rBr = 0.01 # fbr is the fox birth rate when no rabbits are available fBr = 0.005 # interaction is the likelihood that a rabbit and fox will meet I = 0.00001 # hunt is the likeli...
import OneWordProjects import TwoWordProjects import ChooseWord import BusinessType def name_my_project(): print("") print("Choose an option") print("1) One Word Project") print("2) Two Word Project") print("3) Word Describing Project") print("4) Business Type") choice = int(input()) i...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode "...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right from collections import deque class Solution(object): def rightSideView(self, root): """ :type root:...
class ListNode: def __init__(self,key,value): self.key = key self.value = value self.next = None def insert(self,key,value): head = self #points to dummy head while head and head.next: #check if key already exists, if yes replace if head.key =...
# -*- coding: utf-8 -*- import datetime import jholiday import sys # --------------------------------------------------------------------------- # 目的:特定の日付から今日までの中で、土日祝日を含む休日が何日でいつなのか調べる(リスト作成) # --------------------------------------------------------------------------- def holiday_list(y,m,d): # 今日 today = dateti...
import math def newton(F, Flinha, epsilon, x0): f = lambda x: eval(F) fl = lambda x: eval(Flinha) i = 0 deltax = math.fabs(x0) while deltax > epsilon: x1 = x0 - (f(x0) / fl(x0)) deltax = math.fabs(x1-x0) i = i + 1 x0 = x1 print(x0) print("Numero de iteraçoes:...
# Non performatic version #def fibonacci(n): # assert(n >= 0), 'n must be >= 0' # return n if n in (0, 1) else fibonacci(n-1) + fibonacci(n-2) # Performatic version #known = {0:0, 1:1} #def fibonacci(n): # assert(n >= 0), 'n must be >= 0' # if n in known: # return known[n] # res = fibonacci(n-1) ...
#根节点 root = Treenode #递归 res = [] def post_order(root): if not root: return post_order(root.left) post_order(root.right) res.append(node.val) #iterative #第一种迭代方法 #改编自前序遍历的递归解法,因为前序遍历是 node->node.left->node.right # 我们需要想改变遍历顺序 node->node.right->node.left # 在对结果进行reverse,就变成了 node.left->node.right->nod...
""" ------- Problem -------- N stacks of K plates with each plate having a beauty value B. Choose P plates to maximize the sum of the beauty value. If you choose a plate in a stack then you must choose all the plates above that plate. ------- Algorithm ------ 1. create matrix that contains the sum of i plates in ea...
# -*- coding: utf-8 -*- """ Created on Sun Sep 30 16:50:40 2018 @author: champion """ import os ###################################################################################################################################### # Information #################################################...
nums = [] while True: num = int(input("Enter a number [0 to stop] :")) if num == 0: break nums.append(num) avg = sum(nums) // len(nums) for n in nums: if n >= avg: print(n)
total = 0 for i in range(5): num = int(input("Enter number :")) total += num print(f"Total = {total}")
def hasupper(st) -> bool: """ Returns true if the given string has an uppercase letter, otherwise false. Parameter st is the string to be tested """ for c in st: if c.isupper(): return True return False def countdigits(st) -> int: count = 0 for c in st: if ...
#!/usr/bin/python # -*- coding: utf-8 -*- # group.py: groups related items together. # finding common items in a group of lists is finding connected components in a graph import networkx from networkx.algorithms.components.connected import connected_components def to_edges(lst): it = iter(lst) last = next(it)...
name1 = input("Enter ur name\n") name2 = input("Enter ur partner name\n") name3 = name1+name2 lower_name = name3.lower() a = lower_name.count("l") b = lower_name.count("0") c = lower_name.count("v") d = lower_name.count("e") love = a+b+c+d if(love < 1 or love>9): print("Your love score is " , love ,"you go together...
import pygame pygame.init() class Brick(pygame.sprite.Sprite): '''This class defines our brick sprite''' def __init__(self,screen,x_value): '''This initializer takes brick x, brick y, width and color as parameters. It then sets up the surface for bricks, fills it and sets up the rect''' ...
#coding=utf-8 #12/10/2012 #programado por: Jose Enrique y Nayeli Reyes def piramide(escalones): numero=1 asteriscos=1 espacios=escalones while numero<=escalones: print("%s%s" %(espacios*" ", asteriscos*"*")) espacios=espacios-1 asteriscos=asteriscos+2 numero=numero+1 print("\nMagnifica.") ...
#coding=utf-8 #Programado por Navit Cardoso #Programa de menu pizzas x=int(input("Algo:")) print("Programa que despliega un menu de pizzas y calcula el costo de una orden") pizza=int(input("Selecccione una pizza: 1)Personal 2)Mediana 3)Grande 4)Gorila Numero de pizza: ")) if pizza==1: pizza=40 ...
#Programa cadenero #Fuente por Luis carlos Salgado y Juan Pablo Chan #10/10/12 def mayor(edad,nombre): if edad >=18 : print("Bienvenido %s usted es mayor de edad" %nombre) else: print("%s usted es menor de edad" %nombre) nombre=input("hola, como te llamas?") edad=int(input("C...
#coding=utf-8 #Programa hecho por Navit Cardoso #Programa que calcula la mayoria de edad de una persona print("Programa que calcula la mayoria de edad de una persona") nombre=str(input("Nombre: ")) edad=int(input("Edad: ")) if edad>17: print("Me llamo ", nombre, " y soy mayor de edad") else: print("Me llam...
#!/bin/python3 import sys def gemstones(arr): # Complete this function ans = set(arr[0]) for i in range(1, len(arr)): ans = ans.intersection(set(arr[i])) return(len(ans)) n = int(input().strip()) arr = [] arr_i = 0 for arr_i in range(n): arr_t = str(input().strip()) arr....
""" # Un programa sinxelo, para calcular cadrados de números print("Ejercicios 1.1 - 1.4 ") def potencia(): print("Calcularanse a potencia de dous números. ") n1 = input("Ingrese un número enteiro: ") n2 = input("Ingrese otro número enteiro: ") for x in range(int(n1), int(n2)): print(x * x) ...
# -*- coding: utf-8 -*- """ Utilities for manipulating python structures such as lists and dictionaries. """ import numpy as np def replace_in_list(target_list, targets, replacements): """ Replace (in place) an entry in a list with a given element. Parameters ---------- target_list : list ...
# -*- coding: utf-8 -*- """ Neural networks for use in flows. """ import numpy as np import torch from torch import nn from torch.nn import functional as F class MLP(nn.Module): """A standard multi-layer perceptron. Based on the implementation in nflows and modified to include dropout and conditional inp...
''' Project: Predicting movie genres from movie posters Course: COMPSCI 682 Neural Networks: A Modern Introduction File: test.py Description: Tests the resulting model using testing data. Author: Nirman Dave Adapted from: Vleminckx, Benoit. dnn-movie-posters. (2018). Github repository. https://github.com/benckx/dnn-m...
import random punct = (".", ";", "!", "?", ",") count = 0 new_word = "" inputfile = input("Enter input file name:") with open(inputfile, 'r') as fin: for line in fin.readlines(): for word in line.split(): if len(word) > 3: if word.endswith(punct): ...
#wap to find max min mean median mode of a list of numbers using user defined functions. #MINI ''' def mini(l, n): x = l[0] for i in range(n): if x > l[i]: x = l[i] return x #MAXI def maxi(l, n): x = l[0] for i in range(n): if x < l[i]: x = l[i] return x #...
from sql import db from data import data class userbase: log = False table_twitter = "users_twitter" table_reddit = "users_reddit" sql_user = "miles" sql_pass = "shrek5" ''' user data: id (string) - id location (integer) - FIPS code update_pref (string) - how often ...
# print("Twinkle, twinkle, little star, \n\t How I wonder what you are! \n Up above the world so high, \n\tLike a diamond in the sky. \nTwinkle, twinkle, little star, How I wonder what you are!") # Write a Python program to get the Python version you are using. # import sys # print("Python version") # print (sys.ve...
# Task # Complete the insert function in your editor so that it creates a new Node (pass 'data' as the Node constructor argument) and inserts it # at the tail of the linked list referenced by the 'head' parameter. Once the new node is added, return the reference to the 'head' node. # Note: If the 'head' argument passe...
# Working with loops # def main(): x = 0 # define a while loop while (x<5): print(x) x = x+1 print("This is the break between while and for loop") # define a for loop for x in range(5, 10): print(x) print ("This is the break between two differe...
# Working with calenders # # import the calender module import calendar # create a plan text calender c = calendar.TextCalendar(calendar.SUNDAY) pt = c.formatmonth(2017, 1, 0, 0) print(pt) # create an HTML formatted calendar hc = calendar.HTMLCalendar(calendar.SUNDAY) st = hc.formatmonth(2017, 1) print(st) # lo...
# Given an elevation map (a 2-dimensional array of altitudes), label the map such that locations in the same drainage basin have the same label, subject to the following rules. # From each cell, water flows down to at most one of its 4 neighboring cells. # For each cell, if none of its 4 neighboring cells has a ...
valores = [] impares = [] pares = [] while True: valor = int(input('Digite um valor: ')) valores.append(valor) if valor % 2 == 0 and valor != 0: pares.append(valor) else: impares.append(valor) continuar = input('Quer continuar [S/N] ') str(continuar) while continuar != 's'...
from time import sleep # Repetição simples: for c in range(1, 6): print('Olá!') print('FIM') print() # Contagem regressiva: for c in range(10, -1, -1): print(c) sleep(1) print() # Pedindo para o usuário definir os valores do range do laço for: inicio = int(input('Defina o valor inicial (inteiro): ')) fin...
# Faça um algoritmo que leia o preço de um produto e mostre seu novo preço com 5% de desconto p = float(input('Qual o valor original do produto? ')) d = float(input('Qual o valor do desconto que está aplicado? ')) print(f'Com {d}% de desconto, o preço anterior passa a valer R${p - p * (d / 100):.2f}')
nome = str(input('Qual é seu nome? ')).strip().lower() if nome == 'joão': print('Que nome lindo você tem!!!') else: print('(Seu nome é tão normal...)') print(f'Olá, {nome.title()}!')
matriz = [[], [], []] for linha in range(0, 3): for coluna in range(0, 3): numero = int(input(f'Digite um número para a posição [{linha}, {coluna}]: ')) matriz[linha].append(numero) for linha in range(0, 3): for coluna in range(0, 3): print(f'{matriz[linha][coluna]:^5}', end=' | ') ...
# Faça um progrma que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possíveis sobre ele valor = input('Digite algo para te dar informações sobre: ') print('A informação dada é um tipo primitivo:', type(valor)) print('Aqui, "True" significa "sim" e "False" significa "não" ;)') pr...
frase = str(input('Digite uma frase: ')).lower().strip() print(f"A letra 'a' aparece {frase.count('a')} vezes") print(f"A primeira posição em que aparece é no caractere de número {frase.find('a') + 1}") print(f"A última posição em que aparece é no caractere de número {frase.rfind('a') + 1}")
from statistics import mean parametro = '' numeros = [] while parametro != 'n': num = int(input('\nDigite um número: ')) numeros.append(num) parametro = str(input('Quer continuar? [S/N] ')).strip().lower() while parametro != 's' and parametro != 'n': print('Valor inválido!') parametro...
def aumentar(num, porcentagem, form_moeda: bool = False): """ -> Calcula o valor acrescido de uma determinada porcentagem :param num: numero que será acrescido da porcentagem :param porcentagem: valor da porcentagem a ser calculada :param form_moeda: (opcional) formata o valor para tipo moeda :r...
n1 = float(input('Digite o primeiro número: ')) n2 = float(input('Digite o segundo: ')) if n1 > n2: print('O primeiro número é maior') elif n2 > n1: print('O segundo número é maior') else: print('Os dois números são iguais')
valores = [] while True: valor = int(input('Digite um valor: ')) valores.append(valor) continuar = '' while continuar != 's' and continuar != 'n': continuar = input('Gostaria de continuar? [S/N] ') str(continuar).strip().lower() if continuar != 's' and continuar != 'n': ...
def notas_alunos(*n, sit=False): """ -> Função que analisa notas e situações de vários alunos :param n: uma ou mais notas dos alunos (aceita mais de um parâmetro) :param sit: (opcional) indica se deve ou não adicionar a situação da turma :return: um dicionário com o menor e maior valores informados,...
print('Me deixe saber se você ultrapassou o limite de velocidade.') print('Lembrando que a cada km a mais do limite, você paga 7 reais.') km = float(input('Diga-me qual foi a velocidade máxima que você obteve: ')) if km > 80: multa = (km - 80.0) * 7 print(f'Você passou do limite de velocidade! Sua multa custará...
from datetime import date pessoa = dict() data_atual = date.today().year nome = str(input('Nome: ')).strip().title() pessoa['nome'] = nome idade = data_atual - int(input('Ano de nascimento: ')) pessoa['idade'] = idade ctps = int(input('Carteira de trabalho (0 "não tenho"): ')) if ctps != 0: pessoa['ctps'] = ctps...
''' class (成人の)BMI: 関連しそうな属性: - 身長 - 体重 - BMIという値そのもの ルール: - 10以上40以下<-- 常識的な範囲 - 表示するときは、小数点第2位まで - ex: 23.678 -> 23.67 - ex: 23.671 -> 23.67 できること: - ??? ''' # クラス名はUpperCamelCaseが普通 class BMI: def __init__(self, height, weight): ...
import pygame import math import random # ----- Constants ----- WIDTH = 600 RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) OBSTACLE_COLOR = (0, 0, 0) FREE_COLOR = (255, 255, 255) END_COLOR = (0, 21, 255) PURPLE = (185, 8, 255) LINE_COLOR = (168, 166, 158) START_COLOR = (255, 135, 8) OPEN_COLOR = (52, 235, ...
#! /usr/bin/env python #Decode an input morse code string that lacks spaces into meaningfull words import anytree as tree import enchant import encode #Define dictionary to convert morse to char d = enchant.Dict("en_US") morse_text = {'.-':'a', '-...':'b', '-.-.':'c', '-..':...
#!/usr/bin/python import math def primes(n, start = 2): for i in xrange(start, int(math.sqrt(n)) + 1): if not n % i: return [i] + primes(n / i, i) return [n] print primes(600851475143)
from dna import dna from random import randrange,randint,random class population: def __init__(self,num, max_population, mutationR): self.population=[dna(num) for i in range(max_population)] self.parents=[] self.generations=0 self.finished=False self.mutation_rate=m...
import random class Cell: """ A simple cell class that stores the current state of the cell and can be printed as a * for alive and - for dead """ def __init__(self,state): self.state = state self.lived = 0 self.ID = random.random() def __str__(self): if self.state: ...
import collections print(collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])) print(collections.Counter({'a': 2, 'b': 3, 'c': 1})) print(collections.Counter([1, 2, 3, 2, 4, 4, 6, 7, 7, 8, 1, 4]))
__author__ = 'BR' """ Author: BIKASH ROY File name: Assignment7_itemset.py """ import psycopg2 host = input("Enter the db host name.") dbname = input("Enter db name.") port = input("Enter port number to connect to db") user = input("Enter username.") password = input("Enter password") # make connection to the databa...