text stringlengths 37 1.41M |
|---|
import random
Array = []
n = 30
while True:
num = random.randint(0, n)
if num not in Array :
Array.append(num)
if len(Array) == n :
print(Array)
break
|
# Question:
# Write a program that accepts a sentence and calculate the number of letters and digits.
line = input()
my_dict = dict()
digit = 0
letter = 0
for item in line:
if item.isdigit():
digit += 1
my_dict['digits'] = digit
elif item.isalnum():
letter += 1
my_d... |
# Question:
# Write a program which accepts a sequence of comma-separated numbers from console and
# generate a list and a tuple which contains every number.
# Suppose the following input is supplied to the program:
my_input = input().split(",")
my_list = list(my_input)
my_tuple = tuple(my_input)
print(my_li... |
# Question:
# Define a function which can print a dictionary
# where the keys are numbers between 1 and 20 (both included)
# and the values are square of keys.
# Empty dictionary can be created by below methods.
my_dict = dict() # OR
# my_dict = {}
print(" -- Method-1 -- ")
def square_it():
... |
listdata = list(range(5))
listdata.reverse()
print(listdata) # [4, 3, 2, 1, 0]이 출력됨
|
#!/usr/bin/env python
# coding: utf-8
# In[164]:
k = input('이름을 입력하세요')
print('당신이 입력한 이름은 <'+k+'>입니다.')
# In[165]:
numdata = 57
strdata = '파이썬'
listdata = [1,2,3]
dictdata = {'a':1, 'b':2}
def func():
print('안녕하세요.')
print(type(numdata))
print(type(strdata))
print(type(listdata))
print(type(dictdata))... |
listdata = list(range(5))
ret1 = reversed(listdata)
print('원본 리스트 ', end='');print(listdata);
print('역순 리스트 ', end='');print(list(ret1))
ret2 = listdata[::-1]
print('슬라이싱 이용 ', end='');print(ret2)
|
class LineSearchResult:
""" A simple structure for storing the results of line search procedures.
't': argmin_s f(x + s*dx)
'x': optimal x found by golden section search
"""
def __init__(self, success, x, t):
"""
Args:
success: line search terminated successfully
... |
class Country(object):
def __init__(self, id, name):
self.id = id
self.name = name
self.offers = []
self.price_sum = 0
self.price_average = 0
def add_offer(self, offer):
if offer not in self.offers:
self.offers.append(offer)
self.price_sum... |
"""
* http://www.pythonchallenge.com/pc/def/ocr.html
* Python Challenge Level 2
"""
import urllib.request
import re
html = urllib.request.urlopen("http://www.pythonchallenge.com/pc/def/ocr.html").read().decode()
comments = re.findall("<!--(.*?)-->",html, re.DOTALL)
data = comments[1]
count = {}
for c in data:
... |
def handle_numbers(n1, n2, n3):
my_sum = 0
for i in range(n1, n2 + 1):
if i % n3 == 0:
my_sum += 1
return my_sum
def handle_string(value):
result = {
'letters': 0,
'digits': 0
}
for symbol in value:
if symbol.isalpha():
result['letters'] ... |
import machine, neopixel
from math import *
from PinsDefinition import *
#from functools import *
""" Neopixel library:
The ring is a array of tuple (r,v,b) from 0 to nbLedRing-1
"""
def reduce(function, iterable, initializer=None):
it = iter(iterable)
if initializer is None:
value = next(it)
... |
k=-1
while(k!=0):
while(k<0):
k=int(input('Insira K: '))
if(k!=0):
if(k%2==0):
acum=0
for i in range(2,k):
if(i%2!=0):
acum=acum+i
print(acum)
k=-1
|
# ler 6 valores X.
# encontrar e mostrar o maior valor de x.
m=-999
for i in range(6):
x=int(input('Digite o Valor de X: '))
if (m<x):
m=x
if (m==0):
print('Não Foram Digitados Valores Válidos')
else:
print(f'O Maior Valor foi {m}') |
# 066 - varios numeros inteiros teclado. para quando digitar 999.
# mostre quandos digitados e qual a soma desconsiderando a FLAG.
acum=0
som=0
while True:
n=int(input('Digite um Numero '))
if(n==999):
break
som+=n
acum+=1
print(f'Foram Digitados {acum} Números e o Somatório foi de {som}') |
#ler x e y, calacular e mostrar a tabuada dos numeros inteiros entre x e y divisiveis por 3
#no final mostrar a tabuada dos numeros inteiros divisiveis por 3
x=int(input("variavel X: "))
y=x-1
while(y<x):
y=int(input("variavel Y: "))
cont=0
for i in range(x+1,y):
if(i%3==0):
cont=cont+1
... |
sal_fix=int(input('Insira o Salário Fixo em R$ '))
ven=int(input('Insira o valor das Vendas em R$ '))
com=ven*0.05
sal_tot=sal_fix+com
print('\nO Salário Fixo é R$ %.0f'%sal_fix)
print('As Comissões são R$ %.0f'%com)
print('Salário Total é R$ %.0f'%sal_tot) |
# ler valores X e Y. constir que Y receba maior que X.
# após mostrar tabuada de 1 a 10
# de cada um dos inteiros entre x e y.
x=int(input('Insira o Valor de X: '))
y=x-1
while(y<x):
y=int(input('Insira o Valor de Y: '))
for i in range (x+1,y):
for c in range (1,11):
tab=c*i
print(f'Tabua... |
# LERvalKate0consisSEMnegKcadaKparSOMATimp1eK
# provavelmente com ERRO.
k=-1
while(k!=0):
while(k<0):
k=int(input('Digite o Valor de K '))
if(k%2==0):
som=0
for i in range(2,k):
if(i%2!=0):
som+=i
print(f'O Somatório é {som}')
k=-1 |
for i in range(5):
w=int(input('Digite Valor do W: '))
if(w%2==0):
for j in range(1,w+1):
t=w*j
print(t)
else:
f=1
for j in range(1,w+1):
f=f*j
print(f)
|
#TEMAlêV[10].AposAtualizarElementosResultadoMultiplicaçãoElementoPeloIndice,adicionadoaseguir,pelovalorcontidosegundoelementodovetor.
v=[0]*10
v1=int
for i in range(10):
v[i]=int(input(f'Digite o Valor de V{i}: '))
if(i==1):
v1=v[i]
for i in range(10):
v[i]=(v[i]*i)+v1
print(f'O Valor Atualizado... |
#TEMAlêV[6].ClassificarEmOrdemCrescente.FinalMostrarVetor.
#ESTA ERRADA. NAO CONSEGUI TERMINAR. FALTOU TEMPO.
v=[0]*4
v1=int
v2=int
v3=int
v4=int
for i in range(4):
v[i]=int(input(f'Digite o Valor de V{i}: '))
if(i==0):
v1=v4=v[i]
if(v1>v[i]):
v1=v[i]
if(v[i]>v1 and v[i]<v4):
v2... |
from tkinter import *
from math import *
window = Tk()
window.title("Simple Calculator")
entry = Entry(window, width=55, borderwidth=5, bg="red")
entry.grid(row=0, column=0, columnspan=4)
def click_num(number):
comment = entry.get()
entry.delete(0, END)
entry.insert(0, str(comment)+str(number))
def cl... |
import random
def reservoir_sample(iterator, k):
"""
Gathers a random sample of k elements or less from an iterator.
:param iterator: an iterator that provides the elements
:param k: the maximum amount of elements that should be sampled
:return: a list with k elements if iterator has at least k el... |
# This are my implementations of two algorithms that find a maximum subarray
# (a subarray whose sum is maximum).
#
# It is also possible to find the maximum subarray by testing C(n, 2) pairs.
# This is the brute-force approach and it is O(n^2). Don't use this.
#
# The first one finds the maximum subarray using D&C in ... |
# Python Standard Libraries
# N/A
# Third-Party Libraries
# N/A
# Custom Libraries
import trees
def breadth_first_search(node_queue):
"""Sometimes this is called 'level-order' searching
Arguments:
node_queue (List of Node): a FIFO style array
"""
can_current_node_be_processed = (len(node_que... |
#!/usr/bin/python3
charend = ", "
for i in range(0, 100):
digit2 = i % 10
digit1 = i / 10
if i < 10 and digit1 < digit2:
print("{}{}".format(0, i), end=charend)
elif digit1 < digit2:
if i == 89:
charend = "\n"
print(i, end=charend)
|
#!/usr/bin/python3
if __name__ == "__main__":
import sys
i = 0
argcont = len(sys.argv) - 1
if argcont == 1:
print("1 argument", end="")
elif argcont != 1:
print("{} arguments".format(argcont), end="")
if argcont == 0:
print(".")
else:
print(":")
if(len(sys... |
#!/usr/bin/python3
charend = ", "
for i in range(0, 100):
if i < 10:
print("{}{}".format(0, i), end=charend)
else:
if i == 99:
charend = "\n"
print(i, end=charend)
|
#!/usr/bin/env python2
with open("ciphertext","r") as ciphertext:
cipher = ciphertext.read()
ciphertext.close()
# contains picoCTF
edited = cipher[0:7]
'''
# display ord of 1st 7 chars of ciphertext
for i in edited:
print ord(i)
print "start\n"
# display ord of picoCTF
for i in "picoCTF":
print ord(i)... |
import cmath
import random
import calendar
'''
num=int(input('input a num'))
num_sqrt=cmath.sqrt(num)
print(num_sqrt,type(num_sqrt))
'''
'''
for x in range(0, 9):
print(random.randint(0, 9), end=' ')
'''
'''
try:
float('qwe')
except ValueError as Argument:
print(Argument)
pass
print('hello world')
'... |
print ('please input a number')
num = int(input())
sum = 0
for i in range(1,num):
if num%i == 0:
sum += i
if sum == num:
print ('this is Perfect number')
else:
print ('this is not Perfect number')
|
number = input("Write an integer value: ")
result = 0
if len(number) >= 2:
result = + int(number[-1]) + int(number[-2])
print(result)
else:
print("0" + number[-1]) |
print('ı can solve a equation in addition it has to be like "ax**2+bx+c= 0"')
a = float(input('write an "a" '))
b = float(input('write a "b" '))
c = float(input('write a "c" '))
delta = b * b - (4 * a * c)
print(f"Delta is {delta} and then:")
if delta > 0:
print('There are two term for x:')
x1 = ((-b) + (floa... |
numbers1 = [2, 3, 4, 20, 5, 5, 15]
numbers2 = [10, 20, 20, 15, 30, 40]
numbers1Set = set(numbers1)
numbers2Set = set(numbers2)
intersection = set()
union = set()
for number in numbers1Set:
for values in numbers2Set:
if values == number:
intersection.add(values)
for member in numbers1Set:
union.add(member... |
def PascalTriangle(n):
if n == 1:
ReturnedList = [[1]]
return ReturnedList
else:
predetermined = [1, 1]
nestedList = PascalTriangle(n - 1)
calculation = nestedList[-1]
for index in range(len(calculation) - 1):
predetermined.insert(1, calculation[index... |
"""Burada 'memorization'dan bahsedeceğiz. Memorization bazı tekniklerle hafızayı manüpüle etmektir.
Buradaki recursionı yormamak adına eğer daha önceden o değer hesaplandıysa onu bir sözlüğe atıp
gerektiğinde onu sözlükten çekip hesaplamayı tekrarlamaya gerek kalmadan dönebilmektir"""
fiboCache = {}
def fib(n):
if ... |
import time
def rvowel(s):
##recursive vowel counter
if len(s) == 1 and s.upper() in ['A','E','I','O','U']:
return 1
elif len(s) == 1 and not(s.upper() in ['A','E','I','O','U']):
return 0
else:
return rvowel(s[:int((len(s))/2)]) + rvowel(s[int((len(s))/2):])
def vowel(s):
#regul... |
# This file to demonstrate basic understand about urllib work
# Used to make request
from urllib.request import urlopen
# used to parse values into the url
import urllib.parse
# x = urlopen('https://en.wikipedia.org/wiki/Kevin_Bacon')
# print(x.read())
url = 'https://pythonprogramming.net/?s=basics&submit=Search'
va... |
# -*- coding: utf-8 -*-
from collections import Iterator,Iterable
import time
import calendar
localtime = time.localtime(time.time())
print(localtime)
print(time.asctime(localtime))
print((x for x in range(10)))
g = (x for x in range(10))
for x in g:
print(x)
#99乘法表
for i in range(1,10):
for j in range(1,i+1... |
print("Hello World")
print(1 + 2)
print(7 * 6)
for i in range(11):
print(i)
print("Python's strings")
print('Something with "double" quote')
print("Hello " + "Word")
greeting = "Hello"
name = "Bruno"
# print Hello <name>
print(greeting + ' ' + name)
# print with keyboard input
# name = input("Please enter your ... |
def is_family(tree):
fathers = [i[0] for i in tree]
sons = [i[1] for i in tree]
# fathers 中的名字不能有超过一个出现在 sons 中
if len([i for i in set(fathers) if i not in set(sons)]) > 1 :
return False
# 父子不能反向
for i in tree :
if i[::-1] in tree :
return False
# 兄弟不能成父... |
def checkio(marbles, step):
l = [(marbles, 1)]
for i in range(step-1):
l = children(l)
p_list = []
for marble,p in l:
b = marble.count("b")
w = marble.count("w")
p = p*w/(w+b)
p_list.append(p)
return round(sum(p_list),2)
def children(l_in):
# 根据上一级的一个 list,生成下一级的list
# 上一级:[(marble, p),(marble, p... |
#lista_nomes = ['kauan', 'pedro', 'vitor', 'gabriel']
#
#for nome in lista_nomes:
# print(nome)
#else:
# print('todos os nomes da lista foram impressos')
#
#for item in range(0, 11, 2):
# print(item)
escada = ""
caractere = input('caractere: ')
numero_degraus = int(input('degraus: '))
for item in range(0, num... |
def check_prime(num):
j = num
counter = 0
for i in range(2, j):
if j % i == 0:
counter = 1
if counter == 0:
print(str(j) + " is a prime number")
else:
print(str(j) + " is not a prime number")
check_prime(111) |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Autor: Nerea Del Olmo Sanz
# Ej: 13.3.- Tablas de multiplicar
print "\nTablas de Multiplicar\n---------------------"
numbers = range(11)
for number_i in numbers:
print "\nTabla del " + str(number_i) + "\n------------"
for factor_i in numbers:
multiplication = number_... |
import sys
def merge(a, b):
c = []
while a and b:
if a > b:
c.append(b.pop(0))
else:
c.append(a.pop(0))
while a:
c.append(a.pop(0))
while b:
c.append(b.pop(0))
return c
def merge_sort(list):
if len(list) == 1:
return list
mid = int(len(list) / 2)
a = []
b = []
for el in list[:mid]:
a.app... |
import numpy as np
from freya.layers import Layer
class MeanSquaredError(Layer):
"""Mean squared error.
A layer to compute the mean squared error of the neural network. Freya
assumes the loss layer is the last of the network; hence, it does not need
the error of the following layer.
Par... |
import matplotlib.pyplot as plt
int_value = [1, 2, 3, 4, 5]
squares = [1, 4, 9, 16, 25]
plt.plot(int_value, squares, lw = 5)
# 设置标题,并给坐标轴加上标签
plt.title("Square Numbers", fontsize = 24)
plt.xlabel('Value', fontsize = 14)
plt.ylabel('Square of Value', fontsize = 14)
# 设置刻度标记的大小
plt.tick_params(axis='both', labelsize =... |
class Car():
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def get_descriptive_name(self):
long_name = str(self.year) + " " +self.make + " " + self.model
return long_name
class Battery():
def __init__(self, battery_... |
print('enter "q" to quit ')
while 1:
first_number = input('please input 1st number:')
if first_number == 'q':
break
second_number = input('please input 2rd number:')
if first_number == 'q':
break
try:
answer = int(first_number) + int(second_number)
except ValueError:
... |
def time_converter(time):
if time == "00:00":
return "12:00 a.m."
t = time.split(":")
res = ""
if int(t[0]) > 12:
res += str(int(t[0]) % (12 + 1) + 1)
else:
res += str(int(t[0]))
res += ":"
res += t[1]
res += " "
if int(t[0]) > 11:
res += "p.m."
el... |
# CTI 110
# Airelle Hall
# Norris. A
# 20 Sept 2017
# Software Sales
# Write a program that asks users for the numbers of packaged purchased
numberOfPackages = int(input('How many packages do you have?' ))
# Each package is $99.00
packagePrice = 99.00
if numberOfPackages < 10:
discount = 0
elif numberOfP... |
# CTI 110
# M5Lab: Nested Loops
# Hall, A
# 16 Oct 2017
# Commands To Use Turtle
import turtle
import random
win = turtle.Screen()
m = turtle.Turtle()
# Random Pen Colors and Speed
colours = ['yellow','teal','black']
m.speed (7)
#Display for turtle
m.pensize(7)
m.shape('turtle')
m.pencolor('black')
# Command for... |
import os
def file_extension_matches(filename, pattern_list):
path, extension = os.path.splitext(filename)
# strip ext separator
extension = extension[1:]
extension = extension.lower()
return extension in pattern_list
def file_is_picture(filename):
return file_extension_matches(filename,('jpg'... |
#!/usr/bin/env python
from stock import Stock
import utils
from pandas import DataFrame
import sys
# Enable to print additional information
DEBUG = False
companies = []
stocks = []
fields = {}
# dataframe object
df = {}
# the file where stock ticker list can be found
# defaults to companies.txt
src_file = "watc... |
# the sorted function takes a sequence as an argument and returns a
# sorted list
# my_list = [17, 4, 26, 2]
# # must use an assignment to function. without assigning to a variable # # the function won't work
# my_list2 = sorted(my_list)
# print("Sorted list: ", my_list2)
#
# my_tuple = (17, 4, 26, 2)
# # ... |
import urllib.request
from bs4 import BeautifulSoup
# Method inspired by Jason Brooks on stack overflow.
# Link to answer: https://stackoverflow.com/questions/29069444/returning-the-urls-as-a-list-from-a-youtube-search-query
def askSearch():
results = []
query = input("Please enter the name of the video you wou... |
"""
The amount of energy required to increase the temperature of one gram of a material
by one degree Celsius is the material’s specific heat capacity, C. The total amount
of energy required to raise m grams of a material by ΔT degrees Celsius can be
computed using the formula:
q = mCΔT.
Write a program that reads the ... |
"""
Canada has three national holidays which fall on the same dates each year.
Holiday Date
New year’s day January 1
Canada day July 1
Christmas day December 25
Write a program that reads a month and day from the user. If the month and day
match one of the holidays listed previously then your program should display the... |
"""
This program reads a number input from the user and sums all the positives integers from 0 to n
"""
def main(number):
sum = int((number * (number + 1)) / 2)
return print(f"The sum of all integers from 0 to {number} are: {sum}")
if __name__ == "__main__":
number = int(input("Input a number tu sum all ... |
"""
In the United States, fuel efficiency for vehicles is normally expressed in miles-pergallon (MPG). In Canada, fuel efficiency is normally expressed in liters-per-hundred
kilometers (L/100 km). Use your research skills to determine how to convert from
MPG to L/100 km. Then create a program that reads a value from th... |
"""
The following table contains earthquake magnitude ranges on the Richter scale and
their descriptors:
Magnitude Descriptor
Less than 2.0 Micro
2.0 to less than 3.0 Very minor
3.0 to less than 4.0 Minor
4.0 to less than 5.0 Light
5.0 to less than 6.0 Moderate
6.0 to less than 7.0 Strong
7.0 to less than 8.0 Major
8.0... |
"""
The year is divided into four seasons: spring, summer, fall and winter. While the
exact dates that the seasons change vary a little bit from year to year because of the
way that the calendar is constructed, we will use the following dates for this exercise:
Season First day
Spring March 20
Summer June 21
Fall Septe... |
import os
from shutil import copy
import tkinter as tk
from tkinter import filedialog
from tkinter.filedialog import askdirectory
# Variables
subfolders = []
files = []
filestocopy = []
# Functions
def getListOfFiles(dirName):
listofFiles = os.listdir(dirName)
allFiles = list()
for entry in listofFiles... |
def binary_search(arr, low, high, x):
#Check the base condition
if high >low :
mid = (high+low)//2
#If element is present at the middle itself
if arr[mid] == x:
return mid
#If element is smaller than mid, then it can only be present in left subaaray
elif arr[mid]>x:
... |
def binary_search(arr, x):
low=0
high= len(arr)
mid=0
while low <high:
mid = (high+low)//2
#if x is greater than mid, then we can ignore left subarray can be ignored.
if arr[mid] < x:
low= mid+1
elif arr[mid]> x:
high = mid-1
else:
return mid... |
class node:
def __init__(self, data = None):
self.data = data
self.next = None
class linked_list:
def __init__(self):
self.head = node()
def append(self, data):
new_node = node(data)
cur = self.head
while cur.next!=None:
cur = cur.next
... |
import unittest
from app.api.v1.utils.validators import Verify
class TestValidators(unittest.TestCase):
def setUp(self):
self.data = Verify()
def tearDown(self):
self.data = None
def test_empty_data(self):
'''method to test if data is empty'''
test = self.data.is_empty(... |
#selection06.py
a = int(input("첫째 정수 입력:"))
b = int(input("둘째 정수 입력:"))
op = input("연산자 입력:")
if op == "+":
print(a+b)
elif op == "-":
print(a-b)
elif op == "*":
print(a*b)
elif op == "/":
print(a/b)
else :
print("unknown operator")
|
f=open('E:\Perepis.txt','r')
l=list()
s=str()
a=int(input('от 19ХХ'))
b=int(input('до 19ХХ'))
for i in f:
l=i.split(" ")
s=l[3]
if a<int(s[8:])<b:
print(i)
|
from collections import Mapping
from copy import deepcopy
class Grid(Mapping):
"""
A Grid is a two-dimensional data-structure.
>>> g = Grid(5, 5)
>>> Grid.pprint(g)
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
>>> g[0, 0] = 1
>>> g[4, 4] = 1
>>> Grid.pprint(g)
... |
def selection_sort(arr):
for i in range(len(arr)):
min_i = i
for j in range(i+1, len(arr)):
if arr[min_i] > arr[j]:
min_i = j
arr[i], arr[min_i] = arr[min_i], arr[i]
return arr
def bubble_sort(arr):
for i in range(len(arr)):
for j in range(len(ar... |
import numpy as np
x_data = [[0, 0],
[10, 0],
[0, 10],
[10, 10]]
y_data = [1, 1, 0, 0]
def sigmoid(x):
return 1.0/(1.0 + np.exp(-x))
def sigmoid_derivate(o):
return o * (1.0 - o)
def train(x_data, y_data):
w0, w1, w2 = np.random.rand(3)
lr = 0.1
epochs = 10000
... |
#Exercise!
#Display the image below to the right hand side where the 0 is going to be ' ', and the 1 is going to be '*'. This will reveal an image!
picture = [[0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0]]
for item in... |
#Enter the starting balance
balance = 4213
#Enter the interest rate
annualInterestRate = 0.2
#Enter the payment rate as a % of balance
monthlyPaymentRate = 0.04
#placeholder for total amount paid
totalPaid = 0.0
for i in range(1,13):
print("Month: " + str(i))
currentMinPayment = (monthlyPaymentRate*balance)
... |
import math
import sys
from functools import reduce
class Point:
"""Point is a basic 2-d Cartesian pair. This is used as the corners of
of a Rectangle. Some operators are defined on points:
('+', '-', '==', '<', '>')
"""
def __init__(self, x, y):
self.x = x
self.y = y
def co... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 27 23:37:09 2021
@author: imacpro
"""
import pandas as pd
election_data_file = "Resources/election_data.csv"
election_data_df = pd.read_csv(election_data_file)
#election_data_df.head()
#Total number of votes
totalvotes = election_data_df["Voter I... |
import os
def main():
while True:
menu()
num = int(input("请输入您选择的序号:"))
if num == 0:
answer = input("您 确定要退出吗?y/n")
if answer == 'y':
print("感谢您使用本系统!!!")
break
else:
continue
elif num == 1:
... |
exampleList = [1,5,6,6,2,1,5,2,1,4]
for x in exampleList:
print(x)
print('\n')
for x in range(1,11):
print(x)
print('\n')
edibles = ["ham", "spam", "eggs","nuts"]
for food in edibles:
if food == "spam":
print("No more spam please!")
continue
print("Great, delicious " + food)
# h... |
'''
Given two integer N and K, find the minimum number of times N must be multiplied by X to make it divisible by (2K).
Where X = Summation (2(4*i)) for 1 <= i <= 25.
Input
The first and the only line of input contains two space separated integers N and K.
Constraints
1 <= N <= 10^18
1 <= K <= 10^18
Output
Print a sin... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the solve function below.
def solve(s):
result = ""
list_string =list(map(str,s.split()))
for item in range(len(list_string)):
if (list_string[item][0]>=0 and list_string[item][0]<=9) :
... |
"""
Solución del laboratorio
"""
from custom_functions import temperature_methods
import statistics as stats
santanderstemperature_list=[]
print("please enter the temperatures of the department of santander")
for i in range(0, 12):
temperature = int(input("give me the temperature of month {} ".format(i+1)))
... |
def story2():
ques1 = input("you was hiking with you friends on the everest.blizzard came, and caught you surprised.after the blizzard you could not find your friends.couple of bears are chasing you right now.press y to keep runing(you won't last long).press n to climb on a tree.")
if ques1 == 'y':
ques... |
import time
import sys
import random
# Initialize player
class Player:
def __init__(self):
self.name = ''
self.item = ''
self.hp = 100
self.modifiers = 1
def print_stats(self):
delay_print(0.05, f'\n\n\nYour health is {self.hp}. Your current modifier is {self.modifier... |
print('Digite um comprimento em polegadas, que será convertido em centímetros')
P = float(input('Comprimento: '))
C = P * 2.34
print(f'O comprimento em centímetros é: {C} e em polegadas é: {P}') |
print('Digite um número inteiro, que irá aparecer a soma do sucessor de seu triplo com o antecessor de seu dobto')
num = int(input('Número: '))
s = num * 3
a = num * 2
soma = s + a
print(f'A soma do sucessor de seu triplo com o antecessor de seu dobto é: {soma} e o número escolhido foi: {num}') |
print('Digite um numero real, que irá ser elevado ao quadrado')
num = float(input('Número: '))
print(f'O número ao quadrado foi: {num ** 2}') |
print('Digite um comprimento em jardas, que será convertido em metros')
J = float(input('Comprimento: '))
M = 0.91 * J
print(f'O valor em metros é: {M} e em jardas é {J}') |
print('Digite as respostas das somas')
import random
count = 0
acertos = 0
while count < 5:
count = count + 1
num1 = random.randint(0, 99)
num2 = random.randint(0, 99)
resp = int(input(f'Digite a soma de {num1} + {num2}: '))
Resp = num1 + num2
if resp != Resp:
print(f'Você errou a soma ... |
print('Digite o preço do produto e o estado(1-4), para ver qual o preço cobrado')
print('1- MG 7%; \n'
'2- SP 12%; \n'
'3- RJ 15%; \n'
'4- MS 8% \n')
preco = float(input('Preço: '))
estado = int(input('Estado: '))
if estado == 1:
imposto = preco * (7/100)
precofinal = preco + imposto
... |
print('Digite o valor de um produto e este irá receber 12% de desconto')
valor = float(input('Preço: '))
desconto = valor * (12/100)
valor_com_desconto = valor - desconto
print(f'O novo valor com o desconto será: {valor_com_desconto} e o preço antigo era: {valor}') |
print('Digite a distância em Km e a quantidade de litros de gasolina consumidos, para calcular o consumo em km/l')
km = float(input('km: '))
l = float(input('litros: '))
consumo = km / l
if consumo < 8:
print('Venda o carro!')
elif 7 < consumo <12:
print('Econômico!')
elif consumo > 12:
print('Super econômi... |
print('Digite 1, 2, 3 ou 4, para escolher qual operação:')
print(['1-Soma', '2-Subtração', '3-Multiplicação', '4-Divisão'])
num = int(input('Número: '))
print('Agora digite dois valores para essa operação')
num1 = float(input('Número 1: '))
num2 = float(input('Número 2: '))
if num == 1:
soma = num1 + num2
print... |
print('Digite um numero inteiro')
num = int(input('Número: '))
print(f'O número escolhido foi: {num}') |
import csv
#Setting intial variables which will be used in more than one of the steps
years = []
months = []
count = []
#Finding Min, Max and avg for overall dataset
#Gives initial comand for reading in the csv file into python code fort this step
with open("co2-ppm-daily.csv") as CO:
csv_reader = csv.reader(CO,... |
#Chris Rubio
#1530668
print('Birthday Calculator')
print('Current day')
#current day variables
month = int(input('Month: '))
day = int(input('Day: '))
year = int(input('Year: '))
print('Birthday')
#bday variables
bday_month = int(input('Month: '))
bday_day = int(input('Day: '))
bday_year = int(input('Year: '))
#age v... |
__date__ = "09/2020"
__author__ == "lulu"
# # Write your code here
import random
import string
import sys
print("H A N G M A N")
# def menu():
# player_choice = input("Type 'play' to play the game, 'exit' to quit: ")
# return player_choice
flag = True
while flag:
word_list = ['python', 'java', 'kotlin'... |
food = input("Enter Food Items In Increasing Order OF calories seperated by comma : ").split(",")
print(food)
print(list("Using Rev Method : ",reversed(food)))
print("Using Sliceing : ",food)
leng=len(food)
for i in range(leng//2):
a=food[i]
b=food[-i-1]
food[i]=b
food[-i-1]=a
print(food) |
no=22
print("You have 5 times to guess!")
n=5
while n>=1 :
inp = int(input("Enter your no : "))
if no>inp :
print("You entered grater")
elif no<inp :
print("You entered less")
else:
print("You Win !!!")
break
n=n-1
if n==0 :
print("Game Over!!")
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.