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 INSS.
b. quanto pagou ao sindicato.
c. o salrio lquido.
d. calcule os descontos e o salrio lquido, conforme a tabela abaixo:
e. + Salrio Bruto : R$
f. - IR (11%) : R$
g. - INSS (8%) : R$
h. - Sindicato ( 5%) : R$
= Salrio Liquido : R$
Obs.: Salrio Bruto - Descontos = Salrio Lquido."""
valorHora = float(input("Digite quanto voc ganha por hora: "))
Hora = float(input("Digite quantas horas voce trabalhou nesse mes: "))
salarioBruto = valorHora * Hora
IR = (11*salarioBruto)/100
INSS = (8*salarioBruto)/100
sindicato = (5*salarioBruto)/100
descontos = INSS + IR + sindicato
salarioLiquido = salarioBruto - descontos
print("Salario Bruto: R$%0.2f" %salarioBruto)
print("Voce pagou R$%0.2f ao INSS" %INSS)
print("Voce pagou R$%0.2f ao Sindicato" %sindicato)
print("Salario Liquido: R$%0.2f" %salarioLiquido)
|
"""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,305, 301, 101, 311, 111, 25, 20, 10, 21, 11, 1, 7 e 16
"""
num = int(input("Digite um numero menor que 1000: "))
centena = int(num / 100)
resto = num % 100
dezena = int(resto / 10)
resto = resto % 10
print(num)
print(centena)
print(dezena)
print(resto) |
"""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) : aumento de 20%
o salrios entre R$ 280,00 e R$ 700,00 : aumento de 15%
o salrios entre R$ 700,00 e R$ 1500,00 : aumento de 10%
o salrios de R$ 1500,00 em diante : aumento de 5% Aps o aumento ser realizado, informe na tela:
o o salrio antes do reajuste;
o o percentual de aumento aplicado;
o o valor do aumento;
o o novo salrio, aps o aumento.
"""
salario = float(input("Digite o valor do seu salario R$ "))
if salario <= 280:
percentual = 20 / 100
reajuste = salario * percentual
novoSalario = salario + reajuste
percentual = percentual*100
print("")
print("Salario inicial R$%0.2f" %salario)
print("Percentual do aumento %i" %percentual)
print("Valor do aumento R$%0.2f" %reajuste)
print("Novo salario R$%0.2f" %novoSalario)
elif salario > 280 and salario <= 700:
percentual = 15 / 100
reajuste = salario * percentual
novoSalario = salario + reajuste
percentual = percentual*100
print("")
print("Salario inicial R$%0.2f" %salario)
print("Percentual do aumento %i/%" %percentual)
print("Valor do aumento R$%0.2f" %reajuste)
print("Novo salario R$%0.2f" %novoSalario)
elif salario > 700 and salario <= 1500:
percentual = 10 / 100
reajuste = salario * percentual
novoSalario = salario + reajuste
percentual = percentual*100
print("")
print("Salario inicial R$%0.2f" %salario)
print("Percentual do aumento %i" %percentual)
print("Valor do aumento R$%0.2f" %reajuste)
print("Novo salario R$%0.2f" %novoSalario)
else:
percentual = 5 / 100
reajuste = salario * percentual
novoSalario = salario + reajuste
percentual = percentual*100
print("")
print("Salario inicial R$%0.2f" %salario)
print("Percentual do aumento %i" %percentual)
print("Valor do aumento R$%0.2f" %reajuste)
print("Novo salario R$%0.2f" %novoSalario) |
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 += float(matrix_list[row][col] * vector_list[col])
alist.append(temp)
return alist
def main():
with open ("data.txt", 'r') as fp:
for line in fp:
line = line.rstrip('\n')
x_list = [i for i in line.split(' ')]
x_list = list(map(int, x_list))
matrix_list = []
for idx in range(len(x_list)):
alist = [1, x_list[idx]]
matrix_list.append(alist)
print(matrix_list)
#vector_list = [segment, slope]
print(vector_list)
final_list = compute_vector(matrix_list, vector_list)
print("X_VAL Y_VAL")
for idx in range(len(final_list)):
print("%f %f" % (matrix_list[idx][1], final_list[idx]))
main()
|
#!/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" % (segment_val, slope_val))
return (segment_val, slope_val)
def compute_grad_variable(adict):
slope = float(0)
segment = float(0)
learning = float(0.001)
dict_len = len(adict)
print(adict)
print(dict_len)
seg_grad = slope_grad = float(0)
while (True):
for key in adict:
x = key
alist = adict[key]
for idx in range(len(alist)):
y = alist[idx]
(seg_val, slope_val) = derivative_of_cost_function(x, y, dict_len, slope, segment)
seg_grad += seg_val
slope_grad += slope_val
grad = float(1 / float(dict_len))
print(grad)
seg_grad = float(seg_grad * grad)
slope_grad = float(slope_grad * grad)
print ("GRAD Segment: %d :: Slope: %d" % (seg_grad, slope_grad))
temp_seg = float(segment - float(learning * seg_grad))
temp_slope = float(slope - float(learning * slope_grad))
print ("TEMP Segment: %d :: Slope: %d" % (temp_seg, temp_slope))
print ("Segment: %d :: Slope: %d" % (segment, slope))
if (segment == temp_seg and slope == temp_slope):
break
else:
segment = temp_seg
slope = temp_slope
print ("Segment: %d :: Slope: %d" % (segment, slope))
return(segment, slope)
theta_segment = 0
theta_slope = 0
def main():
input_dict = defaultdict(list);
x_list = []
y_list = []
input_data = True
with open("grad.txt", 'r') as fp:
for line in fp:
if (input_data):
line = line.rstrip('\n')
x_list = [i for i in line.split(' ')]
input_data = False
else:
line = line.rstrip('\n')
y_list = [i for i in line.split(' ')]
input_data = True
x_list = list(map(int, x_list))
y_list = list(map(int, y_list))
if (len(x_list) != len(y_list)):
print("Syncing error in input and output data X : Y")
else:
for a, b in zip(x_list, y_list):
input_dict[a].append(b)
segment, slope = compute_grad_variable(input_dict)
theta_segment = segment
theta_slope = slope
print("$1: %f :: $2: %f" % (segment, slope))
input_dict.clear()
fp.close()
main()
|
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 :(')
else:
print('Too high :(')
|
"""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 less than n and it is called abundant if this sum exceeds n.
As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.
Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers."""
from functools import reduce
from datetime import datetime
start_time = datetime.now()
def dividers(N):
D = [1] # список делителей
d = 2 # делитель
while (d * d <= N):
if N % d == 0:
D = D + [d]
d_new = N // d
if d_new != d:
D = D + [d_new]
# следующий делитель
d += 1
result = reduce(lambda x, y: x+y, D)
return result
final = 0
rez = 0
for number in range(1, 28123):
for i in range(number):
b = number - i
if dividers(i) > i and dividers(b) > b and b!= 0 and i != 0:
final += number
break
rez += number
print(rez - final)
end_time = datetime.now()
print('Duration: {}'.format(end_time - start_time)) |
"""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 the family: 56003, 56113, 56333, 56443, 56663, 56773, and 56993. Consequently 56003, being the first member of this family, is the smallest prime with this property.
Find the smallest prime which, by replacing part of the number (not necessarily adjacent digits) with the same digit, is part of an eight prime value family."""
from math import sqrt
from itertools import combinations, permutations, product
import copy
def prime(number):
if number == 1 or number == 0:
return True
for i in range(2, int(sqrt(number))+1):
if number % i == 0:
return True
return False
def factorial(number):
fact_sum = 1
if number == 0 or number == 1:
return 1
for i in range(1, number+1):
fact_sum *= i
return fact_sum
def find_eight(prime_number_count, range_find):
for i in range(10000, range_find):
print(i)
n = [int(x) for x in str(i)]
changed = copy.deepcopy(n)
for i in range(0, len(n)-1):
for j in range(1, len(n)):
if i>=j:
continue
changed[i] = '*'
changed[j] = '*'
# print(changed)
prime_score = 0
for k in range(0, 10):
new_digit_lst = [k if x == '*' else x for x in changed]
new_digit = int(''.join(str(i) for i in new_digit_lst))
if not prime(new_digit):
prime_score += 1
if prime_score == prime_number_count:
print(new_digit, changed, prime_score)
return new_digit, changed, prime_score
print(new_digit, changed, prime_score)
changed = copy.deepcopy(n)
if __name__ == '__main__':
"""TESTING prime Function
lst_prime = [29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103,
4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 21, 20, 22, 24, 25, 26, 27, 28, 30, 32, 33, 34, 35, 36, 38, 39, 40]
answers_test_prime = []
answers_test_prime.extend([False for i in range(18)])
answers_test_prime.extend([True for i in range(27)])
for lst_test_prime_number, answer_bool in zip(lst_prime, answers_test_prime):
if prime(lst_test_prime_number) == answer_bool:
print("TEST PASSED!")
else:
print("TEST FAILED!")
"""
print(find_eight(7, 10000000))
|
"""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 score.
For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.
What is the total of all the name scores in the file?"""
names = open("p022_names.txt", "r")
namestr = names.read()
lstnames = list(namestr.split(","))
lstnames.sort()
score = 0
def convert(string):
score = 0
li = []
li[:] = string
for ordinary in li:
value = ord(ordinary) - 64
if value > 0:
score += value
return score
i = 1
final = 0
for n in lstnames:
final += convert(n)*i
i += 1
print(final) |
"""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 recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.
Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part."""
import math
from decimal import *
from datetime import datetime
start_time = datetime.now()
def getfracpart(flnum):
one = 1
lstfracpart = []
for i in range(10000):
score = 0
if one - flnum >= 0:
while one - flnum >= 0:
one = one - flnum
score += 1
lstfracpart.append(str(score))
else:
one = one * 10
return lstfracpart
def guess_seq_len(seq):
guess = 1
seq = [int(i) for i in str(seq)]
max_len = int(len(seq) / 2)
for x in range(2, max_len):
if seq[0:x] == seq[x:2*x]:
return x
return guess
maximum = 1
index = 0
for i in range(2, 1001):
listtostring = ''.join((getfracpart(i)))
if guess_seq_len(listtostring) > maximum:
maximum = guess_seq_len(listtostring)
index = i
print("Maximum - ", maximum,"Index of maximum(d) - ", index)
end_time = datetime.now()
print('Duration: {}'.format(end_time - start_time)) |
"""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-trivial examples of this type of fraction, less than one in value, and containing two digits in the numerator and denominator.
If the product of these four fractions is given in its lowest common terms, find the value of the denominator."""
import math
def search(numerator, denominator):
division = numerator / denominator
numlst = [int(x) for x in str(numerator)]
denlst = [int(y) for y in str(denominator)]
intersection = list(set(numlst) & set(denlst))
if intersection != []:
if len(intersection) == 1:
commonum = intersection[0]
for number in numlst:
if number == commonum and len(numlst) != 1 and len(denlst) != 1:
numlst.remove(number)
denlst.remove(number)
if denlst[0] != 0:
if numlst[0]/denlst[0] == division:
return [numerator, denominator]
else:
return 0
def reduce_fraction(numer, denom):
gen = math.gcd(numer, denom)
return [numer//gen, denom//gen]
denmultiply = 1
numultiply = 1
for den in range(1, 100):
for num in range(1, 100):
if num < den:
if search(num, den) != 0 and search(num, den) != None and num % 10 != 0 and den != 10:
fraction = search(num, den)
rfraction = reduce_fraction(fraction[0], fraction[1])
denmultiply *= fraction[1]
numultiply *= fraction[0]
print(int(denmultiply / numultiply))
|
"""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 > 1:
factorial *= n
n -= 1
return factorial
numberlst = list(str(fact(100)))
numberlst = [int(i) for i in numberlst]
sumoflst = reduce(lambda x, y: x+y, numberlst)
print(sumoflst) |
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', '').replace('\r', '').strip() |
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, expected_output)
def test_a_2(self):
input = [0, 1, 0, 3, 12]
expected_output = [1, 3, 12, 0, 0]
self.sut.moveZeroesDoublePointer(input)
self.assertEqual(input, expected_output)
def test_b_1(self):
input = [1, 0]
expected_output = [1, 0]
self.sut.moveZeroesCounting(input)
self.assertEqual(input, expected_output)
def test_b_2(self):
input = [1, 0]
expected_output = [1, 0]
self.sut.moveZeroesDoublePointer(input)
self.assertEqual(input, expected_output)
def test_c_1(self):
input = [2, 1]
expected_output = [2, 1]
self.sut.moveZeroesDoublePointer(input)
self.assertEqual(input, expected_output)
def test_c_2(self):
input = [2, 1]
expected_output = [2, 1]
self.sut.moveZeroesDoublePointer(input)
self.assertEqual(input, expected_output)
if __name__ == '__main__':
unittest.main()
|
"""
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)):
sum = A[i] if sum<0 else sum+A[i]
max_sum = sum if sum>max_sum else max_sum
return max_sum |
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 in dict.items():
print(key,'=',value)
|
#-*- 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)
#网上借鉴的一行搞定法 lambda
#str1 = "".join((lambda x:(x.sort(),x)[1])(list(str1)))
#str2 = "".join((lambda x:(x.sort(),x)[1])(list(str1)))
if(str1 == str2):
print "是变位词"
else:
print "不是变位词"
|
#!/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))
f.close()
|
#!/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':'Runoob',
'url':'http://www.runoob.com'
}
# 操作json文件
# 写入JSON数据
with open('data.json','w') as f:
json.dump(data,f)
# 读取数据
with open('data.json','r') as f:
data2 = json.load(f)
print(data2)
|
#!/usr/bin/python3
# 文件名:time5.py
"""
Python 程序能用很多方式处理日期和时间,转换日期格式是一个常见的功能。
Python 提供了一个 time 和 calendar 模块可以用于格式化日期和时间。
时间间隔是以秒为单位的浮点小数。
每个时间戳都以自从1970年1月1日午夜(历元)经过了多长时间来表示。
Python 的 time 模块下有很多函数可以转换常见日期格式。如函数time.time()用于获取当前时间戳, 如下实例:
"""
'''
Calendar模块有很广泛的方法用来处理年历和月历,例如打印某月的月历:
'''
import calendar
cal = calendar.month(2017,6)
print("以下输出2017年6月日历:")
print(cal)
|
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()
return s
#*******************************************************
overall_rating = 0
negated = 0
veried = 0
length = 0
three_letter_words = ['top', 'add', 'who', 'hit', 'all', 'tad', 'why', 'fan', 'art', 'out', 'new', 'old', 'let', 'put', 'mad', 'odd',"bad", "not"] # To keep
notList = ["not", "didnt", "couldnt", "dont", "cant", "wouldnt", "wasnt"]
veryList = ["very", "really", "extremely", "too", "utter", "especially", "so"]
review = sys.argv[1] # Take input string review
#review = removePunctuation(review)
#print("After punctuation removed", review)
#print(review)
f = open('TestDictionary6.txt', "r") # The dictionary text file
entries = [entry for entry in f.read().split('\n')]
entries.pop() # Gets rid of '' entry
#print(entries)
#dictionary = {entry[0:len(entry)-3]: int(entry[len(entry)-2:]) for entry in entries}
dictionary = {entry[0:len(entry)-4]: int(entry[len(entry)-3:]) for entry in entries} # Form {"word": int}
#print(dictionary)
review_words = [elt for elt in review.split(' ')]
#print("review words: ", review_words)
length = len(review_words)
#=================================================================================
# Removes unneeded words (though not ones like "book", "this"-- the special cases)
#
#Where words in the review are actually checked
for elt in review_words:
# Special cases
if(elt in notList):
length -= 1
negated = 1
#overall_rating += 50
continue
if(elt in veryList):
length -= 1
veried += 1
#overall_rating += 50
continue
# Check for excluded
if(elt not in dictionary):
length -= 1
######print("---There is no ", elt)
continue
addition = dictionary[elt]
if(veried != 0 and negated == 1):
if(dictionary[elt] > 50): addition = 100-(addition*0.8)
else: addition = 100-addition*1.5
veried = 0
negated = 0
elif(veried != 0):
if(dictionary[elt] >= 50): addition = addition*(1.5**veried)
else: addition = addition*(0.5**veried)
veried = 0
elif(negated == 1):
addition = 100-addition
negated = 0
#######print(elt, addition)
# Adjust to fit bounds (primative)
if(addition < 0): addition = 0
if(addition > 100): addition = 100
overall_rating += addition
#######print("Overall rating is: ", overall_rating, "length is ", length)
if(length == 0):
print("No usable words, sorry.")
overall_rating = 50
else:
overall_rating = overall_rating/(length)
#print(review_words)
print("******************")
#print(overall_rating)
print("{0:3.1f}".format(overall_rating))
if(overall_rating > 80): print("That's extremely positive :D")
elif(overall_rating > 55): print("That's positive. :)")
elif(overall_rating < 20): print("That's extremely negative :'(")
elif(overall_rating < 45): print("That's negative. :(")
else: print("Neutral :I")
#
print("******************")
|
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 tree
# Also calc left diam, right diam
# Max diam of node is left diam, right diam or left height + right height + 1
def calc_max_diam(tree, diameter):
# Base Case is no children
if (len(tree.children) == 0):
return 1
left_height = calc_height(tree.children[0])
right_height = calc_height(tree.children[1])
left_diam = calc_max_diam(tree.children[0], diameter)
right_diam = calc_max_diam(tree.children[1], diameter)
return max(left_height + right_height + 1, max(left_diam, right_diam))
myTree = Tree(10)
myTree.add_child(100)
myTree.add_child(80)
print(calc_max_diam(myTree, 0))
|
#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_list):
results = []
while (linked_list != None):
results.append(linked_list.value)
linked_list = linked_list.next
return results
print(list_to_array(test))
|
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, midpoint_index + 1, end)
print(left, right)
# Merge
temp_arr = []
while (len(left) > 0 and len(right) > 0):
left_item = left[0]
right_item = right[0]
if (left_item < right_item):
temp_arr.append(left.pop(0))
else:
temp_arr.append(right.pop(0))
if (len(left) > 0):
temp_arr = temp_arr + left
if (len(right) > 0):
temp_arr = temp_arr + right
return temp_arr
print(merge_sort([1,3,-1, 10, 10, 10, 10, 8, 7, 6, 5, 4, 3, 20]))
print(merge_sort([1,3,2, 7, -1, 100, 2, 5, 13, 99, -100]))
|
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 path_adder(tree, target):
paths = []
def find_sum_paths(tree, current_sum, path, target):
current_sum = current_sum + tree.node.value
path.append(tree.node.value)
if (current_sum == target):
paths.append(path)
elif (current_sum > target):
return
else:
for child in tree.children:
find_sum_paths(child, current_sum, path[:], target)
find_sum_paths(tree, 0, [], target)
return paths
print(path_adder(my_tree, 110))
|
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():
self.front=node
self.rear=node
self.rear.next=node
self.rear=node
def dequeue(self):
if self.is_empty():
raise Exception("empty equeue")
if self.front==self.rear:
temp=self.front
self.front=None
self.rear=None
return temp.value
else:
temp=self.front
self.front=self.front.next
temp.next=None
return temp.value
def peek(self):
if self.is_empty():
raise Exception("empty equeue")
return self.front.value
def is_empty(self):
return not self.front
def __len__(self):
counter=0
while self.front:
counter +=1
self.dequeue()
return counter
class BinaryTree:
def __init__(self):
self.root = None
def pre_order(self, root):
# print(root.value)
arr = []
def walk(node):
arr.append(node.value)
if node.left != None:
walk(node.left)
if node.right != None:
walk(node.right)
walk(root)
return arr
def post_order(self, root):
try:
if root.left:
self.post_order(root.left)
if root.right:
self.post_order(root.right)
self.arr.append(root.value)
return self.arr
except:
raise Exception("something went wrong")
def in_order(self, root):
try:
if root.left:
self.in_order(root.left)
self.arr.append(root.value)
if root.right:
self.in_order(root.right)
return self.arr
except:
raise Exception("something went wrong")
def test(self):
self.arr = []
def tree_max(self):
x=self.in_order(self.root)
self.max=0
for i in x :
if i>self.max:
self.max=i
return self.max
def breadthFirst(self,root):
if not root:
raise Exception("Empty Tree")
Queue_breadth = Queue()
Queue_breadth.enqueue(root)
try:
while Queue_breadth.peek():
node_front = Queue_breadth.dequeue()
self.arr.append(node_front.value)
if node_front.left:
Queue_breadth.enqueue(node_front.left)
if node_front.right:
Queue_breadth.enqueue(node_front.right)
except:
return self.arr
class BinarySearch(BinaryTree):
def add(self, value):
if not self.root:
self.root = Node(value)
# print(self.root.value)
return
current = self.root
while current:
if value > current.value:
if current.right:
current = current.right
else:
current.right = Node(value)
return
else:
if current.left:
current = current.left
else:
current.left = Node(value)
return
def Contains(self, value):
if not self.root:
raise Exception("empty is tree")
elif value == self.root.value:
return True
else:
current = self.root
while current:
if current.value < value:
if current.right:
current = current.right
if value == current.value:
return True
else:
return False
else:
if current.left:
current = current.left
if value == current.value:
return True
else:
return False
def find_max_in_level(root):
max=[]
queue=Queue()
level=0
queue.enqueue(root)
def walk(queue,level):
nonlocal max
if len(max)==(level):
max.append(0)
front=queue.dequeue()
if max[level]<=front.value:
max[level]=front.value
level+=1
if front.left:
queue.enqueue(front.left)
walk(queue,level)
if front.right:
queue.enqueue(front.right)
walk(queue,level)
walk(queue,level)
return max
def isSameTree( p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
flag=False
def walk(root1,root2):
nonlocal flag
if not (root1 and root2):
return
if root1.value == root2.value:
flag = True
else:
flag=False
return
walk(root1.left,root2.left)
walk(root1.right,root2.right)
walk(p,q)
return flag
x=Node(50)
x.left=Node(68)
x.right=Node(78)
x.left.left=Node(8)
x.right.right=Node(9)
y=Node(50)
y.left=Node(68)
y.right=Node(78)
y.left.left=Node(8)
y.right.right=Node(9)
print(isSameTree(x,y))
|
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_node
def printList(self):
temp = self.head
strain=''
while temp != None:
strain+=f"{temp.data} -> "
temp = temp.next
strain+="None"
return strain
def zip_list(self, p, q):
list1 = p.head
list2 = q.head
# swap their postions until one finishes off
while list1 != None and list2 != None:
list1_next = list1.next
list2_next = list2.next
list2.next = list1_next
list1.next = list2
list1 = list1_next
list2 = list2_next
q.head = list2
if __name__=="__main__":
linklist1=LinkedList()
linklist1.push(1)
linklist1.push(2)
linklist1.push(3)
linklist2=LinkedList()
linklist2.push(4)
linklist2.push(5)
linklist1.zip_list(linklist1,linklist2)
print(linklist1.printList())
|
'''
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 DoubleLinkedList
class Queue():
'''
All the methods here are technically "inherited" or "implemented" from
the original DoubleLinkedList.py class. Due to the way I implemented it,
I don't even need to do any type of exception handling here.
'''
def __init__(self):
self.linked_list = DoubleLinkedList.DoubleLL()
def enqueue(self, x):
# How this works is defined in DoubleLinkedList.py
return self.linked_list.queue_enqueue(x)
def dequeue(self):
# How this works is defined in DoubleLinkedList.py
return self.linked_list.pop()
def is_empty(self):
# How this works is defined in DoubleLinkedList.py
return self.linked_list.is_empty()
# args: q, Queue
def print_queue(q):
'''
The print function, which will take a single argument (the queue)
and print out its contents. It does this by dequeueing every item in the
queue until it is empty, appending each item to a list as it goes. Once
it reaches the end, it will print out the items and then reconstruct the
queue by enqueueing them once more.
'''
if q.is_empty():
print("Empty")
return False
else:
itemList = []
while not q.is_empty():
node = q.dequeue()
itemList.append(str(node))
print(' '.join(itemList))
for item in itemList:
q.enqueue(int(item))
return True
# this function runs the program according to the problem specification
def driver():
q = Queue()
with open(sys.argv[1]) as f:
n = int(f.readline().strip())
for _ in range(n):
in_data = f.readline().strip().split()
action, value_option = in_data[0], in_data[1:]
if action == "enqueue":
value = int(value_option[0])
q.enqueue(value)
elif action == "dequeue":
try:
print(str(q.dequeue()))
except DoubleLinkedList.DoubleLL.Underflow:
print("QueueError")
elif action == "print":
print_queue(q)
if __name__ == "__main__":
driver()
|
'''
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-heap and min-heap by using lists,
the built-in python heapq module can handle these in order
to keep the heap properties (albeit in a slightly weird
way for a max-heap). We also have the size of each of the
heaps here.
'''
self.minheap = []
self.maxheap = []
self.maxsize = 0
self.minsize = 0
def minheap_add(self, x):
'''
Adding to a min-heap is very straightforward, just need to
use the built-in push method for the heapq module on our
list. It maintains the min-heap property by default. We
also increment the size.
'''
self.minsize += 1
heapq.heappush(self.minheap, (x))
def minheap_pop(self):
'''
Popping from the min-heap is equally as easy using the
built-in method, here we decrement the size by one.
'''
self.minsize -= 1
return heapq.heappop(self.minheap)
def maxheap_add(self, x):
'''
Creating a max-heap via the built-in heapq methods is slightly
weirder than making a min-heap. Because there isn't a built-in
method to maintain a max-heap property, we can keep track of it
by simply inverting the numbers to negative -- whenever we need
to pop them back out we convert them back and our max-heap
property is satisfied. We also increment the size here.
'''
self.maxsize += 1
heapq.heappush(self.maxheap, (x * -1))
def maxheap_pop(self):
'''
Same as the min-heap pop, except we had to invert the number back
to positive. Could have also used abs() here but I thought the
multiplication was more explicit.
'''
self.maxsize -= 1
popped = heapq.heappop(self.maxheap)
return (popped * -1)
def compare_roots_add(self, x):
'''
This will add a number to the min-heap or the max-heap depending
on if the number to be added is smaller than the root of the
max-heap. If it is, it goes into the min-heap instead. We can
use list indexing notation to access the root of each heap,
they are located at index 0. This method uses the previous
methods to add to the heaps, and is the one actually used when
adding numbers after reading the file input.
'''
if x < (self.maxheap[0] * -1):
self.maxheap_add(x)
else:
self.minheap_add(x)
def balance_heaps(self):
'''
This method is called every time we add a number to the heaps. We
need to check if they are balanced, ie; they are not bigger than
each other by a value more than one. We can check if one is bigger
than the other by more than one, if so, we pop the root of the
bigger one and add it onto the smaller one. This ensures that our
heapsizes are always within one of each other.
'''
if (self.minsize - self.maxsize) > 1:
item = self.minheap_pop()
self.maxheap_add(item)
elif (self.maxsize - self.minsize) > 1:
item = self.maxheap_pop()
self.minheap_add(item)
else:
return
def calculate_median(self):
'''
The actual function to calculate the median, this makes 3 checks
to see which calculation we need. If the two heaps are the same size,
we take the sum of their roots and divide by 2 to acquire the median.
If they have differing sizes, we simply return the root of the larger
one. This will always give us our median assuming that the heaps are
balanced and properly formed, which they are due to the checks we made
previously; especially balancing the heaps which happens every time
this function is called.
'''
self.balance_heaps()
if self.minsize == self.maxsize:
median = ((self.maxheap[0] * -1) + self.minheap[0]) / 2
elif self.minsize > self.maxsize:
median = self.minheap[0]
elif self.maxsize > self.minsize:
median = self.maxheap[0] * -1
if (median % 2) == 0:
median = int(median)
return round(median, 1)
# this function runs the program according to the problem specification
def driver():
rmc = RollingMedianCalc()
with open(sys.argv[1]) as f:
# Get the number of lines
n = int(f.readline().strip())
# Reduce the number of lines by two, as the first two numbers entered
# are special
n -= 2
# Grabbing the first two "special" numbers
first = int(f.readline().strip())
second = int(f.readline().strip())
# First number in is always the median by itself as there is nothing
# else entered as of yet
print("Median:\t", first)
# The smallest of the two first numbers goes into the max-heap, the
# largest goes into the min-heap.
if first < second:
rmc.maxheap_add(first)
rmc.minheap_add(second)
else:
rmc.minheap_add(first)
rmc.maxheap_add(second)
# Grab the median of the first two numbers.
print("Median:\t", rmc.calculate_median())
# Begin doing the rest of the numbers in the file.
for _ in range(n):
value = int(f.readline().strip())
rmc.compare_roots_add(value)
print("Median:\t", rmc.calculate_median())
if __name__ == "__main__":
driver()
|
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, employeeid and employeename.
employeeid holds employee ids and employeename holds the employee
names. employeeid and employeename are converted into a list of
dicionaries using the employee ids and names.
The following shows this coded and executed
'''
list = []
employeeid = []
employeename = []
full_employee_list = []
# Import employee data into list################################################
file_name = 'employees.csv'
with open(file_name) as csv_file:
reader = csv.reader(csv_file)
for row in reader:
for data in row:
list.append(data)
# Separate main list into two lists#############################################
for data in list:
if len(data) < 2:
employeeid.append(data)
else:
employeename.append(data)
# Upload two separate lists into dicitonary#####################################
for i in range(len(employeename)):
full_employee_list.append({'ID': employeeid[i], 'Name': employeename[i]})
pprint(full_employee_list)
# Step 2. Load friends.csv ######################################################
'''
This friends.csv file is loaded into a dictionary, where the key represents an
employee (from the friends list). Each key, (employee) has a list of friends.
The dictionary 'people' is used to store this information.
The following code was used to execute creating the dictionary.
'''
people = {}
# Import friendship data into dictionary ########################################
file_name1 = 'friends.csv'
with open(file_name1) as csv_file:
reader = csv.reader(csv_file)
for row in reader:
for p in row:
if p not in people:
people[p] = { 'Friends': []}
people[row[0]]['Friends'].append(row[1])
people[row[1]]['Friends'].append(row[0])
pprint(people)
# Step 3. Answer Questions #####################################################
# Question 1- How many employees are there?#####################################
def cnt():
'''
(None) -> int
Counts the number of ids in full_employee_list
to return the number of employees in the list
>>> print(cnt())
10
'''
counter = 0
for ids in full_employee_list:
counter += 1
return counter
# Qustion 2- What is the average friends per person, most, and few?##############
# 2.1 Average friends############################################################
def avg():
'''
(None)-> int
Loops through the length of friend lists for each
person and adds up the length of all lists. The sum
of length of all lists is divided by the return of the
cnt() function, it returns 10.
The function returns the average number of friends
each person has.
>>> print(avg())
2.4
'''
how_many_friends = 0
friends_total = 0
friends_avg = 0
for person in people:
how_many_friends = len(people[person]['Friends'])
friends_total += how_many_friends
friends_avg = friends_total/cnt()
return friends_avg
# 2.2 Max Friends ################################################################
def max_f():
'''
(None) -> int
Loops through the length of each person's friends list and returns
the maximum number, or the friends with the longest list.
>>> print(max_f())
3
'''
max_num = 0
for person in people:
how_many_friends = len(people[person]['Friends'])
if how_many_friends > max_num:
max_num = how_many_friends
return max_num
# 2.3 Min Friends ###############################################################
def min_f():
'''
(None) -> int
Loops through the length of each person's list and returns the number of the
least friends, or the shortest list.
>>> print(min_f())
1
'''
i = 1
for person in people:
for i in people:
min_num = len(people[person]['Friends'])
current_num = len(people[i]['Friends'])
if current_num < min_num:
min_num = current_num
return min_num
#### OUTPUT FOR PROBLEMs 1 & 2 ANSWERS #############################################
print('There are',cnt(),'employees.')
print('The average number of friends is',avg(),)
# Max Friends Answer
for person in people:
if max_f()== len(people[person]['Friends']):
print(person,':',max_f(),'friends')
# Min Friends Answer
for person in people:
if min_f() ==len(people[person]['Friends']):
print(person,':',min_f(),'friend')
### Question 3- Friends of Friends #################################################
'''
For this part, 'Friends of Friends' list was added to people dictionary.
Below is the following code the shows the creation of the 'Friends of Friends' key
and the data importation through the use of the fof() function.
'''
## Create FOF list #################################################################
for person in people:
if 'Friends of Friends' not in people[person]:
people[person]['Friends of Friends'] = []
### Add data to fof through fof function ###########################################
def fof():
'''
(None)-> dictionary
Loops through people dicionary to find everybody's friends of friends. It
excludes people that are friends, and there's no duplicates
>>> print(fof())
{ '0': {'Friends': ['1','2'], 'Friends of Friends':['3']},
'1': {'Friends': ['0','2','3'], 'Friends of Friends: ['4']},
'''
for person in people:
for friend in people[person]['Friends']:
for fof in people[friend]['Friends']:
if fof != person:
if fof not in people[person]['Friends']:
if fof not in people[person]['Friends of Friends']:
people[person]['Friends of Friends'].append(fof)
else:
pass
return people
# Question 3 Answer #################################################################
pprint(fof())
# Question 4- Mutual Friends ########################################################
'''
The following code shows function m_f() that returns the count of mutual friends a
given pair of employees have.
'''
# Mutual Friends Function ##########################################################
def m_f():
'''
(None) -> tuple
Loops through friends lists and returns the count of mutual frirends.
Prints the two employee ids and their count of mutual friends.
>>> m_f()
('0','1','1')
('0','2','1')
'''
mutual_count = 0
for person1 in people:
for person2 in people:
for mutual_f in people[person1]['Friends']:
if person1 < person2 and mutual_f in people[person2]['Friends']:
mutual_count += 1
if mutual_count > 0:
print((person1,person2,mutual_count))
mutual_count = 0
# Question 4 Answer #################################################################
m_f()
# Question 5- If NOT friends, print mutual friends ##################################
'''
The following code shows the function nm_f() that loops throughs the employees friends
list and returns the mutual friends. However, the employees are NOT friends.
'''
## Non-Mutual Friends Function #######################################################
def nm_f():
'''
(None)-> tuple
Loops through employees who aren't friends, and loops through their lists to find
mutual friends.
Prints out the two employees who aren't friends, and their mutual friend count
>>> nm_f()
('0','3',2)
('0','4',1)
'''
mutual_count1 = 0
for person1 in people:
for person2 in people:
for mutual in people[person1]['Friends']:
if person1 < person2 and mutual in people[person2]['Friends'] and person1 not in people[person2]['Friends']:
mutual_count1 += 1
if mutual_count1 > 0:
print((person1,person2,mutual_count1))
mutual_count1 = 0
# Question 5 Answer ##################################################################
nm_f()
## Part 2 ############################################################################
## Question 6 ########################################################################
'''
The following code shows the creation of two dictionaries based on imported data from
the interests.csv file. To make the dictionaries the data was loaded into one main list,
called lst.
Then the data was parsed into two lists, intersts_id and interests. interests_id contains
the employee ids and the intersts list contains the actual interests.
'''
# Import interest data ###############################################################
interests_id = []
interests = []
file_name = 'interests.txt'
with open(file_name) as csv_file:
reader = csv.reader(csv_file)
for row in reader:
interests_id.append(row[0][0])
interests.append(row[0][2:])
lst = []
for i in range(len(interests)):
lst.append([interests_id[i]] + [interests[i]])
# Question 6.1 Print Interest Dictionary ############################################
'''
From lst, create the dictionary int_dict where the employeeid is the key
and the value is a list of interests
'''
int_d = {}
def int_dict():
'''
(None) -> dictionary
Loops through lst to find ids aren't in the list and append them to the new
dictionary, int_d
>>> int_dict()
{'0': {'interests':['Hadoop', 'Big Data', 'HBas', 'Java', 'Spark', 'Storm', 'Cassandra']}
'1':{ 'interests':['NoSQL','MongoDB','Cassandra','HBase','Postgres']}
'''
for row in lst:
for p in row:
if p not in int_d and len(p) == 1 and p != 'R':
int_d[p] = {'interests': []}
int_d[row[0]]['interests'].append(row[1])
pprint(int_d)
## OUTPUT For First Dictionary #######################################################
int_dict()
# Question 6.2 Print Reversed Interest Dictionary ####################################
'''
A second master list of data was created to flip the order in which data entered the
list. Here, interests and the employee ids are appended in reveresed order compared
to lst, so that when the dictionary is created, the interests are the key and the
employee ids are in the list.
'''
# Create a new list where interests and employee ids are flipped #####################
lst2 = []
for i in range(len(interests)):
lst2.append([interests[i]] + [interests_id[i]])
# From lst two, create int_d2 ########################################################
int_d2 = {}
for row in lst2:
for p in row:
if p not in int_d2 and len(p) != 1 or p == 'R':
int_d2[p] = {'interests_id': []}
int_d2[row[0]]['interests_id'].append(row[1])
pprint(int_d2)
## Question 7: recommending friends based on shared interests (excluding current friendships).
# Add recommendations list to int_d #########################################################
for person in int_d:
if 'recommendations' not in int_d[person]:
int_d[person]['recommendations']= []
### Add interests to dictionary ##############################################################
for person1 in people:
for person2 in people:
for mutual in people[person1]['Friends']:
for person1 in int_d:
for shared in int_d[person1]['interests']:
if shared in int_d[person2]['interests']:
if person1 < person2 and person1 != person2:
if person1 not in people[person2]['Friends']:
if person1 not in int_d[person2]['recommendations']:
int_d[person2]['recommendations'].append(person1)
if person2 not in int_d[person1]['recommendations']:
int_d[person1]['recommendations'].append(person2)
break
pprint(int_d)
## Question 8: Listing people who are FOF and have shared interests.#########################
'''
shared1 is a list that will be added to the dictionary that shows the ids with
shared data science topics
'''
shared1 = []
for person1 in people:
for fof in people[person1]['Friends of Friends']:
for shared in int_d[person1]['interests']:
if shared in int_d[fof]['interests']:
shared1.append(shared)
if person1 < fof and person1 != fof:
if person1 in people[fof]['Friends of Friends']:
if len(shared1) > 1:
print((person1, fof, shared1))
################### SAMPLE OUTPUT FOR 6.2, 7, and 8 ##########################################
'''
6.2
{'Big Data': {interests_id ['0','8','9']},
'C++': {'interests_id':[5]},
'Cassandra': {'interests_id':['0','1']}
7
{'0':'interests: ['Hadoop',
'Big Data',
'HBas',
'Java'
'Spark'
'Storm'
'Cassandra']
'recommendations: ['5','8','9']},
{'1': {'interests: ['NoSQL', 'MongoDB', 'Cassandra', 'HBase', 'Postgres'],
'recommendations': []}
'2': {'interests': ['Python',
'skikit-learn',
'numpy'
'statsmodels',
'pandas'],
'recommendations': ['5']}
8
('3', '5', ['R','Python'])
('4','7',['R','Python', 'machine learning'])
'''
|
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 - https://www.asciiart.eu/animals/cats
CAT_LEFT = """
/\ /
(' ) (
( \ )
|(__)/
"""
CAT_RIGHT = """
\ /\\
) ( ')
( / )
\(__)|
"""
class Pet:
'''A Tamagotchi pet!
Attributes
----------
name : string
The pet's name
sound : string
The pet's sound
'''
max_boredom = 6
max_hunger = 10
leaves_hungry = 16
leaves_bored = 12
ascii_art_left = ""
ascii_art_right = ""
def __init__(self, name, sound, age=0):
self.name = name
self.hunger = randrange(self.max_hunger)
self.boredom = randrange(self.max_boredom)
self.sound = sound
self.age = age
def mood(self):
'''Get the mood of a pet. A pet can be happy, hungry or bored,
depending on wether it was fed or has played enough.
Parameters
----------
none
Returns
-------
str
The mood of the pet
'''
if self.hunger <= self.max_hunger and self.boredom <= self.max_boredom:
return "happy"
elif self.hunger > self.max_hunger:
return "hungry"
else:
return "bored"
def status(self):
'''Get the status of a pet to know it's name, how it feels and what it wants.
Parameters
----------
none
Returns
-------
str
The name, mood and wants of the pet.
'''
state = "I'm " + self.name + '. '
state += 'I feel ' + self.mood() + '. '
if self.mood() == 'hungry':
state += 'Please feed me. '
if self.mood() == 'bored':
state += 'You can play with me. '
return state + f"I'm {self.age} years old now."
def do_command(self, resp):
'''Calls the appropriate methods of a pet based on command "resp" given by player.
Parameters
----------
resp : string
The command to be issued to the pet.
Returns
-------
none
'''
if resp == "speak":
print(self.speak())
elif resp == "play":
self.play()
elif resp == "feed":
self.feed()
elif resp == "wait":
print("Nothing to do...")
elif resp == "adopt":
self.adopt()
elif resp == "list":
self.list_name()
elif resp == "choose":
self.choose()
else:
print("Please provide a valid command.")
def has_left(self):
'''Returns True if a pet has left the game due to hunger or boredom, otherwise False.
Parameters
----------
none
Returns
-------
bool
If a pet has left
'''
return self.hunger > self.leaves_hungry or self.boredom > self.leaves_bored
def clock_tick(self):
"""Add 2 to the pet's hunger and boredom
Parameters
----------
none
Returns
-------
int
max_hunger and max_boredom
"""
self.hunger += 2
self.boredom += 2
self.age += 2
return self.hunger, self.boredom, self.age
def speak(self):
"""Print "I say: " and then the pet's unique sound.
Parameters
----------
none
Returns
-------
none
"""
return f"I say: {self.sound}"
def feed(self):
"""The pet's hunger is decreased by 5.
Parameters
----------
none
Returns
-------
none
"""
self.hunger -= 5
if self.hunger < 0:
self.hunger = 0
return
def play(self, limit_guess = 3):
"""The user tries to guess which way the pet will look up
to 3 times. If guess correctly, the play is done and
pet's boredom is decreased by 5.
Parameters
----------
none
Returns
-------
none
"""
num_guess = 0
pet_look_direction = ['left', 'right']
while num_guess < limit_guess:
my_guess = input('Does the pet look left or right?\n')
if my_guess in pet_look_direction:
rand_index = randrange(2)
if my_guess == pet_look_direction[rand_index]:
print('Correct!')
self.boredom -= 5
if self.boredom < 0:
self.boredom = 0
break
else:
print(f"I look to the {pet_look_direction[rand_index]}. Try again.")
if rand_index == 0:
print(self.ascii_art_left)
else:
print(self.ascii_art_right)
num_guess += 1
else:
print("Please provide a valid command.\n")
def adopt(self):
"""The player adds an additional pet to game.
Parameters
----------
none
Returns
-------
none
"""
main()
def list_name(self):
"""The names of all pets are listed.
Parameters
----------
name_list: list
the list of all pets
Returns
-------
none
"""
for name in pet_dict.keys():
print(name)
def choose(self):
"""List names. Ask player to provide a valid name.
Go back to standaed menu.
Parameters
----------
none
Returns
-------
none
"""
self.list_name()
while True:
name = input("Please provide a valid name.\n")
if name in pet_dict.keys():
break
if pet_dict[name]['type'].lower() == 'cat':
p = Cat(name, pet_dict[name]['sound'], pet_dict[name]['meow_count'], pet_dict[name]['age'])
if pet_dict[name]['type'].lower() == 'dog':
p = Dog(name, pet_dict[name]['sound'], pet_dict[name]['age'])
if pet_dict[name]['type'].lower() == 'poddle':
p = Poodle(name, pet_dict[name]['sound'], pet_dict[name]['age'])
while True:
while not p.has_left():
print()
print(p.status())
if p.age > 18:
print(f"{p.name} has left.\nProgram terminates.")
break
command = input("What should I do?\n")
p.do_command(command)
p.clock_tick()
update_pet_dict_age(p.age, p.name, pet_dict)
print("Your pet has left.")
pet_dict.pop(p.name)
if not list(pet_dict.keys()):
option = input("Do you want play it again or quit?\n")
if option == "again":
main()
elif option == "quit":
print("Byebye~")
#######################################################################
#---------- Part 2: Inheritance - subclasses
#######################################################################
class Dog(Pet):
"""Subclass of Pet
Attributes
----------
name: str
The dog's name
sound: str
The dog's sound
"""
ascii_art_left = DOG_LEFT
ascii_art_right = DOG_RIGHT
def clock_tick(self):
self.hunger += 2
self.boredom += 2
self.age += 2
return self.hunger, self.boredom, self.age
def play(self, limit_guess = 3):
"""The user tries to guess which way the pet will look up
to 3 times. If guess correctly, the play is done and
pet's boredom is decreased by 5.
Parameters
----------
none
Returns
-------
none
"""
super().play()
def speak(self):
"""Print "I say: " and Dog sound
Parameters
----------
none
Returns
-------
none
"""
return f"I say: {self.sound} arrrf!"
class Cat(Pet):
"""Subclass of Pet
Attributes
----------
name: str
The name of cat
sound: str
The sound of cat
meow_count: int
The number of sound
"""
ascii_art_left = CAT_LEFT
ascii_art_right = CAT_RIGHT
def __init__(self, name, sound, meow_count, age = 0):
super().__init__(name, sound)
self.meow_count = meow_count
self.age = age
def clock_tick(self):
self.hunger += 2
self.boredom += 2
self.age += 3
return self.hunger, self.boredom, self.age
def speak(self):
"""Print "I say: " and repeated count of sound
Parameters
----------
none
Returns
-------
none
"""
return f"I say: {self.sound * int(self.meow_count)}"
def play(self):
"""Cats have 5 attempts while playing. Guess which way
the cat will look. If guess correctly, the play is done and
pet's boredom is decreased by 5.
Parameters
----------
limit_guess: int
default limit guess 5 times
Returns
-------
none
"""
super().play(5)
class Poodle(Dog):
"""Subclass of Dog
Attibutes
---------
name: str
The name of Poodle
sound: str
The sound of Poodle
"""
def clock_tick(self):
self.hunger += 2
self.boredom += 2
self.age += 2.5
return self.hunger, self.boredom, self.age
def dance(self):
"""Return "Dancing in circles like poodles do!"
Parameters
----------
none
Returns
-------
str: sentence saying "Dancing in circles like poodles do!"
"""
dance = "Dancing in circles like poodles do!"
return dance
def speak(self):
"""First print the dance method and then the speak method from the superclass.
Parameters
----------
none
Returns
-------
none
"""
return self.dance() + super().speak()
def get_name():
'''Asks the player which name a pet should have.
Parameters
----------
none
Returns
-------
none
'''
return input("How do you want to name your pet?\n")
def get_sound():
'''Asks the player what sound a pet should make
Parameters
----------
none
Returns
-------
none
'''
return input("What does your pet say?\n")
def get_meow_count():
'''Asks the player how often a cat should make a sound.
Parameters
----------
none
Returns
-------
none
'''
while True:
resp = input("How often does your Cat make a sound?\n")
if resp.isnumeric():
return int(resp)
def check_name_is_unique(name, pet_dict):
"""Check whether names in the list is unique
Parameters
----------
name: str
new name
name_list: dict
the dict of all pet
Returns
-------
none
"""
while True:
name_list = []
for key in pet_dict:
name_list.append(key)
if name not in name_list:
break
else:
print("Please provide a valid name.\n")
name = get_name()
def build_pet_dict(resp, name, sound, age, meow_count=0):
if resp == 'cat':
pet_dict[name] = {"type":resp, "sound":sound,
"age": age, "meow_count": meow_count}
else:
pet_dict[name] = {"type":resp, "sound":sound,
"age": age}
def update_pet_dict_age(age, name, pet_dict):
pet_dict[name]['age'] = age
pet_dict = {}
def main():
"""Play loop
Parameters
----------
none
Returns
-------
none
"""
while True:
p = None
while p == None:
resp_pet_type = input("What kind of pet would you like to adopt?\n")
if resp_pet_type.lower() == 'cat':
name = get_name()
check_name_is_unique(name, pet_dict.keys())
sound = get_sound()
meow_count = get_meow_count()
p = Cat(name, sound, meow_count)
build_pet_dict(resp_pet_type, name, sound, p.age, meow_count)
elif resp_pet_type.lower() == 'dog':
name = get_name()
check_name_is_unique(name, pet_dict.keys())
sound = get_sound()
p = Dog(name, sound)
build_pet_dict(resp_pet_type, name, sound, p.age)
elif resp_pet_type.lower() == 'poodle':
name = get_name()
check_name_is_unique(name, pet_dict.keys())
sound = get_sound()
p = Poodle(name, sound)
build_pet_dict(resp_pet_type, name, sound, p.age)
else:
print("We only have Cats, Dogs and Poodles.")
while not p.has_left():
print()
print(p.status())
if p.age > 18:
print(f"{p.name} has left.\nProgram terminates.")
break
command = input("What should I do?\n")
p.do_command(command)
p.clock_tick()
update_pet_dict_age(p.age, p.name, pet_dict)
print("Your pet has left.")
pet_dict.pop(p.name)
if not list(pet_dict.keys()):
option = input("Do you want play it again or quit?\n")
if option == "again":
main()
elif option == "quit":
print("Byebye~")
break
break
if __name__ == "__main__":
main() |
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] == "A":
return 1
else:
return 10 |
#!/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 transaction")
def __str__(self):
return "<Transaction {} from {} to {} >".format(self.amnt, self.u_from, self.u_to)
def __repr__(self):
return "<Transaction {} - {} to {}>".format(self.amnt, self.u_from, self.u_to)
|
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 chars are equal
if len(aStr) == 1:
return aStr == char
#Base case: See if the character in the middle of aStr equals the
#test character
middle = len(aStr) / 2
guess = aStr[middle]
if char == guess:
#We found the character!
return True
#bisect aStr and enter recursion
elif char < guess:
return isIn(char, aStr[:middle])
else:
return isIn(char, aStr[middle+1:]) |
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 compKey in subaDict.keys():
if aDict[key] == subaDict[compKey]:
uniqueValue = False
if uniqueValue:
uniqueVals.append(key)
uniqueVals.sort()
return uniqueVals |
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 two inhabitants: Peggy and Zippy. Peggy tells you that 'of Zippy and I, exactly one is a knight'. Zippy tells you that only a knave would say that Peggy is a knave."
self.puzzleQuestions["3"] = "You meet two inhabitants: Sue and Zippy. Sue says that Zippy is a knave. Zippy says, `I and Sue are knights.'"
self.puzzleQuestions["4"] = "You meet two inhabitants: Sally and Zippy. Sally claims, `I and Zippy are not the same.' Zippy says, `Of I and Sally, exactly one is a knight.'"
self.puzzleQuestions["5"] = "You meet two inhabitants: Homer and Bozo. Homer tells you, `At least one of the following is true: that I am a knight or that Bozo is a knight.' Bozo claims, `Homer could say that I am a knave.'"
self.puzzleQuestions["6"] = "You meet two inhabitants: Marge and Zoey. Marge says, `Zoey and I are both knights or both knaves.' Zoey claims, `Marge and I are the same.'"
self.puzzleQuestions["7"] = "You meet two inhabitants: Mel and Ted. Mel tells you, `Either Ted is a knight or I am a knight.' Ted tells you that Mel is a knave."
self.puzzleQuestions["8"] = "You meet two inhabitants: Zed and Alice. Zed tells you, `I am a knight or Alice is a knave.' Alice tells you, `Of Zed and I, exactly one is a knight.'"
self.puzzleQuestions["9"] = "You meet two inhabitants: Ted and Zeke. Ted claims, `Zeke could say that I am a knave.' Zeke claims that it's not the case that Ted is a knave."
self.puzzleQuestions["10"] = "You meet two inhabitants: Ted and Zippy. Ted says, `Of I and Zippy, exactly one is a knight.' Zippy says that Ted is a knave."
self.puzzleQuestions["11"] = "You meet two inhabitants: Zed and Bart. Zed says, `Bart is a knight or I am a knight.' Bart tells you, `Zed could claim that I am a knave.'"
self.puzzleQuestions["12"] = "You meet two inhabitants: Bob and Betty. Bob claims that Betty is a knave. Betty tells you, `I am a knight or Bob is a knight.'"
self.puzzleQuestions["13"] = "You meet two inhabitants: Bart and Ted. Bart claims, `I and Ted are both knights or both knaves.' Ted tells you, `Bart would tell you that I am a knave.'"
self.puzzleQuestions["14"] = "You meet two inhabitants: Bart and Mel. Bart claims, `Both I am a knight and Mel is a knave.' Mel tells you, `I would tell you that Bart is a knight.'"
self.puzzleQuestions["15"] = "You meet two inhabitants: Betty and Peggy. Betty tells you that Peggy is a knave. Peggy tells you, `Betty and I are both knights.'"
self.puzzleQuestions["16"] = "You meet two inhabitants: Bob and Mel. Bob tells you, `At least one of the following is true: that I am a knight or that Mel is a knave.' Mel claims, `Only a knave would say that Bob is a knave.'"
self.puzzleQuestions["17"] = "You meet two inhabitants: Zed and Alice. Zed tells you, `Alice could say that I am a knight.' Alice claims, `It's not the case that Zed is a knave.'"
self.puzzleQuestions["18"] = "You meet two inhabitants: Alice and Ted. Alice tells you, `Either Ted is a knave or I am a knight.' Ted tells you, `Of I and Alice, exactly one is a knight.'"
self.puzzleQuestions["19"] = "You meet two inhabitants: Zeke and Dave. Zeke tells you, `Of I and Dave, exactly one is a knight.' Dave claims, `Zeke could claim that I am a knight.'"
self.puzzleQuestions["20"] = "You meet two inhabitants: Zed and Zoey. Zed says that it's false that Zoey is a knave. Zoey claims, `I and Zed are different.'"
self.puzzleQuestions["21"] = "You meet two inhabitants: Sue and Marge. Sue says that Marge is a knave. Marge claims, `Sue and I are not the same.'"
self.puzzleQuestions["22"] = "You meet two inhabitants: Bob and Ted. Bob says, `I am a knight or Ted is a knave.' Ted says that only a knave would say that Bob is a knave."
self.puzzleQuestions["23"] = "You meet two inhabitants: Zed and Peggy. Zed says that Peggy is a knave. Peggy tells you, `Either Zed is a knight or I am a knight.'"
self.puzzleQuestions["24"] = "You meet two inhabitants: Zed and Bob. Zed says, `Both I am a knight and Bob is a knave.' Bob says, `Zed could say that I am a knight.'"
self.puzzleQuestions["25"] = "You meet two inhabitants: Rex and Marge. Rex tells you, `I and Marge are knights.' Marge says, `I would tell you that Rex is a knight.'"
self.puzzleAnswers["1"] = "Zoey is a knight. Mel is a knave."
self.puzzleAnswers["2"] = "Peggy is a knave. Zippy is a knave."
self.puzzleAnswers["3"] = "Sue is a knight. Zippy is a knave."
self.puzzleAnswers["4"] = "Sally is a knave. Zippy is a knave"
self.puzzleAnswers["5"] = "Homer is a knave. Bozo is a knave"
self.puzzleAnswers["6"] = "Marge is a knight. Zoey is a knight"
self.puzzleAnswers["7"] = "Mel is a knight. Ted is a knave"
self.puzzleAnswers["8"] = "Zed is a knave. Alice is a knight"
self.puzzleAnswers["9"] = "Ted is a knave. Zeke is a knave"
self.puzzleAnswers["10"] = "Ted is a knight. Zippy is a knave"
self.puzzleAnswers["11"] = "Zed is a knave. Bart is a knave"
self.puzzleAnswers["12"] = "Bob is a knave. Betty is a knight"
self.puzzleAnswers["13"] = "Bart is a knave. Ted is a knight"
self.puzzleAnswers["14"] = "Bart is a knave. Mel is a knave"
self.puzzleAnswers["15"] = "Betty is a knight. Peggy is a knave"
self.puzzleAnswers["16"] = "Bob is a knight. Mel is a knight"
self.puzzleAnswers["17"] = "Zed is a knight. Alice is a knight"
self.puzzleAnswers["18"] = "Alice is a knave. Ted is a knight"
self.puzzleAnswers["19"] = "Zeke is a knight. Dave is a knave"
self.puzzleAnswers["20"] = "Zed is a knave. Zoey is a knave"
self.puzzleAnswers["21"] = "Sue is a knave. Marge is a knight"
self.puzzleAnswers["22"] = "Bob is a knight. Ted is a knight"
self.puzzleAnswers["23"] = "Zed is a knave. Peggy is a knight"
self.puzzleAnswers["24"] = "Zed is a knight. Bob is a knave"
self.puzzleAnswers["25"] = "Indeterminate"
#1
#Q:You meet two inhabitants: Zoey and Mel. Zoey tells you that Mel is a knave. Mel says, `Neither Zoey nor I are knaves.'
#A:zoey is knight, mel is a knave
#2Q:You meet two inhabitants: Peggy and Zippy. Peggy tells you that 'of Zippy and I, exactly one is a knight'. Zippy tells you that only a knave would say that Peggy is a knave.
#A: Peggy is
#3You meet two inhabitants: Sue and Zippy. Sue says that Zippy is a knave. Zippy says, `I and Sue are knights.'
#4 You meet two inhabitants: Sally and Zippy. Sally claims, `I and Zippy are not the same.' Zippy says, `Of I and Sally, exactly one is a knight.'
#5 You meet two inhabitants: Homer and Bozo. Homer tells you, `At least one of the following is true: that I am a knight or that Bozo is a knight.' Bozo claims, `Homer could say that I am a knave.'
#6 You meet two inhabitants: Marge and Zoey. Marge says, `Zoey and I are both knights or both knaves.' Zoey claims, `Marge and I are the same.'
#7 You meet two inhabitants: Mel and Ted. Mel tells you, `Either Ted is a knight or I am a knight.' Ted tells you that Mel is a knave.
#8You meet two inhabitants: Zed and Alice. Zed tells you, `I am a knight or Alice is a knave.' Alice tells you, `Of Zed and I, exactly one is a knight.'
#9 You meet two inhabitants: Ted and Zeke. Ted claims, `Zeke could say that I am a knave.' Zeke claims that it's not the case that Ted is a knave.
#10 You meet two inhabitants: Ted and Zippy. Ted says, `Of I and Zippy, exactly one is a knight.' Zippy says that Ted is a knave.
#11 You meet two inhabitants: Zed and Bart. Zed says, `Bart is a knight or I am a knight.' Bart tells you, `Zed could claim that I am a knave.'
#12 You meet two inhabitants: Bob and Betty. Bob claims that Betty is a knave. Betty tells you, `I am a knight or Bob is a knight.'
#13 You meet two inhabitants: Bart and Ted. Bart claims, `I and Ted are both knights or both knaves.' Ted tells you, `Bart would tell you that I am a knave.'
#14 You meet two inhabitants: Bart and Mel. Bart claims, `Both I am a knight and Mel is a knave.' Mel tells you, `I would tell you that Bart is a knight.'
#15 You meet two inhabitants: Betty and Peggy. Betty tells you that Peggy is a knave. Peggy tells you, `Betty and I are both knights.'
#16 You meet two inhabitants: Bob and Mel. Bob tells you, `At least one of the following is true: that I am a knight or that Mel is a knave.' Mel claims, `Only a knave would say that Bob is a knave.'
#17 You meet two inhabitants: Zed and Alice. Zed tells you, `Alice could say that I am a knight.' Alice claims, `It's not the case that Zed is a knave.'
#18 You meet two inhabitants: Alice and Ted. Alice tells you, `Either Ted is a knave or I am a knight.' Ted tells you, `Of I and Alice, exactly one is a knight.'
#19 You meet two inhabitants: Zeke and Dave. Zeke tells you, `Of I and Dave, exactly one is a knight.' Dave claims, `Zeke could claim that I am a knight.'
#20 You meet two inhabitants: Zed and Zoey. Zed says that it's false that Zoey is a knave. Zoey claims, `I and Zed are different.'
#21 You meet two inhabitants: Sue and Marge. Sue says that Marge is a knave. Marge claims, `Sue and I are not the same.'
#22 You meet two inhabitants: Bob and Ted. Bob says, `I am a knight or Ted is a knave.' Ted says that only a knave would say that Bob is a knave.
#23 You meet two inhabitants: Zed and Peggy. Zed says that Peggy is a knave. Peggy tells you, `Either Zed is a knight or I am a knight.'
#24 You meet two inhabitants: Zed and Bob. Zed says, `Both I am a knight and Bob is a knave.' Bob says, `Zed could say that I am a knight.'
#25 You meet two inhabitants: Rex and Marge. Rex tells you, `I and Marge are knights.' Marge says, `I would tell you that Rex is a knight.'
|
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 = "multiply"
function_options = ('multiply', 'add', 'power', 'exp', 'random', 'avg', 'fib', 'lcm', 'gcd', 'division_reminder')
def fib(nr):
return int(((1 + math.sqrt(5)) / 2) ** nr / math.sqrt(5) + 0.5)
def gcd(x, y):
"""This function implements the Euclidian algorithm
to find G.C.D. of two numbers"""
while(y):
x, y = y, x % y
return x
# define lcm function
def lcm(x, y):
"""This function takes two
integers and returns the L.C.M."""
lcm = (x*y)//gcd(x,y)
return lcm
def get_value(val, factor, function):
if function == "multiply":
return val * factor
elif function == "add":
return val + factor
elif function == "power":
return val ^ factor
elif function == "exp":
return factor ^ val
elif function == "random":
return random.randint(1, factor)
elif function == "avg":
return int((val + factor) / 2)
elif function == "fib":
return fib(val)
elif function == "lcm":
return lcm(val, factor)
elif function == "gcd":
return gcd(val, factor)
elif function == "division_reminder":
return val % factor
fig, ax = plt.subplots(figsize=(6.8, 6.8))
plt.subplots_adjust(left=0.28, right=0.93, bottom=0.25)
plt.axis([
center[0] - radius - 0.2,
center[0] + radius + 0.2,
center[1] - radius - 0.2,
center[1] + radius + 0.2
])
def draw(num_dots, factor, function, axes):
# add main circle
circle1 = plt.Circle(center, radius, color='blue', fill=False)
axes.add_artist(circle1)
# add dots on the circle
dots = []
for i in range(num_dots):
angle = 2 * np.pi * i * (1.0 / num_dots)
dot_coordinates = (np.cos(angle) * radius, np.sin(angle) * radius)
dot = plt.Circle(dot_coordinates, dot_size, color='red')
dots.append(dot_coordinates)
axes.add_artist(dot)
# add dots connections
for i in range(len(dots)):
d0 = dots[i]
value = get_value(i, factor, function)
d1 = dots[value % num_dots]
axes.plot([d0[0], d1[0]],[d0[1], d1[1]],'g')
draw(num_dots0, factor0, function0, ax)
################
# Set controls #
################
axcolor = 'lightgoldenrodyellow'
# Sliders and radio buttons to switch function
ax_numdots = plt.axes([0.175, 0.1, 0.65, 0.03], facecolor=axcolor)
ax_factor = plt.axes([0.175, 0.15, 0.65, 0.03], facecolor=axcolor)
slider_numdots = Slider(ax_numdots, 'NumDots', num_dots_min, num_dots_max, valinit=num_dots0, valfmt='%0.0f')
slider_factor = Slider(ax_factor, 'Factor', factor_min, factor_max, valinit=factor0, valfmt='%0.0f')
rax = plt.axes([0.025, 0.5, 0.15, 0.15], facecolor=axcolor)
radio = RadioButtons(rax, function_options, active=0)
def update(val):
ax.clear()
f = radio.value_selected
num_dots = slider_numdots.val
factor = slider_factor.val
draw(int(num_dots), int(factor), f, ax)
fig.canvas.draw()
slider_numdots.on_changed(update)
slider_factor.on_changed(update)
radio.on_clicked(update)
# +/- buttons
numdots_plus1_ax = plt.axes([0.880, 0.1, 0.03, 0.03])
button_numdots_plus1 = Button(numdots_plus1_ax, '+', color=axcolor, hovercolor='0.975')
def numdots_plus1(event):
new_val = slider_numdots.val + 1
if new_val > slider_numdots.valmax:
new_val = slider_numdots.valmax
slider_numdots.set_val(new_val)
button_numdots_plus1.on_clicked(numdots_plus1)
numdots_minus1_ax = plt.axes([0.025, 0.1, 0.03, 0.03])
button_numdots_minus1 = Button(numdots_minus1_ax, '-', color=axcolor, hovercolor='0.975')
def numdots_minus1(event):
new_val = slider_numdots.val - 1
if new_val < slider_numdots.valmin:
new_val = slider_numdots.valmin
slider_numdots.set_val(new_val)
button_numdots_minus1.on_clicked(numdots_minus1)
factor_plus1_ax = plt.axes([0.880, 0.15, 0.03, 0.03])
button_factor_plus1 = Button(factor_plus1_ax, '+', color=axcolor, hovercolor='0.975')
def factor_plus1(event):
new_val = slider_factor.val + 1
if new_val > slider_factor.valmax:
new_val = slider_factor.valmax
slider_factor.set_val(new_val)
button_factor_plus1.on_clicked(factor_plus1)
factor_minus1_ax = plt.axes([0.025, 0.15, 0.03, 0.03])
button_factor_minus1 = Button(factor_minus1_ax, '-', color=axcolor, hovercolor='0.975')
def factor_minus1(event):
new_val = slider_factor.val - 1
if new_val < slider_factor.valmin:
new_val = slider_factor.valmin
slider_factor.set_val(new_val)
button_factor_minus1.on_clicked(factor_minus1)
# reset button
resetax = plt.axes([0.725, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
def reset(event):
slider_numdots.reset()
slider_factor.reset()
button.on_clicked(reset)
# save picture button
save_ax = plt.axes([0.615, 0.025, 0.1, 0.04])
button_save = Button(save_ax, 'Save', color=axcolor, hovercolor='0.975')
def save(event):
fig.savefig('plot.png')
button_save.on_clicked(save)
plt.show()
|
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: ..lat
'''
print("podaj wiek: ", end="") #nie przechodzi do nowej lini
wiek=input()
print(type(wiek))
print("Twoj wiek: ",wiek," lat")
age1=20
print(type(age1))
surname="Kowalski"
firstLetter=surname[0]
print(firstLetter)
length=len(surname)
print(length)
lastLetter=surname[len(surname)-1]
print(lastLetter)
#konwersja
|
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 image of the castle
self.image = pg.image.load('media/castle.png')
# set the size of the castle
self.width = width
self.height = height
# resize the castle based on the width and height of the image
self.image = pg.transform.scale(self.image, (self.width, self.height))
# define a new rectangle around the image
self.rect = self.image.get_rect()
# set the x and y positions
self.x = x
self.y = y
self.model = model
|
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 = image
# define a rectangle around the image
self.rect = self.image.get_rect()
# initialize the x and y position of the item
self.x = x
self.y = y
def update(self):
pass
|
"""
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:
print("even")
else:
print("odd")
def part2():
"""
Generate a random number between 1 and 9 (including 1 and 9). Ask the user
to guess the number, then tell them whether they guessed too low, too high,
or exactly right.
(Hint: remember to use the user input lessons from the very first
exercise).
Keep the game going until the user types "exit".
[ try checking the random module in python on google. Concepts: Infinite
loops, if, else, loops and user/input].
"""
rand = random.randint(1,9)
while(1):
inp = input("enter a guess (1-9 inclusive")
if inp == "exit":
break
elif int(inp) == rand:
print("you win (exactly right)")
break
elif int(inp) < rand:
print("guess too low")
else:
print("guess too high")
def part3(string):
"""
Ask the user for a string and print out whether this string is a palindrome
or not. (A palindrome is a string that reads the same forwards and
backwards.)
"""
for i in range(0,int(len(string)/2)):
if string[i] != string[len(string)-1-i]:
print("False")
return False
else:
print("True")
return True
def part4a(filename, username, password):
"""
Encrypt your username and password using base64 module
Store your encrypted username on the first line and your encrypted password
on the second line.
"""
f = open(filename, "w")
encodedUser = base64.b64encode(username.encode("utf-8"))
encodedUser1 = str(encodedUser, "utf-8")
encodedPass = base64.b64encode(password.encode("utf-8"))
encodedPass1 = str(encodedPass, "utf-8")
f.write(encodedUser1 + "\n" + encodedPass1)
part4a("beeeep.txt","username","password")
def part4b(filename, password=None):
"""
Create a function to read the file with your login information.
Print out the decrypted username and password.
If a password is specified, update the file with the new password.
"""
with open(filename, "r") as f1:
data = f1.readlines()
user = data[0]
pword = data[1]
decodedUser = base64.b64decode(user)
decodedUser1 = str(decodedUser, "utf-8")
decodedPass = base64.b64decode(pword)
decodedPass1 = str(decodedPass, "utf-8")
print(decodedUser1 + " " + decodedPass1)
if password != None:
encodedPass = base64.b64encode(password.encode("utf-8"))
encodedPass1 = str(encodedPass, "utf-8")
data[1] = encodedPass1 + '\n'
with open(filename, "w") as f1:
f1.writelines(data)
if __name__ == "__main__":
part1(3) # odd!
part1(4) # even!
part2()
part3("ratrace") # False
part3("racecar") # True
part4a("secret.txt", "naitian", "p4ssw0rd")
part4b("secret.txt")
part4b("secret.txt", password="p4ssw0rd!")
part4b("secret.txt")
|
#!/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 = re.compile('.{1,2}') # 匹配任意字符1-2次
return ' '.join(p.findall(t))
def split3(str):
t = str.upper()
return ' '.join([t[2 * i:2 * (i + 1)] for i in range(int(len(t) / 2))])
def parse_to_hex(str):
str_array = str.split()
ret_str = ''
for i in range(len(str_array)):
i_hex = binascii.b2a_hex(str_array[i].encode("utf8"))
i_str = binascii.a2b_hex(i_hex).decode("utf8")
ret_str = ret_str + i_str
return ret_str
if __name__ == '__main__':
# # 待分割字符串
# myStr = 'faa5fbb5fcc5fdd5010200000028000001900000000a002d00000000017d7840000003e800005fa55fb55fc55fd5'
#
# # 分割后:
# # FA A5 FB B5 FC C5 FD D5 01 02 00 00 00 28 00 00 01 90 00 00 00 0A 00 2D 00 00 00 00 01 7D 78 40 00 00 03 E8 00 00 5F A5 5F B5 5F C5 5F D5
#
# print('原始字符串:\n' + myStr + '\n')
# str1 = split1(myStr)
# print('split1符串:\n' + str1 + '\n')
# str2 = split2(myStr)
# print('split2字符串:\n' + str2 + '\n')
# str3 = split3(myStr)
# print('split3字符串:\n' + str3 + '\n')
# a1 = 'FA A5 FB B5 FC C5 FD D5 01 02 00 00 00 28 00 00 01 90 00 00 00 0A 00 2D 00 00 00 00 01 7D 78 40 00 00 03 E8 00 00 5F A5 5F B5 5F C5 5F D5'
# a1_s1 = a1.replace(' ', '')
# print('replaced符串:\n' + a1_s1 + '\n')
#
# a1_bytes = bytes.fromhex(a1_s1)
# print("a1_bytes:")
# print(a1_bytes)
#
# a1_math = binascii.b2a_hex(a1_s1.encode("utf-8"))
# print("a1_math:")
# print(a1_math)
#
# a1_hex = a1_bytes.hex()
# print("a1_hex:")
# print(a1_hex)
b1 = 'FA A5 FB B5 FC C5 FD D5 01 02 00 00 00 28 00 00 01 90 00 00 00 0A 00 2D 00 00 00 00 01 7D 78 40 00 00 03 E8 00 00 5F A5 5F B5 5F C5 5F D5'
b1_str = parse_to_hex(b1)
print("b1_str:")
print(b1_str)
|
#!/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 list_to_dicts(objs):
obj_arr = []
for o in objs:
dict = {}
dict.update(o.__dict__)
obj_arr.append(dict)
return obj_arr
# 对象(支持单个对象、list、set)转换成字典
def class_to_dict(obj):
is_list = obj.__class__ == [].__class__
is_set = obj.__class__ == set().__class__
if is_list or is_set:
obj_arr = []
for o in obj:
# 把Object对象转换成Dict对象
dict = {}
dict.update(o.__dict__)
obj_arr.append(dict)
return obj_arr
else:
dict = {}
dict.update(obj.__dict__)
return dict
if __name__ == '__main__':
stu = Student('zhangsan', 20)
print('-----object_to_dict:------')
print(object_to_dict(stu))
print('-----list_to_dicts------')
print(list_to_dicts([stu, stu]))
print('-----class_to_dict------')
print(class_to_dict(stu))
print('-----class_to_dicts------')
print(class_to_dict([stu, stu]))
stua = Student('zhangsan', 20)
stub = Student('lisi', 10)
stu_set = set()
stu_set.add(stua)
stu_set.add(stub)
print(class_to_dict(stu_set))
|
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 childrens
# number of adults
# time duration
# flight number
while True:
print()
no_of_childrens = int(input("Enter the number of childrens : "))
no_of_adults = int(input("Enter the number of adults : "))
time_duration = int(input("How long you want to go : "))
flight_number = input("What's your flight number : ")
result = calculator(no_of_childrens, no_of_adults, time_duration, flight_number)
print("*"*38)
if result !=None:
print("Your flight Fair is ",result)
else:
print("Sorry, Flight Number is not exsist")
print("*"*38)
continue_or_break = input("Do you want to continue or not (Y|N) :")
if continue_or_break == "N" or continue_or_break == "n":
break
|
#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.contents = True
else:
another_particle.contents = False
def __str__(self):
return "And"
class Or(object):
"""docstring for Or"""
def __init__(self, owning_particle):
super(Or, self).__init__()
self.owning_particle = owning_particle
def collide(self, another_particle):
if self.owning_particle.contents or another_particle.contents:
another_particle.contents = True
else:
another_particle.contents = False
def __str__(self):
return "Or"
class Not(object):
"""docstring for Not"""
def __init__(self, owning_particle):
super(Not, self).__init__()
self.owning_particle = owning_particle
def collide(self, another_particle):
if another_particle.contents:
another_particle.contents = False
else:
another_particle.contents = True
def __str__(self):
return "Not"
class Xor(object):
"""docstring for Xor"""
def __init__(self, owning_particle):
super(Xor, self).__init__()
self.owning_particle = owning_particle
def collide(self, another_particle):
if bool(self.owning_particle.contents) != bool(another_particle.contents):
another_particle.contents = True
else:
another_particle.contents = False
def __str__(self):
return "Xor"
class Nor(object):
"""docstring for Nor"""
def __init__(self, owning_particle):
super(Nor, self).__init__()
self.owning_particle = owning_particle
def collide(self, another_particle):
if not self.owning_particle.contents or another_particle.contents:
another_particle.contents = True
else:
another_particle.contents = False
def __str__(self):
return "Nor"
class Nand(object):
"""docstring for Nand"""
def __init__(self, owning_particle):
super(Nand, self).__init__()
self.owning_particle = owning_particle
def collide(self, another_particle):
if not self.owning_particle.contents and another_particle.contents:
another_particle.contents = True
else:
another_particle.contents = False
def __str__(self):
return "Nand"
|
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)
a = a+2
print("Porgandite koguarv on ",tulemus )
|
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
depth += 1
i_end = i_start + 2**depth - 1
i_mid = -(-(i_start + i_end)//2)
print(i_start, i_mid, i_end)
i += 1
print(left, right)
return '' if right == left else ('Right' if right > left else 'Left') |
# 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], chars[i] # in-place swap
return chars
def reverse_characters(chars, left, right):
while left < right:
chars[left], chars[right] = chars[right], chars[left]
left += 1
right -= 1
def reverse_words(chars):
# reverse all first
reverse_characters(chars, 0, len(chars)-1)
# reverse individual words
start = 0
end = 0
while end < len(chars):
if chars[end] == ' ':
reverse_characters(chars, start, end-1)
end += 1
start = end
else:
end += 1
return chars
print(reverse_words(['a','b',' ','c','a','r']))
|
# [ ] 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(fish_entry, price_entry))
|
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.
hsl_ordered = sorter.sorted(colors, "hSL")
print ("Colors sorted in the order of hSL:")
print([c.name for c in hsl_ordered])
# Sort by RGB order.
rgb_ordered = sorter.sorted(colors, "RGB")
print ("Colors sorted in the order of RGB:")
print([c.name for c in rgb_ordered])
# You can also change the precedence of components.
grb_ordered = sorter.sorted(colors, "GRB")
print ("Colors sorted in the order of GRB:")
print([c.name for c in grb_ordered])
# And you can directly sort hex color codes.
## Hex color codes that correspond to the color_names given above.
hex_codes = ['#ff0000', '#ff0', '#00ff00', '#0ff', '#f0f', '#0000FF']
hsl_ordered = sorter.sorted(hex_codes, "hSL")
print("Hex codes sorted in the order of hSL:")
print(hsl_ordered)
|
__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:
# connecting to database file
connect = sqlite3.connect(db_file)
c = connect.cursor()
c.execute("SELECT * FROM game_products WHERE title=?", (row_selection,))
rows = c.fetchall()
if len(rows) == 0:
print('There is no game title named %s' % row_selection)
else:
for row in rows:
print("\nID = ", row[0])
print("Game Title = ", row[1])
print("Retail Price = ", row[2])
print("Developer = ", row[3])
print("Inventory = ", row[4])
print("Platforms = ", row[5])
print("Release Date = ", row[6], "\n")
selection = input("\nWhat info would you like to update? (Enter one of the following: "
"\ntitle"
"\nretail price"
"\ndeveloper"
"\ninventory"
"\nplatform"
"\nrelease date"
"\n")
if selection == 'title':
updated_title = input("New game title: ")
c.execute("UPDATE game_products SET title=? WHERE title=?",(updated_title, row_selection,))
connect.commit()
elif selection == 'retail price':
updated_price = input("New retail price: ")
c.execute("UPDATE game_products SET retail_price=? WHERE title=?", (updated_price, row_selection,))
connect.commit()
elif selection == 'developer':
updated_developer = input("New developer: ")
c.execute("UPDATE game_products SET developer=? WHERE title=?", (updated_developer, row_selection,))
connect.commit()
elif selection == 'inventory':
updated_inventory = input("Updated inventory: ")
c.execute("UPDATE game_products SET inventory=? WHERE title=?", (updated_inventory, row_selection,))
connect.commit()
elif selection == 'platform':
updated_platform = input("Updated platforms: ")
c.execute("UPDATE game_products SET platforms=? WHERE title=?", (updated_platform, row_selection,))
connect.commit()
elif selection == 'release date':
updated_release = input("Updated release date: ")
c.execute("UPDATE game_products SET release_date=? WHERE title=?", (updated_release, row_selection,))
connect.commit()
else:
print("Error. Please enter a valid entry.")
exit = input("Do you want add more data? (Y/N)")
if exit == 'n':
connect.close()
break
except sqlite3.Error as e:
print("Error %s when updating data. Please try again" % e)
finally:
print("Database has been updated.") |
# try: (예외가 발생할 수 있는 가능성이 있는 코드)
# except: (예외가 발생했을 때 실행할 코드)
try:
print(float(input("> 숫자를 입력해주세요: ")) ** 2)
except:
print("숫자를 입력해주세요")
# pass 키워드를 사용하기도 한다.
# pass 키워드 사용시 프로그램은 종료되지 않되 계속 반복된다.
list_input_a = ["52", "273", "32", "스파이", "283"]
list_number = []
for item in list_input_a:
#숫자로 변환하여 리스트에 추가.
try:
float(item) # 예외가 발생할 경우 다음 코드는 진행이 안된다.
list_number.append(item) # 예외가 없었다면 리스트에 추가한다.
except:
pass
print("{} 내부에 있는 숫자는".format(list_input_a))
print("{}입니다.".format(list_number))
numbers = [52, 273, 32, 103, 90, 10, 275]
print("# 요소 내부에 없는 값 찾기")
number = 10000
if number in numbers: #try
print("{}는 {} 위치에 있습니다.".format(number, numbers.index(number)))
else: # except
print("리스트 내부에 없는 값입니다.")
print()
|
# 소수점이 없는 숫자(정수)
# 소수점이 있는 숫자(정수 < 실수)
# 존재하지 않는 수 = 허수(정수 < 실수 < 복소수)
# Python에서는 숫자의 나눗셈을 할때 float형인지 int형인지 크게 신경을 안써도 된다.(대부분 float형으로 반환)
# 연산자 : *, +, **(제곱), %, //(몫)
# print함수의 경우 숫자를 출력하기 위해서는 "" 가 필요없지만, 문자열의 출력을 위해선 ""가 필요하다.
print("기본적인 연산")
print(15, "+", 4, "=", 15+4)
print(15, "-", 4, "=", 15-4)
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("변환", flatten(example)) |
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.이름, self.나이)
# 위오 같은 class의 선언에서 __시작해서 __로 끝나는 함수가 있는데 이는 특수한 경우에 자동적으로 호출되는 함수이다.
student = Student("강성제", 20)
student.output
print(str(student))
class NewStudent:
def __init__(self, 이름, 나이):
self.이름 = 이름
self.나이 = 나이
def __eq__(self, other):
print("eq() 함수")
return self.나이 == other.나이 and self.이름 == other.이름
def __ne__(self, other):
print("ne() 함수")
return self.나이 != other.나이 and self.이름 != other.이름
def __gt__(self, other):
print("gt() 함수")
return self.나이 > other.나이 and self.이름 > other.이름
def __ge__(self, other):
print("ge() 함수")
return self.나이 >= other.나이 and self.이름 >= other.이름
def __lt__(self, other):
print("lt() 함수")
return self.나이 < other.나이 and self.이름 < other.이름
def __le__(self, other):
print("le() 함수")
return self.나이 <= other.나이 and self.이름 <= other.이름
student = NewStudent("강성제", 20)
print(student == student)
print(student != student)
print(student > student)
print(student >= student)
print(student < student)
print(student <= student) |
#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 = None
self.right = None
def __repr__(self):
return str(self.data)
def find_largest_and_parent(node):
#set parent as none
parent = None
while node.right:
#assume right node is always larger
parent = node
node = node.right
return node, parent
def find_second_largest(node):
#if no node return 0
if not node:
return None
#set value to zero
second_largest = None
#if no right node
if node.left and not node.right:
#find 2nd largest via that route
second_largest, _ = find_largest_and_parent(node.left)
else:
#find via that node
_, second_largest = find_largest_and_parent(node)
print("second_largest", second_largest)
return second_largest
def test_0():
node_a = Node(5)
assert not find_second_largest(node_a)
def test_1():
node_a = Node(5)
node_b = Node(3)
node_c = Node(8)
node_d = Node(2)
node_e = Node(4)
node_f = Node(7)
node_g = Node(9)
node_a.left = node_b
node_a.right = node_c
node_b.left = node_d
node_b.right = node_e
node_c.left = node_f
node_c.right = node_g
assert find_second_largest(node_a).data == 8
def test_2():
node_a = Node(5)
node_b = Node(3)
node_d = Node(2)
node_e = Node(4)
node_a.left = node_b
node_b.left = node_d
node_b.right = node_e
assert find_second_largest(node_a).data == 4
test_0()
test_1()
test_2()
|
#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 example, given the array [‘G’, ‘B’, ‘R’, ‘R’, ‘B’, ‘R’, ‘G’], it should become [‘R’, ‘R’, ‘R’, ‘G’, ‘G’, ‘B’, ‘B’].
def swap_indices(arr, i, j):
#get value of array index and store in tmp varaoble
tmp = arr[i]
#set value of array index i to array index j value
arr[i] = arr[j]
#set value of array index j to tmp value
arr[j] = tmp
def pull_elements_to_front(arr, start_index, end_index, letter):
#set i to srt index
i = start_index
#set j to end inex
j = end_index
#and last letter index to -1
last_letter_index = -1
#while i less then j
while i < j:
#if vlaue at array index i= the letter
if arr[i] == letter:
#then make i the last leter index
last_letter_index = i
#ass one to that value
i += 1
#if value at array index j not = to letter
elif arr[j] != letter:
#minus one from j i.e. end index
j -= 1
#otherise
else:
#set last letter index to i
last_letter_index = i
#and swap indices
swap_indices(arr, i, j)
return last_letter_index
#redorfer fucntion
def reorder_array(arr):
#find last index of red
last_index = pull_elements_to_front(arr, 0, len(arr) - 1, "R")
#then for the green and remeber to add one to tart index fotr it
pull_elements_to_front(arr, last_index + 1, len(arr) - 1, "G")
return arr
assert reorder_array(['G', 'R']) == ['R', 'G']
assert reorder_array(['G', 'B', 'R']) == ['R', 'G', 'B']
assert reorder_array(['B', 'G', 'R']) == ['R', 'G', 'B']
assert reorder_array(['G', 'B', 'R', 'R', 'B', 'R', 'G']) == [
'R', 'R', 'R', 'G', 'G', 'B', 'B']
|
#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 randint(1, 5)
def rand7():
i = 5*rand5() + rand5() - 5 # uniformly samples between 1-25
if i < 22:
return i % 7 + 1
return rand7()
num_experiments = 100000
result_dict = dict()
for _ in range(num_experiments):
number = rand7()
if number not in result_dict:
result_dict[number] = 0
result_dict[number] += 1
desired_probability = 1 / 7
for number in result_dict:
result_dict[number] = result_dict[number] / num_experiments
assert round(desired_probability, 2) == round(result_dict[number], 2)
|
#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 ** 2
for _ in range(num_random_tests):
x_rand = random() * radius
y_rand = random() * radius
if (x_rand ** 2) + (y_rand ** 2) < rsquared:
pi_counter += 1
return 4 * pi_counter / num_random_tests
assert round(estimate_pi(100000000), 3) == 3.141
|
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()):
self.fila.pop(0)
def inverter(self):
pilha = Pilha()
for i in range(self.lenght()-1,-1,-1):
pilha.push(self.fila[i])
print(pilha.pilha)
class Pilha():
def __init__(self):
self.pilha = []
def lenght(self):
return len(self.pilha)
def isEmpyt(self):
return self.lenght()==0
def push(self, elemento):
self.pilha.append(elemento)
def pop():
self.pilha
fila = Fila()
fila.enqueue(1)
fila.enqueue(2)
fila.enqueue(3)
print(fila.fila)
fila.inverter()
|
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 be either 978 or 979. It is always 3 digits in length
->Registration group: for the particular zone, may be between 1 and 5 digits in length
->Registrant: for the particular publisher or imprint. This may be up to 7 digits in length
->Publication: for the particular edition and format of a specific title, may be up to 6 digits in length
->Check digit: the final single digit that mathematically validates the rest of the number """
isbn_split = book.isbn.split('-')
if len(book.isbn) != 17 or len(isbn_split) != 5:
raise BookValidatorException('Invalid isbn')
if isbn_split[0] != '978' and isbn_split[0] != '979':
raise BookValidatorException('Invalid isbn - prefix (it can only be 978 or 979)!')
if len(isbn_split[1]) == 0 or len(isbn_split[1]) > 5:
raise BookValidatorException('Invalid isbn - The length of registration group may be between 1 and 5 digits')
if len(isbn_split[2]) > 7:
raise BookValidatorException('Invalid isbn -the length of the registrant element may be up to t digits')
if len(isbn_split[3]) > 6:
raise BookValidatorException('Invalid isbn -the length of the publication element may be up to 6 digits')
if len(isbn_split[4]) != 1:
raise BookValidatorException('Invalid isbn - the length of the check digit must be 1 digit')
def dublicate_isbn(self, book, list):
b = book.isbn
for a in list:
if b == a.isbn:
raise Exception
|
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]] + solution
if __name__ == '__main__':
nums = [4, 2, 4, 2, 5, 2, 1, 3, 3]
max_sum = 9
result = recursive_backtracking(nums, max_sum)
print(*result) |
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 = item
if item > high:
high = item
return (high - low)
assert(max_difference([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 9)
assert(max_difference([5, 2, 5, 3, 4, 5, 6, 7, 7, 8, 9]) == 7)
assert(max_difference([0, 2, 3, 4, 5, 6, 7, 800, 9, 10]) == 800)
def max_sale(ls):
"""Return the indices that provide the greatest sale price."""
min_price = ls[0]
max_sale = ls[1] - ls[0]
for i in range(1, len(ls)):
min_price = min(min_price, ls[i - 1])
current_sale = ls[i] - min_price
max_sale = max(current_sale, max_sale)
return max_sale
assert(max_sale([5, 2, 5, 3, 4, 5, 6, 7, 7, 8, 9]) == 7)
assert(max_sale([5, 2, 5, 3, 4, 5, 60, 7, 7, 8, 9]) == 58)
assert(max_sale([9, 7, 4, 3, 1]) == -1)
assert(max_sale([9, 7, 4, 2, 1]) == -1)
|
'''
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 enumerate(phrase):
if c == letter:
qtd += 1
print(f"letra '{c}' na posicao: {i}")
if qtd > 0 :
print(f"Quantidade de ocorrencias: {qtd}")
else:
print("Nao ha ocorrencias da letra solicitada.")
|
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, shape, order='F')
return plt.imshow(shaped_matrix, cmap=gray)
def show_letter(pixels):
"""Display the provided pixels in the standard letter shape."""
return show_image(pixels, (30, 30))
def show_wordsearch(pixels):
"""Display the provided pixels in the standard wordsearch shape."""
return show_image(pixels, (450, 450))
def pixel_line(start, end, rad=2):
"""Create a line from at the specified pixel coordinates with a radius.
:param start: The starting position as pixel coordinates
:param end: The ending position as pixel coordinates
:param rad: The radius of the line in pixels
:return: A 450x450x4 RGBA image array with a yellow line drawn on a
transparent background
"""
base = np.zeros((450, 450, 4))
sx, sy = start
ex, ey = end
steps = int(max(abs(ex - sx), abs(ey - sy)))
xstep = (ex - sx)/steps
ystep = (ey - sy)/steps
currentx, currenty = start
yellow_pixel = np.array([1, 1, 0, 1])
for _ in range(steps):
icurrentx, icurrenty = int(currentx), int(currenty)
base[max(0, icurrenty - rad):min(450, icurrenty + rad),
max(0, icurrentx - rad):min(450, icurrentx + rad)] = yellow_pixel
currentx += xstep
currenty += ystep
return base
def letter_line(x, y, direction, length, rad=2):
"""Create a line at the specified letter-grid coordinates.
:param x: The starting x-coordinate (0 <= x < 15)
:param y: The starting y-coordinate (0 <= y < 15)
:param direction: A tuple giving the direction of the line
:param length: The length of the line in letters
:param rad: The radius of the line in pixels
:return: A 450x450x4 RGBA image array with a yellow line drawn on a
transparent background
"""
start = (x*30, y*30)
end = (((length - 1) * direction[0] + x) * 30,
((length - 1) * direction[1] + y) * 30)
return pixel_line(start, end, rad=rad)
def draw_line_from_word(word, coords, direction, rad=2):
"""Create a line from a single word-solution to a wordsearch.
:param word: The word as a string
:param coords: The (x, y) coordinate of the first letter of the word
:param direction: A tuple giving the direction of the solution
:param rad: Thre radius of the line in pixels
:return: A 450x450x4 RGBA image array with a yellow line drawn on a
transparent background
"""
x, y = coords
x += 0.5
y += 0.5
return letter_line(x, y, direction, len(word), rad=rad)
def draw_lines(words, rad=2):
"""Draw a line for each word-solution to a wordsearch and show the result.
:param words: The word-solutions as a `dict`:
`{'word': (start, end, direction)}`
:param rad: The radius of the line in pixels
"""
lines = [draw_line_from_word(word, start, direction, rad=rad) for
(word, (start, end, direction)) in words.items()]
[plt.imshow(line, alpha=0.5) for line in lines]
|
'''
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 they match).
The quote marks aren’t printed when the string is displayed.
'''
'''
# Variable
# Strings (str) Variable name cannot be start with no. expample : 01a , 22a, 2288a, @a
a = "I am working as a Devops"
# Integer ( int ) Means no
b = 123456
# Float (No) means desimal no
c = 15.56
# Complex
'''
z = 10j
print(type(z))
'''
# Booleans = True or False
# d = True
# e = False
# None
# printing the variables
# print(a)
# print(b)
# print(c)
# print(d)
# Printing the type of variables : str or float or int or booleans
# print(type(d))
# To make all capital
Dev = 'video editor'
Dev.upper()
'''
s,g,h = 29,34,45
print(s,g,h)
|
# 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)
# print(count)
# user = int(input("Enter the number of rows:"))
# for i in range(0,user):
# for j in range(0,user-i-1):
# print(end=" ")
# for j in range(0,i+1):
# print("*",end=" ")
# print()
for i in range(10):
if (i+1) % 2 != 0: # allow only even number
for j in range(10):
print('{:2} x {:2} : {:3}'.format(i+1, j+1, ((i+1)*(j+1))))
userInput = input('next')
if userInput!='n':
break |
"""
Воин
Создать класс воина, создать 2 или больше объектов воина с соответствующими воину атрибутами. Реализовать методы,
которые позволять добавить силы воину, улучшить оружие. Реализовать возможность драки 2х воинов с потерей здоровья,
приобретения опыта (можно магические методы, можно кастомные).
"""
class Warrior:
""" Класс игрового персонажа """
def __init__(self, name, power):
self.name = name
self.hp = 100
self.exp = 0
self.power = power
def attack(self, another_warrior):
another_warrior.hp = another_warrior.hp - self.power
self.exp += 40
return another_warrior.hp, self.exp
def heal(self):
self.hp += 15
return self.hp
def buff(self):
self.power += 5
return self.power
class Battle:
""" Битва """
def __init__(self, *args):
self.war1 = args[0]
self.war2 = args[1]
def start(self):
self.war1.attack(war2)
self.war2.heal()
self.war2.attack(war1)
self.war1.buff()
self.war1.attack(war2)
return print(f'Характеристики воина {war1.name}: \tЗдоровье: {war1.hp}, \tОпыт: {war1.exp}, \tСила: {war1.power},'
f'\nХарактеристики воина {war2.name}: \tЗдоровье: {war2.hp}, \tОпыт:{war2.exp}, \tСила: {war2.power}')
war1 = Warrior('Orc', 15)
war2 = Warrior('Elf', 12)
Battle(war1, war2).start()
|
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("l")
o = combinedname.count("o")
v = combinedname.count("v")
e = combinedname.count("e")
total1 = l+o+v+e
total_score = str(total)+str(total1)
if 10 > int(total_score) > 90:
print(f"Your score is {total_score}, you go together like coke and mentos.")
elif 40<=int(total_score) <= 50:
print(f"Your score is {total_score}, you are alright together.")
else:
print(f"Your score is {total_score}.") |
# =====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_list)
|
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)
print(listCompose)
print(listCompose[-3:])
print(listCompose[-1][0])
import sys
it=iter(listCompose)
#for v in it:
while True:
try:
print (next(it))
except StopIteration:
sys.exit() |
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 += 1
numero = numero // 10
print("O dígito ", digito, "ocorre", ocorrencia, "vezes no número", numeroReal)
main()
#https://pt.stackoverflow.com/q/461085/101
|
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/q/257905/101
|
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 que o segundo")
elif valor2 > valor1:
print("O segundo valor é maior que o primeiro")
elif valor2 == valor1:
print("Os números são iguais")
else:
print("Então insira os números corretos")
#https://pt.stackoverflow.com/q/414484/101
|
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úmero foi lido: {qnt}')
#https://pt.stackoverflow.com/q/485318/101
|
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: '))
media = (nota1 + nota2 + nota3 + nota4) / 4
final += media
print(f'Olá {nome} sua média no {bimestre}o. bimestre é {media}')
print(f'Olá {nome} sua média final é {final / 4} e você está {"aprovador" if final / 4 >= 5 else "reprovado"}')
#https://pt.stackoverflow.com/q/573063/101
|
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.