[FP] Code reformat

- Performed code reformat to the entire directory '1ano/1semestre/fp/'
This commit is contained in:
TiagoRG 2023-05-16 21:18:38 +01:00
parent 4cd88a465f
commit cd0b5c5f82
86 changed files with 401 additions and 370 deletions

View File

@ -2,7 +2,7 @@ largura = float(input("Largura? "))
altura = float(input("Altura? ")) altura = float(input("Altura? "))
area = largura * altura area = largura * altura
perimetro = largura*2 + altura*2 perimetro = largura * 2 + altura * 2
print("Area:", area) print("Area:", area)
print("Perimetro:", perimetro) print("Perimetro:", perimetro)

View File

@ -9,4 +9,3 @@ surname = input("Apelido? ")
course = input("Curso? ") course = input("Curso? ")
print("Olá {} {}!\nBem vindo ao curso de {}!".format(name, surname, course)) print("Olá {} {}!\nBem vindo ao curso de {}!".format(name, surname, course))

View File

@ -4,5 +4,4 @@ mins = secs // 60
m = mins % 60 m = mins % 60
h = mins // 60 h = mins // 60
print("{:02d}:{:02d}:{:02d}".format(h, m, s)) print("{:02d}:{:02d}:{:02d}".format(h, m, s))

View File

@ -1,13 +1,13 @@
from math import * from math import *
A = float(input('Comprimento do cateto A: ')) A = float(input('Comprimento do cateto A: '))
B = float(input('Comprimento do cateto B: ')) B = float(input('Comprimento do cateto B: '))
C = sqrt(A**2 + B**2) C = sqrt(A ** 2 + B ** 2)
cosseno = A / C cosseno = A / C
angRad = acos(cosseno) angRad = acos(cosseno)
angDeg = angRad * 180 / pi angDeg = angRad * 180 / pi
print(f'O comprimento da hipotenusa é {round(C, 2)} e o valor do angulo entre o cateto A e a hipotenusa é {round(angDeg, 2)}°') print(
f'O comprimento da hipotenusa é {round(C, 2)} e o valor do angulo entre o cateto A e a hipotenusa é {round(angDeg, 2)}°')

View File

@ -1,6 +1,5 @@
from math import sqrt from math import sqrt
x1, y1 = input("Introduza x1 e y1, separados por uma virgula ',': ").split(',') x1, y1 = input("Introduza x1 e y1, separados por uma virgula ',': ").split(',')
x2, y2 = input("Introduza x2 e y2, separados por uma virgula ',': ").split(',') x2, y2 = input("Introduza x2 e y2, separados por uma virgula ',': ").split(',')
@ -9,6 +8,6 @@ y1 = float(y1)
x2 = float(x2) x2 = float(x2)
y2 = float(y2) y2 = float(y2)
distancia = sqrt((x2 - x1)**2 + (y2 - y1)**2) distancia = sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
print('A distancia entre os dois pontos é: ', distancia) print('A distancia entre os dois pontos é: ', distancia)

View File

@ -1,7 +1,7 @@
A = 3 A = 3
M = 2 M = 2
viagensDia = 2 * M * sum(i for i in range(1, A+1)) viagensDia = 2 * M * sum(i for i in range(1, A + 1))
viagensAno = viagensDia * 365 viagensAno = viagensDia * 365
mAno = viagensAno * 3 mAno = viagensAno * 3

View File

@ -1,4 +1,3 @@
# A teenager is a person between 13 and 19 years old, inclusive. # A teenager is a person between 13 and 19 years old, inclusive.
# A child is under 13. A grown-up is 20 or more. # A child is under 13. A grown-up is 20 or more.
# This program outputs the age category for a given input age. # This program outputs the age category for a given input age.
@ -15,7 +14,7 @@ if age < 0:
print("Age:", age) print("Age:", age)
if age < 13 : if age < 13:
cat = "child" cat = "child"
elif 13 < age < 20: elif 13 < age < 20:
cat = "teenager" cat = "teenager"

View File

@ -2,7 +2,8 @@ import math
POINTS = (6, 13, 4, 18, 1, 20, 5, 12, 9, 14, 11, 8, 16, 7, 19, 3, 17, 2, 15, 10) POINTS = (6, 13, 4, 18, 1, 20, 5, 12, 9, 14, 11, 8, 16, 7, 19, 3, 17, 2, 15, 10)
print("Introduza as coordenadas (x, y) do dardo.\nRepresenta as posicoes horizontal e vertical respetivamente.\nAmbas em milimetros.") print(
"Introduza as coordenadas (x, y) do dardo.\nRepresenta as posicoes horizontal e vertical respetivamente.\nAmbas em milimetros.")
x = int(input('X: ')) x = int(input('X: '))
y = int(input('Y: ')) y = int(input('Y: '))
@ -19,7 +20,6 @@ elif mod < 32:
print('Pontuacao: 25 pontos.') print('Pontuacao: 25 pontos.')
exit(1) exit(1)
angleRad = math.atan2(y, x) angleRad = math.atan2(y, x)
angleDeg = math.degrees(angleRad) - 9 angleDeg = math.degrees(angleRad) - 9
score = POINTS[int(angleDeg / 20)] score = POINTS[int(angleDeg / 20)]

View File

@ -1,7 +1,6 @@
CTP = float(input('Componente Teorica-pratica: ')) CTP = float(input('Componente Teorica-pratica: '))
CP = float(input('Componente Pratica: ')) CP = float(input('Componente Pratica: '))
NF = round(0.3 * CTP + 0.7 * CP) NF = round(0.3 * CTP + 0.7 * CP)
if (CTP < 6.6) or (CP < 6.6): if (CTP < 6.6) or (CP < 6.6):

View File

@ -9,7 +9,7 @@ print("Índice de Massa Corporal")
altura = float(input("Altura (m)? ")) altura = float(input("Altura (m)? "))
peso = float(input("Peso (kg)? ")) peso = float(input("Peso (kg)? "))
imc = peso / altura**2 imc = peso / altura ** 2
print("IMC:", imc, "kg/m2") print("IMC:", imc, "kg/m2")

View File

@ -2,7 +2,7 @@
# given the height (in meter) and weight (in kg) of a person. # given the height (in meter) and weight (in kg) of a person.
def bodyMassIndex(height, weight): def bodyMassIndex(height, weight):
# Complete the function definition... # Complete the function definition...
bmi = weight / height**2 bmi = weight / height ** 2
return bmi return bmi
@ -10,7 +10,7 @@ def bodyMassIndex(height, weight):
# BMI: <18.5 [18.5, 25[ [25, 30[ 30 or greater # BMI: <18.5 [18.5, 25[ [25, 30[ 30 or greater
# Category: Underweight Normal weight Overweight Obesity # Category: Underweight Normal weight Overweight Obesity
def bmiCategory(bmi): def bmiCategory(bmi):
assert bmi>0 assert bmi > 0
# Complete the function definition... # Complete the function definition...
if bmi < 18.5: if bmi < 18.5:
return 'Underweight' return 'Underweight'

View File

@ -1,6 +1,7 @@
def isLeapYear(year): def isLeapYear(year):
return year % 400 == 0 if year % 100 == 0 else year % 4 == 0 return year % 400 == 0 if year % 100 == 0 else year % 4 == 0
def monthDays(year, month): def monthDays(year, month):
assert month > 0 assert month > 0
@ -9,6 +10,7 @@ def monthDays(year, month):
return days + 1 if (isLeapYear(year) and month == 2) else days return days + 1 if (isLeapYear(year) and month == 2) else days
def nextDay(year, month, day): def nextDay(year, month, day):
# Verifica se é o último dia do ano # Verifica se é o último dia do ano
if (month, day) == (12, 31): if (month, day) == (12, 31):
@ -52,6 +54,7 @@ def main():
y, m, d = nextDay(2017, 12, 31) y, m, d = nextDay(2017, 12, 31)
print(y, m, d) # 2018 1 1 ? print(y, m, d) # 2018 1 1 ?
# call the main function # call the main function
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -4,9 +4,11 @@ def max2(x, y):
else: else:
return y return y
def max3(x, y, z): def max3(x, y, z):
return max2(x, max2(y, z)) return max2(x, max2(y, z))
def main(): def main():
n1 = float(input('Introduza dois valores.\nN1: ')) n1 = float(input('Introduza dois valores.\nN1: '))
n2 = float(input('N2: ')) n2 = float(input('N2: '))

View File

@ -5,5 +5,6 @@ def tax(r):
return 0.2 * r - 100 return 0.2 * r - 100
return 0.3 * r - 300 return 0.3 * r - 300
x = float(input('R? ')) x = float(input('R? '))
print('O valor de tax(r) é: {:.3f}'.format(tax(x))) print('O valor de tax(r) é: {:.3f}'.format(tax(x)))

View File

@ -1,15 +1,18 @@
def intersects(a1, b1, a2, b2): def intersects(a1, b1, a2, b2):
assert a1 < b1 assert a1 <= b1 and a2 <= b2, "Os intervalos não são válidos."
assert a2 < b2 return a1 <= b2 and a2 <= b1
if a1 < b2 and a2 < b1:
return True
else:
return False
a1 = float(input("a1: ")) def main():
b1 = float(input("b1: ")) a1 = float(input("a1: "))
a2 = float(input("a2: ")) b1 = float(input("b1: "))
b2 = float(input("b2: ")) a2 = float(input("a2: "))
b2 = float(input("b2: "))
print(intersects(a1, b1, a2, b2)) try:
print(intersects(a1, b1, a2, b2))
except AssertionError as e:
print(e)
main()

View File

@ -11,5 +11,6 @@ def countdown(n):
yield n yield n
n -= 1 n -= 1
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -7,11 +7,13 @@ def mdc(a, b):
else: else:
return mdc(b, r) return mdc(b, r)
def main(): def main():
print('Este programa calcula o máximo divisor comum de dois námeros naturais') print('Este programa calcula o máximo divisor comum de dois námeros naturais')
n1 = int(input('Numero 1: ')) n1 = int(input('Numero 1: '))
n2 = int(input('Numero 2: ')) n2 = int(input('Numero 2: '))
print(f'\nO Máximo Divisor Comum de {n1} e {n2} é: {mdc(n1, n2)}') print(f'\nO Máximo Divisor Comum de {n1} e {n2} é: {mdc(n1, n2)}')
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -1,11 +1,11 @@
# Esta função implementa g(x) = 8 - x**3 # Esta função implementa g(x) = 8 - x**3
def g(x): def g(x):
return 8 - x**3 return 8 - x ** 3
# Defina uma função que implemente p(x) = x**2 + 2x + 3 # Defina uma função que implemente p(x) = x**2 + 2x + 3
def p(x): def p(x):
return x**2 + 2*x + 3 return x ** 2 + 2 * x + 3
def main(): def main():

View File

@ -20,6 +20,7 @@ Este é um número {category(n, div_list_array)}.
""") """)
# Obtém uma lista com todos os dividores de um número # Obtém uma lista com todos os dividores de um número
def divList(n): def divList(n):
divs = [] divs = []
@ -28,6 +29,7 @@ def divList(n):
divs.append(str(x)) divs.append(str(x))
return divs return divs
# Obtém a categoria de um número # Obtém a categoria de um número
def category(n, divs): def category(n, divs):
total = 0 total = 0
@ -37,5 +39,6 @@ def category(n, divs):
if total == n: return 'perfeito' if total == n: return 'perfeito'
if total > n: return 'abundante' if total > n: return 'abundante'
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -4,9 +4,11 @@ def factorial(n):
total *= x total *= x
return total return total
def main(): def main():
n = int(input('Introduza um número: ')) n = int(input('Introduza um número: '))
print('O fatorial de {} é: {}'.format(n, factorial(n))) print('O fatorial de {} é: {}'.format(n, factorial(n)))
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -1,11 +1,13 @@
def fibonacci(n): def fibonacci(n):
if n == 0: return 0 if n == 0: return 0
if n == 1: return 1 if n == 1: return 1
return fibonacci(n-1) + fibonacci(n-2) return fibonacci(n - 1) + fibonacci(n - 2)
def main(): def main():
n = int(input('Introduza um número: ')) n = int(input('Introduza um número: '))
print(f'O {n}º número de Fibonacci é: {fibonacci(n)}') print(f'O {n}º número de Fibonacci é: {fibonacci(n)}')
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -2,6 +2,7 @@
import random import random
def main(): def main():
# Pick a random number between 1 and 100, inclusive # Pick a random number between 1 and 100, inclusive
secret = random.randrange(1, 101) secret = random.randrange(1, 101)
@ -19,7 +20,9 @@ def main():
c += 1 c += 1
trieslist.append(str(num)) trieslist.append(str(num))
triesstr = ', '.join(trieslist) triesstr = ', '.join(trieslist)
print(f'Well done! The secret number was {secret}. It took you {c} tries to get it right.\nList of tries: {triesstr}') print(
f'Well done! The secret number was {secret}. It took you {c} tries to get it right.\nList of tries: {triesstr}')
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -3,8 +3,8 @@ import math
def leibnizPi4(n): def leibnizPi4(n):
total = 0 total = 0
for x in range(1, n+1): for x in range(1, n + 1):
increment = 1/(x*2-1) increment = 1 / (x * 2 - 1)
total += -increment if x % 2 == 0 else increment total += -increment if x % 2 == 0 else increment
return total return total
@ -13,7 +13,7 @@ def main():
num = int(input('Introduza o número de termos: ')) num = int(input('Introduza o número de termos: '))
print(f""" print(f"""
Resultado da série de Leibniz: {leibnizPi4(num)} Resultado da série de Leibniz: {leibnizPi4(num)}
Valor do PI/4: {math.pi/4} Valor do PI/4: {math.pi / 4}
""") """)

View File

@ -10,14 +10,17 @@ def GetValues():
count += 1 count += 1
return values return values
# Calcula a média dos valores da lista 'values' # Calcula a média dos valores da lista 'values'
def GetMedia(val): def GetMedia(val):
return sum(val) / len(val) return sum(val) / len(val)
# Função principal # Função principal
def main(): def main():
values = GetValues() values = GetValues()
print('Média dos valores introduzidos: ', GetMedia(values)) print('Média dos valores introduzidos: ', GetMedia(values))
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -3,7 +3,7 @@ Un = 100 # Un = each term of the sequence. Initially = U0
count = 0 count = 0
while Un > 0: while Un > 0:
print(round(Un, 4)) print(round(Un, 4))
Un = 1.01*Un - 1.01 # Set Un to the next term of the sequence Un = 1.01 * Un - 1.01 # Set Un to the next term of the sequence
count += 1 count += 1
print('O programa mostrou ', count, ' termos') print('O programa mostrou ', count, ' termos')

View File

@ -1,7 +1,7 @@
# Show a table of the squares of the first four numbers # Show a table of the squares of the first four numbers
print(" {:1s} | {:>3s} | {:>7s}".format("n", "", "2**n")) print(" {:1s} | {:>3s} | {:>7s}".format("n", "", "2**n"))
for n in range(1, 21): for n in range(1, 21):
print("{:2d} | {:3d} | {:7d}".format(n, n**2, 2**n)) print("{:2d} | {:3d} | {:7d}".format(n, n ** 2, 2 ** n))
# Modify the program to show the squares of 1..20. (Use the range function.) # Modify the program to show the squares of 1..20. (Use the range function.)
# Also, add a column to show 2**n. Adjust the formatting. # Also, add a column to show 2**n. Adjust the formatting.

View File

@ -2,7 +2,8 @@
# JMR 2019 # JMR 2019
def isLeapYear(year): def isLeapYear(year):
return year%4 == 0 and year%100 != 0 or year%400 == 0 return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
def printLeapYears(year1, year2): def printLeapYears(year1, year2):
"""Print all leap years in range [year1, year2[.""" """Print all leap years in range [year1, year2[."""

View File

@ -10,10 +10,12 @@ def inputTotal():
if n == '': return tot if n == '': return tot
tot += float(n) tot += float(n)
# MAIN PROGRAM # MAIN PROGRAM
def main(): def main():
tot = inputTotal() tot = inputTotal()
print(tot) print(tot)
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -11,13 +11,15 @@
# JMR 2019 # JMR 2019
def main(): def main():
for i in range (1, 11): for i in range(1, 11):
table(i) table(i)
print() print()
def table(n): def table(n):
for i in range(1, 11): for i in range(1, 11):
print(f'{n} x {i} = {n*i}') print(f'{n} x {i} = {n * i}')
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -6,12 +6,14 @@
import turtle # allows us to use the turtles library import turtle # allows us to use the turtles library
# Make turtle t draw a square with the given side length # Make turtle t draw a square with the given side length
def square(t, side): def square(t, side):
for n in range(4): for n in range(4):
t.forward(side) t.forward(side)
t.left(90) t.left(90)
# Make turtle t draw a spiral. # Make turtle t draw a spiral.
# The first side should have length = start, the second start+incr, etc., # The first side should have length = start, the second start+incr, etc.,
# until the length reaches length=end (exclusive). # until the length reaches length=end (exclusive).

View File

@ -19,14 +19,14 @@ def evenThenOdd(string):
def removeAdjacentDuplicates(s): def removeAdjacentDuplicates(s):
new = '' new = ''
for i in range(len(s)): for i in range(len(s)):
if i == 0 or s[i] != s[i-1]: if i == 0 or s[i] != s[i - 1]:
new += s[i] new += s[i]
return new return new
def reapeatNumTimes(n): def reapeatNumTimes(n):
lst = [] lst = []
for i in range(1, n+1): for i in range(1, n + 1):
lst += [i] * i lst += [i] * i
return lst return lst

View File

@ -10,5 +10,6 @@ def shorten(string):
abv += char abv += char
return abv return abv
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -19,6 +19,7 @@ def nameToTels(partName, telList, nameList):
tels.append(telList[index]) tels.append(telList[index])
return tels return tels
def main(): def main():
# Lists of telephone numbers and names # Lists of telephone numbers and names
telList = ['975318642', '234000111', '777888333', '911911911'] telList = ['975318642', '234000111', '777888333', '911911911']
@ -26,15 +27,15 @@ def main():
# Test telToName: # Test telToName:
tel = input("Tel number? ") tel = input("Tel number? ")
print( telToName(tel, telList, nameList) ) print(telToName(tel, telList, nameList))
print( telToName('234000111', telList, nameList) == "Brad" ) print(telToName('234000111', telList, nameList) == "Brad")
print( telToName('222333444', telList, nameList) == "222333444" ) print(telToName('222333444', telList, nameList) == "222333444")
# Test nameToTels: # Test nameToTels:
name = input("Name? ") name = input("Name? ")
print( nameToTels(name, telList, nameList) ) print(nameToTels(name, telList, nameList))
print( nameToTels('Clau', telList, nameList) == ['777888333'] ) print(nameToTels('Clau', telList, nameList) == ['777888333'])
print( nameToTels('Br', telList, nameList) == ['234000111', '911911911'] ) print(nameToTels('Br', telList, nameList) == ['234000111', '911911911'])
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -15,7 +15,6 @@ print(len(train))
# Qual o total de passageiros? # Qual o total de passageiros?
print(sum(train)) print(sum(train))
# Os dias da semana: # Os dias da semana:
week = ['sab', 'dom', 'seg', 'ter', 'qua', 'qui', 'sex'] week = ['sab', 'dom', 'seg', 'ter', 'qua', 'qui', 'sex']

View File

@ -15,6 +15,7 @@ def passengers(train, n):
num2 = sum(class2) num2 = sum(class2)
return [num1, num2] return [num1, num2]
def test(): def test():
train1 = [12, 32, 10, 21] train1 = [12, 32, 10, 21]
train2 = [9, 29, 19] train2 = [9, 29, 19]
@ -26,6 +27,7 @@ def test():
print(passengers(train2, 1)) print(passengers(train2, 1))
print(passengers(train3, 0)) print(passengers(train3, 0))
# Run tests: # Run tests:
test() test()

View File

@ -7,6 +7,7 @@ def transfer1car(t1, t2):
t2.append(t1[-1]) t2.append(t1[-1])
t1.remove(t1[-1]) t1.remove(t1[-1])
def test(): def test():
train1 = [12, 32, 10, 21] train1 = [12, 32, 10, 21]
train2 = [9, 29, 19] train2 = [9, 29, 19]
@ -21,6 +22,7 @@ def test():
transfer1car(train3, train1) transfer1car(train3, train1)
print(train1, train2, train3) print(train1, train2, train3)
# Run tests: # Run tests:
test() test()

View File

@ -18,6 +18,7 @@ def match(t1, t2, g1, g2):
t1[2] += 1 t1[2] += 1
t2[2] += 1 t2[2] += 1
def test(): def test():
team1 = ["Ajax", 0, 0, 0] team1 = ["Ajax", 0, 0, 0]
team2 = ["Benfica", 0, 0, 0] team2 = ["Benfica", 0, 0, 0]
@ -31,6 +32,7 @@ def test():
match(team3, team1, 0, 3) match(team3, team1, 0, 3)
print(team1, team2, team3) print(team1, team2, team3)
# Run tests: # Run tests:
test() test()

View File

@ -9,6 +9,7 @@ def inputDate():
d = int(input("Dia? ")) d = int(input("Dia? "))
return (y, m, d) return (y, m, d)
# Complete a definição de forma que inputPerson(msg) # Complete a definição de forma que inputPerson(msg)
# peça o nome de uma pessoa e a sua data de nascimento # peça o nome de uma pessoa e a sua data de nascimento
# e devolva esses dados num tuplo com a forma (nome, (ano, mẽs, dia)). # e devolva esses dados num tuplo com a forma (nome, (ano, mẽs, dia)).
@ -18,6 +19,7 @@ def inputPerson(msg):
birth = inputDate() birth = inputDate()
return (name, birth) return (name, birth)
def test(): def test():
print("Natal de 2020") print("Natal de 2020")
natal = inputDate() natal = inputDate()
@ -31,6 +33,7 @@ def test():
older = p1[1] < p2[1] older = p1[1] < p2[1]
print("p1 é mais velha que p2:", older) print("p1 é mais velha que p2:", older)
# Run tests: # Run tests:
test() test()

View File

@ -4,14 +4,16 @@
MESESPT = ("janeiro", "fevereiro", "março", "abril", "maio", "junho", MESESPT = ("janeiro", "fevereiro", "março", "abril", "maio", "junho",
"julho", "agosto", "setembro", "outubro", "novembro", "dezembro") "julho", "agosto", "setembro", "outubro", "novembro", "dezembro")
# Complete a função para que, dado um tuplo (ano, mes, dia) # Complete a função para que, dado um tuplo (ano, mes, dia)
# devolva um data por extenso. # devolva um data por extenso.
# Por exemplo, datePT((1938, 1, 22)) deve devolver "22 de janeiro de 1938". # Por exemplo, datePT((1938, 1, 22)) deve devolver "22 de janeiro de 1938".
def datePT(date): def datePT(date):
ano, mes, dia = date ano, mes, dia = date
s = f"{str(dia)} de {MESESPT[mes-1]} de {ano}" s = f"{str(dia)} de {MESESPT[mes - 1]} de {ano}"
return s return s
# Complete a definição para converter uma data no formato "DD/MM/AAAA" # Complete a definição para converter uma data no formato "DD/MM/AAAA"
# num tuplo de inteiros com (ano, mês, dia). # num tuplo de inteiros com (ano, mês, dia).
# Por exemplo: parseDMY("25/12/2020") deve devolver (2020, 12, 25). # Por exemplo: parseDMY("25/12/2020") deve devolver (2020, 12, 25).

View File

@ -17,8 +17,8 @@ def printFilesSize(path):
print(f"[Error] Path is not a directory: '{os.path.abspath(path)}'") print(f"[Error] Path is not a directory: '{os.path.abspath(path)}'")
exit(1) exit(1)
else: else:
print(f'|{"-"*78}|') print(f'|{"-" * 78}|')
print(f'| {"File":<63} {"Size":>12} |\n|{"-"*78}|') print(f'| {"File":<63} {"Size":>12} |\n|{"-" * 78}|')
for file in directory: for file in directory:
base_size = os.stat(f'{path}/{file}').st_size base_size = os.stat(f'{path}/{file}').st_size
if os.path.isdir(f'{path}/{file}'): if os.path.isdir(f'{path}/{file}'):
@ -28,11 +28,11 @@ def printFilesSize(path):
elif base_size < 1024 ** 2: elif base_size < 1024 ** 2:
size = f'{base_size // 1024}.{str(base_size % 1024)[0]} KB' size = f'{base_size // 1024}.{str(base_size % 1024)[0]} KB'
elif base_size < 1024 ** 3: elif base_size < 1024 ** 3:
size = f'{base_size // (1024**2)}.{str(base_size % (1024**2))[0]} MB' size = f'{base_size // (1024 ** 2)}.{str(base_size % (1024 ** 2))[0]} MB'
else: else:
size = f'{base_size // (1024**3)}.{str(base_size % (1024**3))[0]} GB' size = f'{base_size // (1024 ** 3)}.{str(base_size % (1024 ** 3))[0]} GB'
print(f'| {file:<63} {size:>12} |') print(f'| {file:<63} {size:>12} |')
print(f'|{"-"*78}|') print(f'|{"-" * 78}|')
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -32,5 +32,6 @@ def main():
return return
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -44,5 +44,3 @@ def main():
# Call main function # Call main function
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -1,6 +1,7 @@
from extras.allMatches import * # importa a função allMatches criada na aula05
import math import math
from extras.allMatches import * # importa a função allMatches criada na aula05
def main(): def main():
equipas = getTeams() # pede as equipas ao utilizador equipas = getTeams() # pede as equipas ao utilizador
@ -54,18 +55,18 @@ def getTable(teams, results):
# devolve a tabela ordenada por pontos, diferença de golos e por último por golos marcados. # devolve a tabela ordenada por pontos, diferença de golos e por último por golos marcados.
return {team: table[team] for team in return {team: table[team] for team in
sorted(table, key=lambda x: (table[x][5], table[x][3]-table[x][4], table[x][3]), reverse=True)} sorted(table, key=lambda x: (table[x][5], table[x][3] - table[x][4], table[x][3]), reverse=True)}
def updateStats(table, team, gm, gs): def updateStats(table, team, gm, gs):
table[team][5] += (points := 1 if gm == gs else (3 if gm > gs else 0)) # calcula os pontos a atribuir à equipa e adiciona à tabela table[team][5] += (
table[team][math.trunc(2 - points/2)] += 1 # determina o index ao qual atribui o jogo (V/E/D) points := 1 if gm == gs else (3 if gm > gs else 0)) # calcula os pontos a atribuir à equipa e adiciona à tabela
table[team][math.trunc(2 - points / 2)] += 1 # determina o index ao qual atribui o jogo (V/E/D)
table[team][3] += gm # adiciona os golos marcados table[team][3] += gm # adiciona os golos marcados
table[team][4] += gs # adiciona os golos marcados table[team][4] += gs # adiciona os golos marcados
def printTable(table): def printTable(table):
print(f"\n{'Equipa':<15}\tV\tE\tD\tGM\tGS\tPts") print(f"\n{'Equipa':<15}\tV\tE\tD\tGM\tGS\tPts")
for team in table: for team in table:

View File

@ -37,7 +37,6 @@ def transfer(bag1, amount, bag2):
def transferProcess(bag1, amount, bag2, coins): def transferProcess(bag1, amount, bag2, coins):
bagBackup = (bag1.copy(), bag2.copy()) bagBackup = (bag1.copy(), bag2.copy())
amountBackup = amount amountBackup = amount
@ -57,7 +56,7 @@ def transferProcess(bag1, amount, bag2, coins):
if len(coins) == 1: if len(coins) == 1:
return False return False
return transferProcess(bag1, amountBackup, bag2, COINS[COINS.index(firstUsedCoin)+1:]) return transferProcess(bag1, amountBackup, bag2, COINS[COINS.index(firstUsedCoin) + 1:])
def strbag(bag): def strbag(bag):
@ -113,4 +112,3 @@ def main():
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -1,7 +1,6 @@
# Devolve o IMC para uma pessoa com peso w e altura h. # Devolve o IMC para uma pessoa com peso w e altura h.
def imc(w, h): def imc(w, h):
return w/h**2 return w / h ** 2
def main(): def main():

View File

@ -1,4 +1,3 @@
def main(): def main():
A = "reading" A = "reading"
B = "eating" B = "eating"

View File

@ -1,14 +1,14 @@
# Algorithm from https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Pseudocode # Algorithm from https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Pseudocode
def primesUpTo(n): def primesUpTo(n):
assert n >= 2, "n must be >= 2" assert n >= 2, "n must be >= 2"
A = [True for i in range(n+1)] A = [True for i in range(n + 1)]
for i in range(2, n+1): for i in range(2, n + 1):
if A[i]: if A[i]:
for j in range(i**2, n+1, i): for j in range(i ** 2, n + 1, i):
A[j] = False A[j] = False
return set([i for i in range(2, n+1) if A[i]]) return set([i for i in range(2, n + 1) if A[i]])
def main(): def main():
@ -17,7 +17,7 @@ def main():
print(s) print(s)
# Do some checks: # Do some checks:
assert primesUpTo(30) == {2,3,5,7,11,13,17,19,23,29} assert primesUpTo(30) == {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}
assert len(primesUpTo(1000)) == 168 assert len(primesUpTo(1000)) == 168
assert len(primesUpTo(7918)) == 999 assert len(primesUpTo(7918)) == 999
assert len(primesUpTo(7919)) == 1000 assert len(primesUpTo(7919)) == 1000

View File

@ -1,6 +1,5 @@
import bisect import bisect
with open("wordlist.txt", "r") as f: with open("wordlist.txt", "r") as f:
word_list: list[str] = f.read().split() word_list: list[str] = f.read().split()

View File

@ -2,7 +2,7 @@ import math
def main(): def main():
print(findZero(lambda x: x + math.sin(10*x), 0.2, 0.4, 0.001)) print(findZero(lambda x: x + math.sin(10 * x), 0.2, 0.4, 0.001))
def findZero(func, a, b, tol): def findZero(func, a, b, tol):

View File

@ -1,4 +1,3 @@
# This function sorts a list (like list.sort) # This function sorts a list (like list.sort)
# using the insertion sort algorithm. # using the insertion sort algorithm.
# Modify it to accept a key= keyword argument that works like in list.sort. # Modify it to accept a key= keyword argument that works like in list.sort.
@ -37,7 +36,7 @@ def main():
assert lst == sorted(lst0, key=len) assert lst == sorted(lst0, key=len)
# sort by length, than lexicographic order: # sort by length, than lexicographic order:
myorder = lambda s:(len(s), s) myorder = lambda s: (len(s), s)
lst = lst0.copy() lst = lst0.copy()
insertionSort(lst, key=myorder) insertionSort(lst, key=myorder)
print("lst3", lst) print("lst3", lst)
@ -48,4 +47,3 @@ def main():
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -1,5 +1,4 @@
import sys import sys
import math
def integrate(f, a, b, n): def integrate(f, a, b, n):

View File

@ -7,7 +7,7 @@ def median(lst):
lst = sorted(lst, reverse=True) lst = sorted(lst, reverse=True)
if len(lst) % 2 == 0: if len(lst) % 2 == 0:
middle = len(lst) // 2 - 1 middle = len(lst) // 2 - 1
return sum(lst[middle:middle+2]) / 2 return sum(lst[middle:middle + 2]) / 2
else: else:
return lst[len(lst) // 2] return lst[len(lst) // 2]

View File

@ -4,7 +4,7 @@
# polynomial2(a,b,c) deve devolver uma função f tal que # polynomial2(a,b,c) deve devolver uma função f tal que
# f(x) seja o polinómio de segundo grau ax²+bx+c. # f(x) seja o polinómio de segundo grau ax²+bx+c.
def polynomial2(a, b, c): def polynomial2(a, b, c):
return lambda x: a*x**2 + b*x + c return lambda x: a * x ** 2 + b * x + c
# DESAFIO EXTRA: # DESAFIO EXTRA:
@ -14,7 +14,7 @@ def polynomial2(a, b, c):
# polynomial(a), onde a=[a0, a1, ..., an], deve devolver uma função f tal que # polynomial(a), onde a=[a0, a1, ..., an], deve devolver uma função f tal que
# f(x) seja o polinómio a0*x**n + a1*x**(n-1) + ... + an. # f(x) seja o polinómio a0*x**n + a1*x**(n-1) + ... + an.
def polynomial(coefs): def polynomial(coefs):
return lambda x: sum([coefs[i]*x**(len(coefs)-i-1) for i in range(len(coefs))]) return lambda x: sum([coefs[i] * x ** (len(coefs) - i - 1) for i in range(len(coefs))])
def main(): def main():
@ -34,6 +34,6 @@ def main():
s = polynomial([1, -1, 0, 100]) # creates s(x)=x³-x²+100 s = polynomial([1, -1, 0, 100]) # creates s(x)=x³-x²+100
print([s(x) for x in xx]) # [100, 100, 104, 118] print([s(x) for x in xx]) # [100, 100, 104, 118]
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -1,4 +1,3 @@
# Tabela classificativa da Primeira Liga de futebol de Portugal em 2018-11-30. # Tabela classificativa da Primeira Liga de futebol de Portugal em 2018-11-30.
# (Descarregada de https://www.resultados.com/futebol/portugal/primeira-liga/) # (Descarregada de https://www.resultados.com/futebol/portugal/primeira-liga/)
@ -34,21 +33,20 @@ def printTabela(tabela):
print("{:19s} {:>3} {:>3} {:>3} {:>3} {:>3}:{:<3} {:>3}".format( print("{:19s} {:>3} {:>3} {:>3} {:>3} {:>3}:{:<3} {:>3}".format(
"Equipa", "J", "V", "E", "D", "GM", "GS", "P")) "Equipa", "J", "V", "E", "D", "GM", "GS", "P"))
for reg in tabela: for reg in tabela:
nome,v,e,d,gm,gs = reg nome, v, e, d, gm, gs = reg
print("{:19s} {:3d} {:3d} {:3d} {:3d} {:3d}:{:<3d} {:3d}".format( print("{:19s} {:3d} {:3d} {:3d} {:3d} {:3d}:{:<3d} {:3d}".format(
nome, numJogos(reg), v, e, d, gm, gs, pontos(reg))) nome, numJogos(reg), v, e, d, gm, gs, pontos(reg)))
# numJogos é uma função definida por uma expressão lambda que, # numJogos é uma função definida por uma expressão lambda que,
# dado um registo de uma equipa, devolve o número de jogos que a equipa jogou. # dado um registo de uma equipa, devolve o número de jogos que a equipa jogou.
numJogos = lambda reg: reg[V]+reg[E]+reg[D] numJogos = lambda reg: reg[V] + reg[E] + reg[D]
# a) # a)
# Complete a expressão lambda para definir uma função que, # Complete a expressão lambda para definir uma função que,
# dado um registo de uma equipa, devolva o número de pontos da equipa. # dado um registo de uma equipa, devolva o número de pontos da equipa.
# (Cada vitória vale 3 pontos, cada empate vale 1 ponto.) # (Cada vitória vale 3 pontos, cada empate vale 1 ponto.)
pontos = lambda reg: reg[V]*3+reg[E] pontos = lambda reg: reg[V] * 3 + reg[E]
def main(): def main():
@ -57,7 +55,6 @@ def main():
print(tabela[-1][N], pontos(tabela[-1])) # Chaves 7? print(tabela[-1][N], pontos(tabela[-1])) # Chaves 7?
# Mostra a tabela classificativa original, não ordenada: # Mostra a tabela classificativa original, não ordenada:
printTabela(tabela) printTabela(tabela)
@ -70,14 +67,14 @@ def main():
# c) # c)
# Acrescente os argumentos adequados à função sorted para # Acrescente os argumentos adequados à função sorted para
# obter uma tabela ordenada por ordem decrescente da diferença GM-GS: # obter uma tabela ordenada por ordem decrescente da diferença GM-GS:
tab = sorted(tabela, key=lambda reg: reg[GM]-reg[GS], reverse=True) tab = sorted(tabela, key=lambda reg: reg[GM] - reg[GS], reverse=True)
printTabela(tab) printTabela(tab)
# d) # d)
# Acrescente os argumentos adequados à função sorted para # Acrescente os argumentos adequados à função sorted para
# obter uma tabela ordenada por ordem decrescente de pontos e, # obter uma tabela ordenada por ordem decrescente de pontos e,
# se iguais, por ordem da diferença GM-GS: # se iguais, por ordem da diferença GM-GS:
tab = sorted(tabela, key=lambda reg: (pontos(reg), reg[GM]-reg[GS]), reverse=True) tab = sorted(tabela, key=lambda reg: (pontos(reg), reg[GM] - reg[GS]), reverse=True)
printTabela(tab) printTabela(tab)

View File

@ -46,4 +46,3 @@ def main():
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -1,15 +1,14 @@
# Generates all length-3 words with symbols taken from the given alphabet. # Generates all length-3 words with symbols taken from the given alphabet.
def genWords3(symbols): def genWords3(symbols):
return [ x+y+z for x in symbols for y in symbols for z in symbols ] return [x + y + z for x in symbols for y in symbols for z in symbols]
# Generates all length-n words with symbols taken from the given alphabet. # Generates all length-n words with symbols taken from the given alphabet.
def genWords(symbols, n): def genWords(symbols, n):
if n == 0: if n == 0:
return [''] return ['']
lista = genWords(symbols, n-1) lista = genWords(symbols, n - 1)
return [ x+y for x in symbols for y in lista ] return [x + y for x in symbols for y in lista]
def main(): def main():
@ -26,6 +25,6 @@ def main():
lstC = genWords("01", 4) # should return all length-4 binary words lstC = genWords("01", 4) # should return all length-4 binary words
print(lstC) print(lstC)
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -12,6 +12,7 @@ endX("xxhixx") → "hixxxx"
endX("hixhix") "hihixx" endX("hixhix") "hihixx"
""" """
def endX(s): def endX(s):
if s == '': if s == '':
return '' return ''

View File

@ -1,10 +1,9 @@
# Calcula o factorial de n, baseado na recorrencia n! = n*(n-1)!. # Calcula o factorial de n, baseado na recorrencia n! = n*(n-1)!.
# Mas não termina! Detete a causa e corrija o erro. # Mas não termina! Detete a causa e corrija o erro.
def fact(n): def fact(n):
if n == 0: if n == 0:
return 1 return 1
return n*fact(n-1) return n * fact(n - 1)
# Calcula o maximo divisor comum entre a e b. # Calcula o maximo divisor comum entre a e b.
@ -12,19 +11,19 @@ def fact(n):
# Mas não termina! Detete a causa e corrija o erro. # Mas não termina! Detete a causa e corrija o erro.
def gcd(a, b): def gcd(a, b):
assert a > 0 and b > 0 assert a > 0 and b > 0
if a%b == 0: if a % b == 0:
return b return b
return gcd(b, a%b) return gcd(b, a % b)
def main(): def main():
print( fact(4) ) # 24 print(fact(4)) # 24
print( fact(5) ) # 120 print(fact(5)) # 120
x = 2*27*53*61 x = 2 * 27 * 53 * 61
y = 2*2*17*23*53 y = 2 * 2 * 17 * 23 * 53
print(x, y, gcd(x, y)) print(x, y, gcd(x, y))
assert gcd(x, y) == 2*53 assert gcd(x, y) == 2 * 53
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -1,4 +1,5 @@
import sys import sys
from ezgraphics import GraphicsWindow from ezgraphics import GraphicsWindow

View File

@ -24,4 +24,4 @@ def reverseDigits(value):
def reverseAux(partValue, partReversed): def reverseAux(partValue, partReversed):
if partValue == 0: if partValue == 0:
return partReversed return partReversed
return reverseAux(partValue//10, partReversed*10 + partValue%10) return reverseAux(partValue // 10, partReversed * 10 + partValue % 10)

View File

@ -28,23 +28,24 @@ def traced(func):
return tracedfunc return tracedfunc
# Initial tracing prefix: # Initial tracing prefix:
traced.indent = "" traced.indent = ""
# Uncomment to turn off tracing by default: # Uncomment to turn off tracing by default:
#traced.indent = None # traced.indent = None
#traced.indent = traced.__dict__.get("indent") # traced.indent = traced.__dict__.get("indent")
if __name__ == "__main__": if __name__ == "__main__":
# How to use this module: # How to use this module:
from traced import traced from traced import traced
@traced @traced
def func(x): def func(x):
return x*x return x * x
func(3) func(3)

View File

@ -27,4 +27,3 @@ def score(guess, secret):
cows_index.append(i) cows_index.append(i)
return len(bulls_index), len(cows_index) return len(bulls_index), len(cows_index)

View File

@ -10,7 +10,8 @@ def loadDataBase(fname, produtos):
with open(fname, 'r') as f: # Abre o ficheiro em modo de leitura with open(fname, 'r') as f: # Abre o ficheiro em modo de leitura
productsFileContent = f.read() # Cria uma string com o conteudo do ficheiro productsFileContent = f.read() # Cria uma string com o conteudo do ficheiro
for product in productsFileContent.split('\n')[1:]: # Divide a string 'productsFileContent' numa lista com cada produto for product in productsFileContent.split('\n')[
1:]: # Divide a string 'productsFileContent' numa lista com cada produto
productComponents = product.split(';') # Divide as componentes do produto (código, nome, secção, preço, iva) productComponents = product.split(';') # Divide as componentes do produto (código, nome, secção, preço, iva)
if len(productComponents) != 5: if len(productComponents) != 5:
@ -29,7 +30,8 @@ def registaCompra(produtos):
mostra nome, quantidade e preço final de cada um, mostra nome, quantidade e preço final de cada um,
e devolve dicionário com {codigo: quantidade, ...} e devolve dicionário com {codigo: quantidade, ...}
""" """
compra = {"totals": [0, 0, 0]} # Inicia o dicionário da compra com os totais da mesma: [total bruto, total iva, total liquido] compra = {"totals": [0, 0,
0]} # Inicia o dicionário da compra com os totais da mesma: [total bruto, total iva, total liquido]
userInput = input('Code? ') userInput = input('Code? ')
while userInput != "": while userInput != "":
try: try:
@ -52,7 +54,7 @@ def registaCompra(produtos):
noIvaPrice = produtos[code][2] * amount # Obtém o preço (sem iva) do determinado produto noIvaPrice = produtos[code][2] * amount # Obtém o preço (sem iva) do determinado produto
compra["totals"][0] += noIvaPrice # Adiciona o preço sem iva ao total bruto compra["totals"][0] += noIvaPrice # Adiciona o preço sem iva ao total bruto
compra["totals"][1] += noIvaPrice * produtos[code][3] # Adiciona o valor do iva ao total iva compra["totals"][1] += noIvaPrice * produtos[code][3] # Adiciona o valor do iva ao total iva
print(f"{produtos[code][0]} {amount} {noIvaPrice * (1+produtos[code][3]):.2f}") print(f"{produtos[code][0]} {amount} {noIvaPrice * (1 + produtos[code][3]):.2f}")
userInput = input('Code? ') userInput = input('Code? ')
@ -64,7 +66,8 @@ def fatura(produtos, compra):
"""Imprime a fatura de uma dada compra.""" """Imprime a fatura de uma dada compra."""
# Obtém a lista de secções presentes na compra (por ordem alfabética) # Obtém a lista de secções presentes na compra (por ordem alfabética)
sections = sorted(list({section for section in [product[1] for code, product in produtos.items() if code in compra]})) sections = sorted(
list({section for section in [product[1] for code, product in produtos.items() if code in compra]}))
# Itera as secções para apresentar os produtos ordenados por secção # Itera as secções para apresentar os produtos ordenados por secção
for section in sections: for section in sections:
@ -75,7 +78,8 @@ def fatura(produtos, compra):
# Itera os códigos para apresentar as informações de cada produto # Itera os códigos para apresentar as informações de cada produto
for code in sectionProductsCodes: for code in sectionProductsCodes:
print(f"{compra[code]:>4} {produtos[code][0]:<31}({int(produtos[code][3]*100):>2}%){round(compra[code]*produtos[code][2]*(1+produtos[code][3]), 2):>11}") print(
f"{compra[code]:>4} {produtos[code][0]:<31}({int(produtos[code][3] * 100):>2}%){round(compra[code] * produtos[code][2] * (1 + produtos[code][3]), 2):>11}")
# Apresenta os totais da compra # Apresenta os totais da compra
print(f"""{'Total Bruto:':>41}{round(compra["totals"][0], 2):>11} print(f"""{'Total Bruto:':>41}{round(compra["totals"][0], 2):>11}
@ -102,7 +106,7 @@ def main(args):
# Processar opção # Processar opção
if op == "C": if op == "C":
# Esta opção regista os produtos de uma compra # Esta opção regista os produtos de uma compra
compras[len(compras)+1] = registaCompra(produtos) compras[len(compras) + 1] = registaCompra(produtos)
elif op == "F": elif op == "F":
# Esta opção apresenta a fatura de uma compra # Esta opção apresenta a fatura de uma compra
@ -120,5 +124,6 @@ def main(args):
# Não altere este código / Do not change this code # Não altere este código / Do not change this code
import sys import sys
if __name__ == "__main__": if __name__ == "__main__":
main(sys.argv[1:]) main(sys.argv[1:])

View File

@ -98,7 +98,9 @@ def fatura(calls: dict, phone_number: str) -> None:
def validate_phone_number(phone_number: str) -> bool: def validate_phone_number(phone_number: str) -> bool:
return phone_number.isdigit() and len(phone_number) >= 3 if phone_number[0] != "+" else phone_number[1:].isdigit() and len(phone_number[1:]) >= 3 return phone_number.isdigit() and len(phone_number) >= 3 if phone_number[0] != "+" else phone_number[
1:].isdigit() and len(
phone_number[1:]) >= 3
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -23,7 +23,7 @@ def get_user_input(journeys: dict, budget: int) -> None:
print('Jornada inválida') print('Jornada inválida')
match_id = 1 match_id = 1
true_bet_count = [0,0] true_bet_count = [0, 0]
with open(f'apostas_jornadas/jornada{journey_input}.csv', 'w') as f: with open(f'apostas_jornadas/jornada{journey_input}.csv', 'w') as f:
for match in journeys[journey_input]: for match in journeys[journey_input]:
while True: while True:
@ -32,12 +32,12 @@ def get_user_input(journeys: dict, budget: int) -> None:
f.write(f"{match_id},{bet}\n") f.write(f"{match_id},{bet}\n")
match_id += 1 match_id += 1
if len(bet) != 1: if len(bet) != 1:
true_bet_count[len(bet)-2] += 1 true_bet_count[len(bet) - 2] += 1
break break
else: else:
print('Aposta inválida') print('Aposta inválida')
budget -= 0.4 * (2**true_bet_count[0] * 3**true_bet_count[1]) budget -= 0.4 * (2 ** true_bet_count[0] * 3 ** true_bet_count[1])
print_results(journeys, int(journey_input), budget) print_results(journeys, int(journey_input), budget)
@ -56,7 +56,7 @@ def print_results(journeys: dict, journey: int, budget: int) -> None:
for game in games: for game in games:
game = game.strip().split(',') game = game.strip().split(',')
if game[1] == match[0] and game[2] == match[1]: if game[1] == match[0] and game[2] == match[1]:
bet = bets[str(journeys[str(journey)].index(match)+1)] bet = bets[str(journeys[str(journey)].index(match) + 1)]
result = 'CERTO' if ( result = 'CERTO' if (
('1' in bet and game[3] > game[4]) ('1' in bet and game[3] > game[4])
or ('X' in bet and game[3] == game[4]) or ('X' in bet and game[3] == game[4])
@ -74,7 +74,8 @@ def print_results(journeys: dict, journey: int, budget: int) -> None:
price = 1000 price = 1000
else: else:
price = 5000 price = 5000
print(f"TEM {right_bets_count} CERTAS. {'SEM PRÉMIO' if right_bets_count < 7 else ('3º PRÉMIO' if right_bets_count < 8 else ('2º PRÉMIO' if right_bets_count < 9 else '1º PRÉMIO'))}") print(
f"TEM {right_bets_count} CERTAS. {'SEM PRÉMIO' if right_bets_count < 7 else ('3º PRÉMIO' if right_bets_count < 8 else ('2º PRÉMIO' if right_bets_count < 9 else '1º PRÉMIO'))}")
budget += price budget += price
get_user_input(journeys, budget) get_user_input(journeys, budget)

View File

@ -23,7 +23,6 @@ print(twits[0]["text"])
# Algumas mensagens contêm hashtags: # Algumas mensagens contêm hashtags:
print(twits[880]["text"]) print(twits[880]["text"])
# A) # A)
word_count: dict[str, int] = {} word_count: dict[str, int] = {}
@ -38,21 +37,18 @@ word_list = list(word_count.keys())
print("A)\n" + str(word_list), end="\n\n") print("A)\n" + str(word_list), end="\n\n")
# B) # B)
ordered_list = sorted(word_list, key=lambda t: word_count[t], reverse=True) ordered_list = sorted(word_list, key=lambda t: word_count[t], reverse=True)
print("B)\n" + str(ordered_list), end="\n\n") print("B)\n" + str(ordered_list), end="\n\n")
# C) # C)
ordered_hashtag_list = [word for word in ordered_list if word.startswith('#')] ordered_hashtag_list = [word for word in ordered_list if word.startswith('#')]
print("C)\n" + str(ordered_hashtag_list), end="\n\n") print("C)\n" + str(ordered_hashtag_list), end="\n\n")
# D) # D)
print("D)\n") print("D)\n")
most_used = word_count[ordered_hashtag_list[0]] most_used = word_count[ordered_hashtag_list[0]]
for hashtag in ordered_hashtag_list: for hashtag in ordered_hashtag_list:
print(f"{hashtag:<30} ({word_count[hashtag]:>2}) {'+' * ((word_count[hashtag]*18)//most_used)}") print(f"{hashtag:<30} ({word_count[hashtag]:>2}) {'+' * ((word_count[hashtag] * 18) // most_used)}")

View File

@ -1,4 +1,3 @@
# On a chessboard, positions are marked with letters between a and h for the column and a # On a chessboard, positions are marked with letters between a and h for the column and a
# number between 1 and 8 for the row. The first place on the board, a1, is black. The next # number between 1 and 8 for the row. The first place on the board, a1, is black. The next
# is white, alternating across a row. Odd rows start with black, even rows start with white. # is white, alternating across a row. Odd rows start with black, even rows start with white.

View File

@ -6,7 +6,7 @@
def firstEqualLast(lst): def firstEqualLast(lst):
n = 0 n = 0
for i in range(1, len(lst)//2+1): for i in range(1, len(lst) // 2 + 1):
if lst[:i] == lst[-i:]: if lst[:i] == lst[-i:]:
n = i n = i
return n return n

View File

@ -1,4 +1,3 @@
# Given a string s and a string t, return a string in which all the characters # Given a string s and a string t, return a string in which all the characters
# of s that occur in t have been replaced by a _ sign. The comparisons are # of s that occur in t have been replaced by a _ sign. The comparisons are
# case sensitive. # case sensitive.

View File

@ -1,4 +1,3 @@
# Given a string s, return the longest prefix that is repeated somewhere else in the string. # Given a string s, return the longest prefix that is repeated somewhere else in the string.
# For example, "abcdabejf" would return "ab" as "ab" starts at the beginning of the string # For example, "abcdabejf" would return "ab" as "ab" starts at the beginning of the string
# and is repeated again later. Do not use the find method. # and is repeated again later. Do not use the find method.
@ -7,7 +6,7 @@ def longestPrefixRepeated(s):
# Your code here... # Your code here...
longest = "" longest = ""
for i in range(1, len(s)//2+1): for i in range(1, len(s) // 2 + 1):
if s[:i] in s[i:]: if s[:i] in s[i:]:
longest = s[:i] longest = s[:i]

View File

@ -1,3 +1,4 @@
def printStocks(stocks): def printStocks(stocks):
for stock in stocks: for stock in stocks:
print(f"{stock[0]:<10}{stock[1]:<19}{stock[2]:>6.2f}{stock[3]:>10.2f}{stock[4]:>10}{(stock[3]/stock[2]-1)*100:>7.1f}%") print(
f"{stock[0]:<10}{stock[1]:<19}{stock[2]:>6.2f}{stock[3]:>10.2f}{stock[4]:>10}{(stock[3] / stock[2] - 1) * 100:>7.1f}%")

View File

@ -3,5 +3,6 @@ def load(fname):
with open(fname, 'r') as f: with open(fname, 'r') as f:
for stock in f: for stock in f:
components = stock[:-1].split('\t') components = stock[:-1].split('\t')
stocks_list.append((components[0], components[1], float(components[2]), float(components[3]), int(components[4]))) stocks_list.append(
(components[0], components[1], float(components[2]), float(components[3]), int(components[4])))
return stocks_list return stocks_list

View File

@ -14,6 +14,7 @@ Se não, deve devolver a quantidade que não conseguiu descarregar.
""" """
# Se w=['coal', 45], então w[0]='coal' e w[1]=45. # Se w=['coal', 45], então w[0]='coal' e w[1]=45.
def unload(t, m, q): def unload(t, m, q):

View File

@ -4,7 +4,7 @@ Por exemplo, onlyCaps("John Fitzgerald Kennedy") deve devolver "JFK".
A solução tem de ser recursiva e não pode usar ciclos. A solução tem de ser recursiva e não pode usar ciclos.
""" """
def onlyCaps(s): def onlyCaps(s):
# NOTE: ch.isupper() -> True if ch is uppercase. # NOTE: ch.isupper() -> True if ch is uppercase.
return "" if len(s) == 0 else (s[0] + onlyCaps(s[1:]) if s[0].isupper() else onlyCaps(s[1:])) return "" if len(s) == 0 else (s[0] + onlyCaps(s[1:]) if s[0].isupper() else onlyCaps(s[1:]))