diff --git a/1ano/1semestre/fp/aula00/retangulo.py b/1ano/1semestre/fp/aula00/retangulo.py index 53164cc..c104d69 100644 --- a/1ano/1semestre/fp/aula00/retangulo.py +++ b/1ano/1semestre/fp/aula00/retangulo.py @@ -2,7 +2,7 @@ largura = float(input("Largura? ")) altura = float(input("Altura? ")) area = largura * altura -perimetro = largura*2 + altura*2 +perimetro = largura * 2 + altura * 2 print("Area:", area) print("Perimetro:", perimetro) diff --git a/1ano/1semestre/fp/aula00/welcome.py b/1ano/1semestre/fp/aula00/welcome.py index de7f7d8..7f2906d 100644 --- a/1ano/1semestre/fp/aula00/welcome.py +++ b/1ano/1semestre/fp/aula00/welcome.py @@ -9,4 +9,3 @@ surname = input("Apelido? ") course = input("Curso? ") print("Olá {} {}!\nBem vindo ao curso de {}!".format(name, surname, course)) - diff --git a/1ano/1semestre/fp/aula01/ex01.py b/1ano/1semestre/fp/aula01/ex01.py index 77c1963..51788b8 100755 --- a/1ano/1semestre/fp/aula01/ex01.py +++ b/1ano/1semestre/fp/aula01/ex01.py @@ -2,4 +2,4 @@ nome = input('Como te chamas? ') anoNascenca = int(input('Em que ano nasceste? ')) ano = int(input('Ano para verificar: ')) -print(f'{nome}, em {ano} farás {ano - anoNascenca} anos.') \ No newline at end of file +print(f'{nome}, em {ano} farás {ano - anoNascenca} anos.') diff --git a/1ano/1semestre/fp/aula01/ex02.py b/1ano/1semestre/fp/aula01/ex02.py index 809617c..d49fa4c 100755 --- a/1ano/1semestre/fp/aula01/ex02.py +++ b/1ano/1semestre/fp/aula01/ex02.py @@ -2,4 +2,4 @@ celcius = float(input('°C: ')) fahrenheit = 1.8 * celcius + 32 -print(f'\n{celcius} °C = {fahrenheit} °F') \ No newline at end of file +print(f'\n{celcius} °C = {fahrenheit} °F') diff --git a/1ano/1semestre/fp/aula01/ex03.py b/1ano/1semestre/fp/aula01/ex03.py index 9e90771..6ca2997 100755 --- a/1ano/1semestre/fp/aula01/ex03.py +++ b/1ano/1semestre/fp/aula01/ex03.py @@ -3,4 +3,4 @@ v2 = float(input('Velocidade de regresso (v2): ')) vm = (2 * v1 * v2) / (v1 + v2) -print('\nA velocidade média da viagem completa foi: ', vm) \ No newline at end of file +print('\nA velocidade média da viagem completa foi: ', vm) diff --git a/1ano/1semestre/fp/aula01/ex04.py b/1ano/1semestre/fp/aula01/ex04.py index 56286cb..9ec51ec 100755 --- a/1ano/1semestre/fp/aula01/ex04.py +++ b/1ano/1semestre/fp/aula01/ex04.py @@ -4,5 +4,4 @@ mins = secs // 60 m = mins % 60 h = mins // 60 - -print("{:02d}:{:02d}:{:02d}".format(h, m, s)) \ No newline at end of file +print("{:02d}:{:02d}:{:02d}".format(h, m, s)) diff --git a/1ano/1semestre/fp/aula01/ex05.py b/1ano/1semestre/fp/aula01/ex05.py index e6d3f0b..b23584d 100755 --- a/1ano/1semestre/fp/aula01/ex05.py +++ b/1ano/1semestre/fp/aula01/ex05.py @@ -1,13 +1,13 @@ from math import * - A = float(input('Comprimento do cateto A: ')) B = float(input('Comprimento do cateto B: ')) -C = sqrt(A**2 + B**2) +C = sqrt(A ** 2 + B ** 2) cosseno = A / C angRad = acos(cosseno) 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)}°') \ No newline at end of file +print( + f'O comprimento da hipotenusa é {round(C, 2)} e o valor do angulo entre o cateto A e a hipotenusa é {round(angDeg, 2)}°') diff --git a/1ano/1semestre/fp/aula01/ex06.py b/1ano/1semestre/fp/aula01/ex06.py index 3087c5a..3c001f4 100755 --- a/1ano/1semestre/fp/aula01/ex06.py +++ b/1ano/1semestre/fp/aula01/ex06.py @@ -1,6 +1,5 @@ from math import sqrt - x1, y1 = input("Introduza x1 e y1, 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) 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) \ No newline at end of file +print('A distancia entre os dois pontos é: ', distancia) diff --git a/1ano/1semestre/fp/aula01/ex07.py b/1ano/1semestre/fp/aula01/ex07.py index f9aa729..13afe26 100755 --- a/1ano/1semestre/fp/aula01/ex07.py +++ b/1ano/1semestre/fp/aula01/ex07.py @@ -1,7 +1,7 @@ A = 3 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 mAno = viagensAno * 3 diff --git a/1ano/1semestre/fp/aula02/age.py b/1ano/1semestre/fp/aula02/age.py index b5b4375..f43cbfe 100755 --- a/1ano/1semestre/fp/aula02/age.py +++ b/1ano/1semestre/fp/aula02/age.py @@ -1,4 +1,3 @@ - # A teenager is a person between 13 and 19 years old, inclusive. # A child is under 13. A grown-up is 20 or more. # This program outputs the age category for a given input age. @@ -11,15 +10,15 @@ age = int(input("Age? ")) if age < 0: print("ERROR: invalid age!") - exit(1) # this terminates the program + exit(1) # this terminates the program print("Age:", age) -if age < 13 : +if age < 13: cat = "child" -elif 13 < age < 20: +elif age < 20: cat = "teenager" else: cat = "grown-up" -print("Category: ", cat) \ No newline at end of file +print("Category: ", cat) diff --git a/1ano/1semestre/fp/aula02/darts.py b/1ano/1semestre/fp/aula02/darts.py index 4b941ef..b95d0b8 100755 --- a/1ano/1semestre/fp/aula02/darts.py +++ b/1ano/1semestre/fp/aula02/darts.py @@ -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) -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: ')) y = int(input('Y: ')) @@ -19,7 +20,6 @@ elif mod < 32: print('Pontuacao: 25 pontos.') exit(1) - angleRad = math.atan2(y, x) angleDeg = math.degrees(angleRad) - 9 score = POINTS[int(angleDeg / 20)] diff --git a/1ano/1semestre/fp/aula02/ex02_03.py b/1ano/1semestre/fp/aula02/ex02_03.py index 66be19a..04ae97c 100755 --- a/1ano/1semestre/fp/aula02/ex02_03.py +++ b/1ano/1semestre/fp/aula02/ex02_03.py @@ -11,4 +11,4 @@ if x2 > mx: if x3 > mx: mx = x3 -print("Maximum: ", mx) \ No newline at end of file +print("Maximum: ", mx) diff --git a/1ano/1semestre/fp/aula02/ex05.py b/1ano/1semestre/fp/aula02/ex05.py index 54c934a..f21e0de 100755 --- a/1ano/1semestre/fp/aula02/ex05.py +++ b/1ano/1semestre/fp/aula02/ex05.py @@ -7,4 +7,4 @@ if duracao < 60: else: custo = duracao * tarifario_sec -print('Custo: ', custo) \ No newline at end of file +print('Custo: ', custo) diff --git a/1ano/1semestre/fp/aula02/ex09.py b/1ano/1semestre/fp/aula02/ex09.py index 658122a..f1eb875 100755 --- a/1ano/1semestre/fp/aula02/ex09.py +++ b/1ano/1semestre/fp/aula02/ex09.py @@ -1,7 +1,6 @@ CTP = float(input('Componente Teorica-pratica: ')) CP = float(input('Componente Pratica: ')) - NF = round(0.3 * CTP + 0.7 * CP) if (CTP < 6.6) or (CP < 6.6): @@ -16,4 +15,4 @@ NF = round(0.3 * ATPR + 0.7 * ATP) if NF >= 10: print('Aprovado com nota ', NF) else: - print('Continua reprovado, nota ', NF) \ No newline at end of file + print('Continua reprovado, nota ', NF) diff --git a/1ano/1semestre/fp/aula02/imc.py b/1ano/1semestre/fp/aula02/imc.py index 3a11fd0..ea9cd88 100755 --- a/1ano/1semestre/fp/aula02/imc.py +++ b/1ano/1semestre/fp/aula02/imc.py @@ -9,7 +9,7 @@ print("Índice de Massa Corporal") altura = float(input("Altura (m)? ")) peso = float(input("Peso (kg)? ")) -imc = peso / altura**2 +imc = peso / altura ** 2 print("IMC:", imc, "kg/m2") @@ -23,4 +23,4 @@ elif imc < 30: else: categoria = "Obeso" -print("Categoria:", categoria) \ No newline at end of file +print("Categoria:", categoria) diff --git a/1ano/1semestre/fp/aula03/bmi.py b/1ano/1semestre/fp/aula03/bmi.py index 25b3492..7fc6e83 100755 --- a/1ano/1semestre/fp/aula03/bmi.py +++ b/1ano/1semestre/fp/aula03/bmi.py @@ -2,7 +2,7 @@ # given the height (in meter) and weight (in kg) of a person. def bodyMassIndex(height, weight): # Complete the function definition... - bmi = weight / height**2 + bmi = weight / height ** 2 return bmi @@ -10,7 +10,7 @@ def bodyMassIndex(height, weight): # BMI: <18.5 [18.5, 25[ [25, 30[ 30 or greater # Category: Underweight Normal weight Overweight Obesity def bmiCategory(bmi): - assert bmi>0 + assert bmi > 0 # Complete the function definition... if bmi < 18.5: return 'Underweight' @@ -25,7 +25,7 @@ def bmiCategory(bmi): # This is the main function def main(): print("Índice de Massa Corporal") - + altura = float(input("Altura (m)? ")) if altura < 0: print("ERRO: altura inválida!") @@ -46,4 +46,4 @@ def main(): # Program starts executing here if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/1ano/1semestre/fp/aula03/dates.py b/1ano/1semestre/fp/aula03/dates.py index 9b72649..e08e43d 100755 --- a/1ano/1semestre/fp/aula03/dates.py +++ b/1ano/1semestre/fp/aula03/dates.py @@ -1,26 +1,28 @@ def isLeapYear(year): return year % 400 == 0 if year % 100 == 0 else year % 4 == 0 + def monthDays(year, month): assert month > 0 - + MONTHDAYS = (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) days = MONTHDAYS[month] - + 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 if (month, day) == (12, 31): year += 1 month = 1 day = 1 - + # Verifica se é o último dia do mês elif (monthDays(year, month) == day): month += 1 day = 1 - + # Dia comum else: day += 1 @@ -30,28 +32,29 @@ def nextDay(year, month, day): # This is the main function def main(): - print("Was", 2017, "a leap year?", isLeapYear(2017)) # False? - print("Was", 2016, "a leap year?", isLeapYear(2016)) # True? - print("Was", 2000, "a leap year?", isLeapYear(2000)) # True? - print("Was", 1900, "a leap year?", isLeapYear(1900)) # False? - - print("January 2017 had", monthDays(2017, 1), "days") # 31? + print("Was", 2017, "a leap year?", isLeapYear(2017)) # False? + print("Was", 2016, "a leap year?", isLeapYear(2016)) # True? + print("Was", 2000, "a leap year?", isLeapYear(2000)) # True? + print("Was", 1900, "a leap year?", isLeapYear(1900)) # False? + + print("January 2017 had", monthDays(2017, 1), "days") # 31? print("February 2017 had", monthDays(2017, 2), "days") # 28? print("February 2016 had", monthDays(2016, 2), "days") # 29? print("February 2000 had", monthDays(2000, 2), "days") # 29? print("February 1900 had", monthDays(1900, 2), "days") # 28? - + y, m, d = nextDay(2017, 1, 30) - print(y, m, d) # 2017 1 31 ? + print(y, m, d) # 2017 1 31 ? y, m, d = nextDay(2017, 1, 31) - print(y, m, d) # 2017 2 1 ? + print(y, m, d) # 2017 2 1 ? y, m, d = nextDay(2017, 2, 28) - print(y, m, d) # 2017 3 1 ? + print(y, m, d) # 2017 3 1 ? y, m, d = nextDay(2016, 2, 29) - print(y, m, d) # 2016 3 1 ? + print(y, m, d) # 2016 3 1 ? 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 if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/1ano/1semestre/fp/aula03/ex05_06.py b/1ano/1semestre/fp/aula03/ex05_06.py index 0d9ffc4..29d725c 100755 --- a/1ano/1semestre/fp/aula03/ex05_06.py +++ b/1ano/1semestre/fp/aula03/ex05_06.py @@ -4,9 +4,11 @@ def max2(x, y): else: return y + def max3(x, y, z): return max2(x, max2(y, z)) + def main(): n1 = float(input('Introduza dois valores.\nN1: ')) n2 = float(input('N2: ')) @@ -21,4 +23,4 @@ def main(): if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/1ano/1semestre/fp/aula03/ex07.py b/1ano/1semestre/fp/aula03/ex07.py index f138ac0..10c5fa7 100755 --- a/1ano/1semestre/fp/aula03/ex07.py +++ b/1ano/1semestre/fp/aula03/ex07.py @@ -5,5 +5,6 @@ def tax(r): return 0.2 * r - 100 return 0.3 * r - 300 + x = float(input('R? ')) -print('O valor de tax(r) é: {:.3f}'.format(tax(x))) \ No newline at end of file +print('O valor de tax(r) é: {:.3f}'.format(tax(x))) diff --git a/1ano/1semestre/fp/aula03/ex08.py b/1ano/1semestre/fp/aula03/ex08.py index 34b1006..9ec5bec 100755 --- a/1ano/1semestre/fp/aula03/ex08.py +++ b/1ano/1semestre/fp/aula03/ex08.py @@ -1,15 +1,18 @@ def intersects(a1, b1, a2, b2): - assert a1 < b1 - assert a2 < b2 + assert a1 <= b1 and a2 <= b2, "Os intervalos não são válidos." + return a1 <= b2 and a2 <= b1 - if a1 < b2 and a2 < b1: - return True - else: - return False -a1 = float(input("a1: ")) -b1 = float(input("b1: ")) -a2 = float(input("a2: ")) -b2 = float(input("b2: ")) +def main(): + a1 = float(input("a1: ")) + b1 = float(input("b1: ")) + a2 = float(input("a2: ")) + b2 = float(input("b2: ")) -print(intersects(a1, b1, a2, b2)) \ No newline at end of file + try: + print(intersects(a1, b1, a2, b2)) + except AssertionError as e: + print(e) + + +main() diff --git a/1ano/1semestre/fp/aula03/ex12.py b/1ano/1semestre/fp/aula03/ex12.py index 58f6bfa..fb3d90b 100755 --- a/1ano/1semestre/fp/aula03/ex12.py +++ b/1ano/1semestre/fp/aula03/ex12.py @@ -11,5 +11,6 @@ def countdown(n): yield n n -= 1 + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/1ano/1semestre/fp/aula03/ex13.py b/1ano/1semestre/fp/aula03/ex13.py index 371ad6c..0e6ad6c 100755 --- a/1ano/1semestre/fp/aula03/ex13.py +++ b/1ano/1semestre/fp/aula03/ex13.py @@ -7,11 +7,13 @@ def mdc(a, b): else: return mdc(b, r) + def main(): print('Este programa calcula o máximo divisor comum de dois námeros naturais') n1 = int(input('Numero 1: ')) n2 = int(input('Numero 2: ')) print(f'\nO Máximo Divisor Comum de {n1} e {n2} é: {mdc(n1, n2)}') + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/1ano/1semestre/fp/aula03/poly.py b/1ano/1semestre/fp/aula03/poly.py index f2af98a..5168b81 100755 --- a/1ano/1semestre/fp/aula03/poly.py +++ b/1ano/1semestre/fp/aula03/poly.py @@ -1,11 +1,11 @@ # Esta função implementa g(x) = 8 - x**3 def g(x): - return 8 - x**3 + return 8 - x ** 3 # Defina uma função que implemente p(x) = x**2 + 2x + 3 def p(x): - return x**2 + 2*x + 3 + return x ** 2 + 2 * x + 3 def main(): diff --git a/1ano/1semestre/fp/aula04/divs-cate.py b/1ano/1semestre/fp/aula04/divs-cate.py index e8a164c..6e58b48 100755 --- a/1ano/1semestre/fp/aula04/divs-cate.py +++ b/1ano/1semestre/fp/aula04/divs-cate.py @@ -4,7 +4,7 @@ def main(): div_list_array = divList(n) div_list = ", ".join(div_list_array) - + print(f""" -------------------- @@ -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 def divList(n): divs = [] @@ -28,6 +29,7 @@ def divList(n): divs.append(str(x)) return divs + # Obtém a categoria de um número def category(n, divs): total = 0 @@ -35,7 +37,8 @@ def category(n, divs): total += int(div) if total < n: return 'deficiente' if total == n: return 'perfeito' - if total > n: return 'abundante' + if total > n: return 'abundante' + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/1ano/1semestre/fp/aula04/factorial.py b/1ano/1semestre/fp/aula04/factorial.py index 1173189..020443a 100755 --- a/1ano/1semestre/fp/aula04/factorial.py +++ b/1ano/1semestre/fp/aula04/factorial.py @@ -4,9 +4,11 @@ def factorial(n): total *= x return total + def main(): n = int(input('Introduza um número: ')) print('O fatorial de {} é: {}'.format(n, factorial(n))) + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/1ano/1semestre/fp/aula04/fibonacci.py b/1ano/1semestre/fp/aula04/fibonacci.py index 4882725..ca410e0 100755 --- a/1ano/1semestre/fp/aula04/fibonacci.py +++ b/1ano/1semestre/fp/aula04/fibonacci.py @@ -1,11 +1,13 @@ def fibonacci(n): if n == 0: return 0 if n == 1: return 1 - return fibonacci(n-1) + fibonacci(n-2) + return fibonacci(n - 1) + fibonacci(n - 2) + def main(): n = int(input('Introduza um número: ')) print(f'O {n}º número de Fibonacci é: {fibonacci(n)}') + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/1ano/1semestre/fp/aula04/hilo.py b/1ano/1semestre/fp/aula04/hilo.py index c8b118a..fb6fbe4 100755 --- a/1ano/1semestre/fp/aula04/hilo.py +++ b/1ano/1semestre/fp/aula04/hilo.py @@ -2,6 +2,7 @@ import random + def main(): # Pick a random number between 1 and 100, inclusive secret = random.randrange(1, 101) @@ -19,7 +20,9 @@ def main(): c += 1 trieslist.append(str(num)) 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__": main() diff --git a/1ano/1semestre/fp/aula04/leibnizPi4.py b/1ano/1semestre/fp/aula04/leibnizPi4.py index c4e036e..d842858 100755 --- a/1ano/1semestre/fp/aula04/leibnizPi4.py +++ b/1ano/1semestre/fp/aula04/leibnizPi4.py @@ -3,8 +3,8 @@ import math def leibnizPi4(n): total = 0 - for x in range(1, n+1): - increment = 1/(x*2-1) + for x in range(1, n + 1): + increment = 1 / (x * 2 - 1) total += -increment if x % 2 == 0 else increment return total @@ -13,7 +13,7 @@ def main(): num = int(input('Introduza o número de termos: ')) print(f""" Resultado da série de Leibniz: {leibnizPi4(num)} -Valor do PI/4: {math.pi/4} +Valor do PI/4: {math.pi / 4} """) diff --git a/1ano/1semestre/fp/aula04/media.py b/1ano/1semestre/fp/aula04/media.py index 6af9476..a1feaec 100755 --- a/1ano/1semestre/fp/aula04/media.py +++ b/1ano/1semestre/fp/aula04/media.py @@ -10,14 +10,17 @@ def GetValues(): count += 1 return values + # Calcula a média dos valores da lista 'values' def GetMedia(val): return sum(val) / len(val) + # Função principal def main(): values = GetValues() print('Média dos valores introduzidos: ', GetMedia(values)) + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/1ano/1semestre/fp/aula04/sequenceUn.py b/1ano/1semestre/fp/aula04/sequenceUn.py index 23908ef..3d6af38 100755 --- a/1ano/1semestre/fp/aula04/sequenceUn.py +++ b/1ano/1semestre/fp/aula04/sequenceUn.py @@ -1,9 +1,9 @@ # This program generates 20 terms of a sequence by a recurrence relation. -Un = 100 # Un = each term of the sequence. Initially = U0 +Un = 100 # Un = each term of the sequence. Initially = U0 count = 0 while Un > 0: 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 print('O programa mostrou ', count, ' termos') diff --git a/1ano/1semestre/fp/aula04/table.py b/1ano/1semestre/fp/aula04/table.py index a92f6e7..ac0715f 100755 --- a/1ano/1semestre/fp/aula04/table.py +++ b/1ano/1semestre/fp/aula04/table.py @@ -1,7 +1,7 @@ # Show a table of the squares of the first four numbers print(" {:1s} | {:>3s} | {:>7s}".format("n", "n²", "2**n")) 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.) # Also, add a column to show 2**n. Adjust the formatting. diff --git a/1ano/1semestre/fp/aula04/tp-codecheck/ex01.py b/1ano/1semestre/fp/aula04/tp-codecheck/ex01.py index db76789..9774694 100755 --- a/1ano/1semestre/fp/aula04/tp-codecheck/ex01.py +++ b/1ano/1semestre/fp/aula04/tp-codecheck/ex01.py @@ -2,39 +2,40 @@ # JMR 2019 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): - """Print all leap years in range [year1, year2[.""" - for year in listLeapYears(year1, year2): - print(year) + """Print all leap years in range [year1, year2[.""" + for year in listLeapYears(year1, year2): + print(year) def numLeapYears(year1, year2): - """Return the number of leap years in range [year1, year2[.""" - return len(listLeapYears(year1, year2)) + """Return the number of leap years in range [year1, year2[.""" + return len(listLeapYears(year1, year2)) def listLeapYears(year1, year2): - """Return a list of leap years in range [year1, year2[.""" - # (We'll get back to lists later in the course.) - lst = [] - for year in range(year1, year2): - if isLeapYear(year): - lst.append(year) - - return lst + """Return a list of leap years in range [year1, year2[.""" + # (We'll get back to lists later in the course.) + lst = [] + for year in range(year1, year2): + if isLeapYear(year): + lst.append(year) + + return lst # MAIN PROGRAM: def main(): - printLeapYears(1870, 1921) + printLeapYears(1870, 1921) - x = numLeapYears(1679, 2079) - print("In [1679, 2079[ there are", x, "leap years") + x = numLeapYears(1679, 2079) + print("In [1679, 2079[ there are", x, "leap years") - print(listLeapYears(1970, 2002)) + print(listLeapYears(1970, 2002)) if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/1ano/1semestre/fp/aula04/tp-codecheck/ex02.py b/1ano/1semestre/fp/aula04/tp-codecheck/ex02.py index 7433812..eca37fd 100755 --- a/1ano/1semestre/fp/aula04/tp-codecheck/ex02.py +++ b/1ano/1semestre/fp/aula04/tp-codecheck/ex02.py @@ -3,17 +3,19 @@ def inputTotal(): - """Read numbers until empty string is entered and return the sum.""" - tot = 0.0 - while True: - n = input("valor? ") # input("valor? ") - if n == '': return tot - tot += float(n) + """Read numbers until empty string is entered and return the sum.""" + tot = 0.0 + while True: + n = input("valor? ") # input("valor? ") + if n == '': return tot + tot += float(n) + # MAIN PROGRAM def main(): - tot = inputTotal() - print(tot) + tot = inputTotal() + print(tot) + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/1ano/1semestre/fp/aula04/tp-codecheck/ex03.py b/1ano/1semestre/fp/aula04/tp-codecheck/ex03.py index 01f63a4..5f51893 100755 --- a/1ano/1semestre/fp/aula04/tp-codecheck/ex03.py +++ b/1ano/1semestre/fp/aula04/tp-codecheck/ex03.py @@ -11,13 +11,15 @@ # JMR 2019 def main(): - for i in range (1, 11): - table(i) - print() + for i in range(1, 11): + table(i) + print() + def table(n): - for i in range(1, 11): - print(f'{n} x {i} = {n*i}') + for i in range(1, 11): + print(f'{n} x {i} = {n * i}') + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/1ano/1semestre/fp/aula04/turtle1.py b/1ano/1semestre/fp/aula04/turtle1.py index c4594ad..68b770c 100755 --- a/1ano/1semestre/fp/aula04/turtle1.py +++ b/1ano/1semestre/fp/aula04/turtle1.py @@ -4,7 +4,8 @@ # For a summary of the available methods: # https://runestone.academy/runestone/books/published/thinkcspy/PythonTurtle/SummaryofTurtleMethods.html -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 def square(t, side): @@ -12,6 +13,7 @@ def square(t, side): t.forward(side) t.left(90) + # Make turtle t draw a spiral. # The first side should have length = start, the second start+incr, etc., # until the length reaches length=end (exclusive). @@ -26,24 +28,24 @@ def spiral(t, start, end, incr): t.forward(start) t.left(90) start += incr - + def main(): print("This program opens a window with a graphical user interface.") - wn = turtle.Screen() # creates a graphics window - alex = turtle.Turtle() # create a turtle named alex + wn = turtle.Screen() # creates a graphics window + alex = turtle.Turtle() # create a turtle named alex - alex.forward(150) # tell alex to move forward by 150 units - alex.right(90) # turn by 90 degrees - alex.forward(75) # complete the second side + alex.forward(150) # tell alex to move forward by 150 units + alex.right(90) # turn by 90 degrees + alex.forward(75) # complete the second side - beth = turtle.Turtle() # another turtle - beth.shape("turtle") # with another shape - beth.color("blue") # and color - beth.up() # pen up - beth.goto(-200, -100) # move to given point - beth.down() # pen down - square(beth, 100) # draw a square + beth = turtle.Turtle() # another turtle + beth.shape("turtle") # with another shape + beth.color("blue") # and color + beth.up() # pen up + beth.goto(-200, -100) # move to given point + beth.down() # pen down + square(beth, 100) # draw a square # This should draw a spiral alex.up() @@ -57,7 +59,7 @@ def main(): alex.down() spiral(alex, 200, 0, -5) - turtle.exitonclick() # wait for a button click, then close window + turtle.exitonclick() # wait for a button click, then close window print("The window was closed. Bye!") diff --git a/1ano/1semestre/fp/aula05/allMatches.py b/1ano/1semestre/fp/aula05/allMatches.py index efc3dbf..730f6d0 100755 --- a/1ano/1semestre/fp/aula05/allMatches.py +++ b/1ano/1semestre/fp/aula05/allMatches.py @@ -16,4 +16,4 @@ def allMatches(teamList): if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/1ano/1semestre/fp/aula05/ex08.py b/1ano/1semestre/fp/aula05/ex08.py index 46de941..7605d1e 100755 --- a/1ano/1semestre/fp/aula05/ex08.py +++ b/1ano/1semestre/fp/aula05/ex08.py @@ -19,14 +19,14 @@ def evenThenOdd(string): def removeAdjacentDuplicates(s): new = '' 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] return new def reapeatNumTimes(n): lst = [] - for i in range(1, n+1): + for i in range(1, n + 1): lst += [i] * i return lst diff --git a/1ano/1semestre/fp/aula05/ispalindrome.py b/1ano/1semestre/fp/aula05/ispalindrome.py index f31e668..66202c1 100755 --- a/1ano/1semestre/fp/aula05/ispalindrome.py +++ b/1ano/1semestre/fp/aula05/ispalindrome.py @@ -2,11 +2,11 @@ def main(): s = input('Introduza uma string >> ') print(ispalindrome(s)) - + def ispalindrome(s): pal_s = s[::-1] return pal_s == s - + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/1ano/1semestre/fp/aula05/shorten.py b/1ano/1semestre/fp/aula05/shorten.py index d976232..4d2c969 100755 --- a/1ano/1semestre/fp/aula05/shorten.py +++ b/1ano/1semestre/fp/aula05/shorten.py @@ -4,11 +4,8 @@ def main(): def shorten(string): - abv = '' - for char in string: - if char.isupper(): - abv += char - return abv - + return ''.join([char for char in string if char.isupper()]) + + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/1ano/1semestre/fp/aula05/telephones.py b/1ano/1semestre/fp/aula05/telephones.py index 5239a01..b21c9c0 100755 --- a/1ano/1semestre/fp/aula05/telephones.py +++ b/1ano/1semestre/fp/aula05/telephones.py @@ -19,22 +19,23 @@ def nameToTels(partName, telList, nameList): tels.append(telList[index]) return tels + def main(): # Lists of telephone numbers and names telList = ['975318642', '234000111', '777888333', '911911911'] - nameList = ['Angelina', 'Brad', 'Claudia', 'Bruna'] + nameList = ['Angelina', 'Brad', 'Claudia', 'Bruna'] # Test telToName: tel = input("Tel number? ") - print( telToName(tel, telList, nameList) ) - print( telToName('234000111', telList, nameList) == "Brad" ) - print( telToName('222333444', telList, nameList) == "222333444" ) + print(telToName(tel, telList, nameList)) + print(telToName('234000111', telList, nameList) == "Brad") + print(telToName('222333444', telList, nameList) == "222333444") # Test nameToTels: name = input("Name? ") - print( nameToTels(name, telList, nameList) ) - print( nameToTels('Clau', telList, nameList) == ['777888333'] ) - print( nameToTels('Br', telList, nameList) == ['234000111', '911911911'] ) + print(nameToTels(name, telList, nameList)) + print(nameToTels('Clau', telList, nameList) == ['777888333']) + print(nameToTels('Br', telList, nameList) == ['234000111', '911911911']) if __name__ == "__main__": diff --git a/1ano/1semestre/fp/aula05/tp05-codecheck/exercises01/ex01.py b/1ano/1semestre/fp/aula05/tp05-codecheck/exercises01/ex01.py index 532a410..d77319e 100755 --- a/1ano/1semestre/fp/aula05/tp05-codecheck/exercises01/ex01.py +++ b/1ano/1semestre/fp/aula05/tp05-codecheck/exercises01/ex01.py @@ -15,7 +15,6 @@ print(len(train)) # Qual o total de passageiros? print(sum(train)) - # Os dias da semana: week = ['sab', 'dom', 'seg', 'ter', 'qua', 'qui', 'sex'] @@ -25,4 +24,4 @@ print(week[2:]) # E para obter os dias úteis de dois em dois ['seg', 'qua', 'sex']? print(week[2::2]) -# JMR@ua.pt 2021 \ No newline at end of file +# JMR@ua.pt 2021 diff --git a/1ano/1semestre/fp/aula05/tp05-codecheck/exercises01/ex02.py b/1ano/1semestre/fp/aula05/tp05-codecheck/exercises01/ex02.py index d17d940..829fea7 100755 --- a/1ano/1semestre/fp/aula05/tp05-codecheck/exercises01/ex02.py +++ b/1ano/1semestre/fp/aula05/tp05-codecheck/exercises01/ex02.py @@ -20,4 +20,4 @@ train2 = [4, 6, 5] train += train2 print(train) -# JMR@ua.pt \ No newline at end of file +# JMR@ua.pt diff --git a/1ano/1semestre/fp/aula05/tp05-codecheck/exercises02/ex01.py b/1ano/1semestre/fp/aula05/tp05-codecheck/exercises02/ex01.py index 26522ff..273ffce 100755 --- a/1ano/1semestre/fp/aula05/tp05-codecheck/exercises02/ex01.py +++ b/1ano/1semestre/fp/aula05/tp05-codecheck/exercises02/ex01.py @@ -15,18 +15,20 @@ def passengers(train, n): num2 = sum(class2) return [num1, num2] + def test(): train1 = [12, 32, 10, 21] train2 = [9, 29, 19] train3 = [14, 34, 24] print(train1, train2, train3) - + print('\nTesting passengers') print(passengers(train1, 2)) print(passengers(train2, 1)) print(passengers(train3, 0)) - + + # Run tests: test() -# JMR@ua.pt 2021 \ No newline at end of file +# JMR@ua.pt 2021 diff --git a/1ano/1semestre/fp/aula05/tp05-codecheck/exercises02/ex02.py b/1ano/1semestre/fp/aula05/tp05-codecheck/exercises02/ex02.py index 32c6fdb..a24733b 100755 --- a/1ano/1semestre/fp/aula05/tp05-codecheck/exercises02/ex02.py +++ b/1ano/1semestre/fp/aula05/tp05-codecheck/exercises02/ex02.py @@ -6,13 +6,14 @@ def transfer1car(t1, t2): t2.append(t1[-1]) t1.remove(t1[-1]) - + + def test(): train1 = [12, 32, 10, 21] train2 = [9, 29, 19] train3 = [14, 34, 24] print(train1, train2, train3) - + print("\nTesting transfer1car") transfer1car(train1, train2) print(train1, train2, train3) @@ -20,8 +21,9 @@ def test(): print(train1, train2, train3) transfer1car(train3, train1) print(train1, train2, train3) - + + # Run tests: test() -# JMR@ua.pt 2021 \ No newline at end of file +# JMR@ua.pt 2021 diff --git a/1ano/1semestre/fp/aula05/tp05-codecheck/exercises02/ex03.py b/1ano/1semestre/fp/aula05/tp05-codecheck/exercises02/ex03.py index d419533..6c57911 100755 --- a/1ano/1semestre/fp/aula05/tp05-codecheck/exercises02/ex03.py +++ b/1ano/1semestre/fp/aula05/tp05-codecheck/exercises02/ex03.py @@ -17,13 +17,14 @@ def match(t1, t2, g1, g2): else: t1[2] += 1 t2[2] += 1 - + + def test(): team1 = ["Ajax", 0, 0, 0] team2 = ["Benfica", 0, 0, 0] team3 = ["Juventus", 0, 0, 0] print(team1, team2, team3) - + match(team1, team2, 2, 1) print(team1, team2, team3) match(team2, team3, 1, 1) @@ -31,7 +32,8 @@ def test(): match(team3, team1, 0, 3) print(team1, team2, team3) + # Run tests: test() -# JMR@ua.pt 2021 \ No newline at end of file +# JMR@ua.pt 2021 diff --git a/1ano/1semestre/fp/aula05/tp05-codecheck/exercises03/ex01.py b/1ano/1semestre/fp/aula05/tp05-codecheck/exercises03/ex01.py index b636568..7484b0b 100755 --- a/1ano/1semestre/fp/aula05/tp05-codecheck/exercises03/ex01.py +++ b/1ano/1semestre/fp/aula05/tp05-codecheck/exercises03/ex01.py @@ -9,6 +9,7 @@ def inputDate(): d = int(input("Dia? ")) return (y, m, d) + # Complete a definição de forma que inputPerson(msg) # 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)). @@ -18,20 +19,22 @@ def inputPerson(msg): birth = inputDate() return (name, birth) + def test(): print("Natal de 2020") natal = inputDate() print("natal:", natal) - + p1 = inputPerson("Introduza os dados de p1") print("p1:", p1) p2 = inputPerson("Introduza os dados de p2") print("p2:", p2) - + older = p1[1] < p2[1] print("p1 é mais velha que p2:", older) - + + # Run tests: test() -# JMR@ua.pt 2021 \ No newline at end of file +# JMR@ua.pt 2021 diff --git a/1ano/1semestre/fp/aula05/tp05-codecheck/exercises03/ex02.py b/1ano/1semestre/fp/aula05/tp05-codecheck/exercises03/ex02.py index f2550a8..5c6cc96 100755 --- a/1ano/1semestre/fp/aula05/tp05-codecheck/exercises03/ex02.py +++ b/1ano/1semestre/fp/aula05/tp05-codecheck/exercises03/ex02.py @@ -4,14 +4,16 @@ MESESPT = ("janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro") + # Complete a função para que, dado um tuplo (ano, mes, dia) # devolva um data por extenso. # Por exemplo, datePT((1938, 1, 22)) deve devolver "22 de janeiro de 1938". def datePT(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 + # Complete a definição para converter uma data no formato "DD/MM/AAAA" # num tuplo de inteiros com (ano, mês, dia). # Por exemplo: parseDMY("25/12/2020") deve devolver (2020, 12, 25). @@ -23,4 +25,4 @@ def parseDMY(s): # No CodeCheck estas funções são testadas com argumentos pré-programados. # Se quiser testar offline, tem de acrescentar as suas intruções de chamada. -# JMR@ua.pt 2021 \ No newline at end of file +# JMR@ua.pt 2021 diff --git a/1ano/1semestre/fp/aula06/fileList.py b/1ano/1semestre/fp/aula06/fileList.py index c6fba1b..8dfe5db 100755 --- a/1ano/1semestre/fp/aula06/fileList.py +++ b/1ano/1semestre/fp/aula06/fileList.py @@ -17,8 +17,8 @@ def printFilesSize(path): print(f"[Error] Path is not a directory: '{os.path.abspath(path)}'") exit(1) else: - print(f'|{"-"*78}|') - print(f'| {"File":<63} {"Size":>12} |\n|{"-"*78}|') + print(f'|{"-" * 78}|') + print(f'| {"File":<63} {"Size":>12} |\n|{"-" * 78}|') for file in directory: base_size = os.stat(f'{path}/{file}').st_size if os.path.isdir(f'{path}/{file}'): @@ -28,11 +28,11 @@ def printFilesSize(path): elif base_size < 1024 ** 2: size = f'{base_size // 1024}.{str(base_size % 1024)[0]} KB' 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: - 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'|{"-"*78}|') + print(f'|{"-" * 78}|') if __name__ == "__main__": diff --git a/1ano/1semestre/fp/aula06/filesum.py b/1ano/1semestre/fp/aula06/filesum.py index f1f7ec0..f6ab9e8 100755 --- a/1ano/1semestre/fp/aula06/filesum.py +++ b/1ano/1semestre/fp/aula06/filesum.py @@ -4,10 +4,10 @@ from tkinter import filedialog def main(): # 1) Pedir nome do ficheiro (usando alternativa #B): name = filedialog.askopenfilename(title="Choose File") - + # 2) Calcular soma dos números no ficheiro: total = fileSum(name) - + # 3) Mostrar a soma: print("Sum:", total) diff --git a/1ano/1semestre/fp/aula06/floatinput.py b/1ano/1semestre/fp/aula06/floatinput.py index 68bece4..35d02ae 100755 --- a/1ano/1semestre/fp/aula06/floatinput.py +++ b/1ano/1semestre/fp/aula06/floatinput.py @@ -32,5 +32,6 @@ def main(): return + if __name__ == "__main__": main() diff --git a/1ano/1semestre/fp/aula06/school.py b/1ano/1semestre/fp/aula06/school.py index 396ab3b..844aaae 100755 --- a/1ano/1semestre/fp/aula06/school.py +++ b/1ano/1semestre/fp/aula06/school.py @@ -34,7 +34,7 @@ def main(): loadFile("datafiles/school1.csv", lst) loadFile("datafiles/school2.csv", lst) loadFile("datafiles/school3.csv", lst) - + # ordenar a lista lst.sort() # mostrar a pauta @@ -44,5 +44,3 @@ def main(): # Call main function if __name__ == "__main__": main() - - diff --git a/1ano/1semestre/fp/aula07/campeonato.py b/1ano/1semestre/fp/aula07/campeonato.py index 7a247b8..9cc7734 100644 --- a/1ano/1semestre/fp/aula07/campeonato.py +++ b/1ano/1semestre/fp/aula07/campeonato.py @@ -1,20 +1,21 @@ -from extras.allMatches import * # importa a função allMatches criada na aula05 import math +from extras.allMatches import * # importa a função allMatches criada na aula05 + def main(): - equipas = getTeams() # pede as equipas ao utilizador - partidas = allMatches(equipas) # cria a lista de partidas - resultados = getResults(partidas) # pede os resultados ao utilizador + equipas = getTeams() # pede as equipas ao utilizador + partidas = allMatches(equipas) # cria a lista de partidas + resultados = getResults(partidas) # pede os resultados ao utilizador tabela = getTable(equipas, resultados) # cria a tabela de classificação - printTable(tabela) # imprime a tabela de classificação + printTable(tabela) # imprime a tabela de classificação def getTeams(): - teams = [] # cria uma lista vazia para as equipas - while True: # Ciclo para obter as equipas + teams = [] # cria uma lista vazia para as equipas + while True: # Ciclo para obter as equipas team = input("Nome da equipa: ") - if team in teams: # Garante não haver equipas repetidas + if team in teams: # Garante não haver equipas repetidas continue if team == "": if len(teams) < 2: @@ -26,25 +27,25 @@ def getTeams(): def getResults(matches): - results = dict() # cria um dicionário vazio para os resultados + results = dict() # cria um dicionário vazio para os resultados for match in matches: - team1, team2 = match # desempacota a partida + team1, team2 = match # desempacota a partida print("Resultado do jogo entre", team1, "e", team2) goals1 = int(input("Golos da equipa 1: ")) goals2 = int(input("Golos da equipa 2: ")) - results[match] = (goals1, goals2) # adiciona o resultado ao dicionário + results[match] = (goals1, goals2) # adiciona o resultado ao dicionário return results def getTable(teams, results): - table = dict() # cria um dicionário vazio para a tabela + table = dict() # cria um dicionário vazio para a tabela for team in teams: - table[team] = [0, 0, 0, 0, 0, 0] # inicializa a tabela com as equipas a zeros + table[team] = [0, 0, 0, 0, 0, 0] # inicializa a tabela com as equipas a zeros for match in results: - team1, team2 = match # desempacota a partida - goals1, goals2 = results[match] # desempacota os resultados + team1, team2 = match # desempacota a partida + goals1, goals2 = results[match] # desempacota os resultados # atualiza os resultados da equipa 1 updateStats(table, team1, goals1, goals2) @@ -54,18 +55,18 @@ def getTable(teams, results): # devolve a tabela ordenada por pontos, diferença de golos e por último por golos marcados. 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): - 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][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][4] += gs # adiciona os golos marcados + 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][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][4] += gs # adiciona os golos marcados def printTable(table): - print(f"\n{'Equipa':<15}\tV\tE\tD\tGM\tGS\tPts") for team in table: diff --git a/1ano/1semestre/fp/aula07/coins.py b/1ano/1semestre/fp/aula07/coins.py index 038dfe2..5671d18 100755 --- a/1ano/1semestre/fp/aula07/coins.py +++ b/1ano/1semestre/fp/aula07/coins.py @@ -37,7 +37,6 @@ def transfer(bag1, amount, bag2): def transferProcess(bag1, amount, bag2, coins): - bagBackup = (bag1.copy(), bag2.copy()) amountBackup = amount @@ -57,11 +56,11 @@ def transferProcess(bag1, amount, bag2, coins): if len(coins) == 1: 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): - """Return a string representing the contents of a bag.""" + """Return a string representing the contents of a bag.""" # You may want to change this to produce a more user-friendly # representation such as "4x200+3x50+1x5+3x1=958". string = "" @@ -82,29 +81,29 @@ def main(): assert value({1: 7, 5: 2, 20: 4, 100: 1}) == 197 # Test the strbag function. - print(strbag({1: 7, 5: 2, 20: 4, 100: 1})) # 1x100+4x20+2x5+7x1=197 + print(strbag({1: 7, 5: 2, 20: 4, 100: 1})) # 1x100+4x20+2x5+7x1=197 print(strbag({1: 7, 5: 2, 10: 0, 20: 4, 100: 1})) # 1x100+4x20+2x5+7x1=197 - print("bag1:", strbag(bag1)) # bag1: 1x200+2x100+4x50+5x20+1x5+4x1=709 - print("bag2:", strbag(bag2)) # bag2: =0 - - print(transfer1coin(bag1, 10, bag2)) # False! - print("bag1:", strbag(bag1)) # bag1: 1x200+2x100+4x50+5x20+1x5+4x1=709 - print("bag2:", strbag(bag2)) # bag2: =0 + print("bag1:", strbag(bag1)) # bag1: 1x200+2x100+4x50+5x20+1x5+4x1=709 + print("bag2:", strbag(bag2)) # bag2: =0 - print(transfer1coin(bag1, 20, bag2)) # True - print("bag1:", strbag(bag1)) # bag1: 1x200+2x100+4x50+4x20+1x5+4x1=689 - print("bag2:", strbag(bag2)) # bag2: 1x20=20 + print(transfer1coin(bag1, 10, bag2)) # False! + print("bag1:", strbag(bag1)) # bag1: 1x200+2x100+4x50+5x20+1x5+4x1=709 + print("bag2:", strbag(bag2)) # bag2: =0 - print(transfer1coin(bag1, 20, bag2)) # True - print("bag1:", strbag(bag1)) # bag1: 1x200+2x100+4x50+3x20+1x5+4x1=669 - print("bag2:", strbag(bag2)) # bag2: 2x20=40 + print(transfer1coin(bag1, 20, bag2)) # True + print("bag1:", strbag(bag1)) # bag1: 1x200+2x100+4x50+4x20+1x5+4x1=689 + print("bag2:", strbag(bag2)) # bag2: 1x20=20 - print(transfer(bag1, 157, bag2)) # True (should be easy) - print("bag1:", strbag(bag1)) # bag1: 1x200+1x100+3x50+3x20+2x1=512 - print("bag2:", strbag(bag2)) # bag2: 1x100+1x50+2x20+1x5+2x1=197 + print(transfer1coin(bag1, 20, bag2)) # True + print("bag1:", strbag(bag1)) # bag1: 1x200+2x100+4x50+3x20+1x5+4x1=669 + print("bag2:", strbag(bag2)) # bag2: 2x20=40 - print(transfer(bag1, 60, bag2)) # not easy, but possible... + print(transfer(bag1, 157, bag2)) # True (should be easy) + print("bag1:", strbag(bag1)) # bag1: 1x200+1x100+3x50+3x20+2x1=512 + print("bag2:", strbag(bag2)) # bag2: 1x100+1x50+2x20+1x5+2x1=197 + + print(transfer(bag1, 60, bag2)) # not easy, but possible... print("bag1:", strbag(bag1)) print("bag2:", strbag(bag2)) @@ -113,4 +112,3 @@ def main(): if __name__ == "__main__": main() - diff --git a/1ano/1semestre/fp/aula07/countLetters.py b/1ano/1semestre/fp/aula07/countLetters.py index 41a8276..8585b0b 100644 --- a/1ano/1semestre/fp/aula07/countLetters.py +++ b/1ano/1semestre/fp/aula07/countLetters.py @@ -3,11 +3,11 @@ import sys def main(): letters = countLetters(sys.argv[1]) - + # Print the results for c in sorted(letters.keys()): print(c, letters[c]) - + # Print the most used letter and the number of times it's used usedTheMostCount = max(letters.values()) usedTheMost = [letter for letter in letters.keys() if letters[letter] == usedTheMostCount][0] @@ -24,7 +24,7 @@ def countLetters(filename): if c not in letters: letters[c] = 0 letters[c] += 1 - + # Returns the dictionary with the letters return letters diff --git a/1ano/1semestre/fp/aula08/imctable2.py b/1ano/1semestre/fp/aula08/imctable2.py index c9aa5a8..8df48c1 100644 --- a/1ano/1semestre/fp/aula08/imctable2.py +++ b/1ano/1semestre/fp/aula08/imctable2.py @@ -1,17 +1,16 @@ - # Devolve o IMC para uma pessoa com peso w e altura h. def imc(w, h): - return w/h**2 + return w / h ** 2 def main(): # Lista de pessoas com nome, peso em kg, altura em metro. people = [("John", 64.5, 1.757), - ("Berta", 64.0, 1.612), - ("Maria", 45.1, 1.715), - ("Andy", 98.3, 1.81), - ("Lisa", 46.8, 1.622), - ("Kelly", 83.2, 1.78)] + ("Berta", 64.0, 1.612), + ("Maria", 45.1, 1.715), + ("Andy", 98.3, 1.81), + ("Lisa", 46.8, 1.622), + ("Kelly", 83.2, 1.78)] print("People:", people) @@ -19,7 +18,7 @@ def main(): names = [n for n, w, h in people] # = [p[0] for p in people] # equivalente print("Names:", names) - + # Usando list comprehensions, obtenha: # a) Uma lista com os valores de imc de todas as pessoas. imcs = [imc(w, h) for n, w, h in people] @@ -27,7 +26,7 @@ def main(): # b) Uma lista dos tuplos de pessoas com altura superior a 1.7m. tallpeople = [(n, w, h) for n, w, h in people if h > 1.7] - print("Tall people:", tallpeople) + print("Tall people:", tallpeople) # c) Uma lista de nomes das pessoas com IMC entre 18 e 25. midimc = [n for n, w, h in people if 18 <= imc(w, h) <= 25] diff --git a/1ano/1semestre/fp/aula08/interests.py b/1ano/1semestre/fp/aula08/interests.py index e7676d4..27c6622 100644 --- a/1ano/1semestre/fp/aula08/interests.py +++ b/1ano/1semestre/fp/aula08/interests.py @@ -1,4 +1,3 @@ - def main(): A = "reading" B = "eating" @@ -16,7 +15,7 @@ def main(): "Paolo": {B, D, F}, "Frank": {D, B, E, F, A}, "Teresa": {F, H, C, D} - } + } print("a) Table of common interests:") commoninterests = {(p1, p2): interests[p1].intersection(interests[p2]) diff --git a/1ano/1semestre/fp/aula08/primesupto.py b/1ano/1semestre/fp/aula08/primesupto.py index 50e7000..a502c5a 100644 --- a/1ano/1semestre/fp/aula08/primesupto.py +++ b/1ano/1semestre/fp/aula08/primesupto.py @@ -1,14 +1,14 @@ # Algorithm from https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Pseudocode def primesUpTo(n): 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]: - for j in range(i**2, n+1, i): + for j in range(i ** 2, n + 1, i): 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(): @@ -17,7 +17,7 @@ def main(): print(s) # 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(7918)) == 999 assert len(primesUpTo(7919)) == 1000 diff --git a/1ano/1semestre/fp/aula09/binarySearch.py b/1ano/1semestre/fp/aula09/binarySearch.py index 22e2499..e60a63d 100644 --- a/1ano/1semestre/fp/aula09/binarySearch.py +++ b/1ano/1semestre/fp/aula09/binarySearch.py @@ -1,6 +1,5 @@ import bisect - with open("wordlist.txt", "r") as f: word_list: list[str] = f.read().split() diff --git a/1ano/1semestre/fp/aula09/countLetters2.py b/1ano/1semestre/fp/aula09/countLetters2.py index 2032210..e3f8227 100644 --- a/1ano/1semestre/fp/aula09/countLetters2.py +++ b/1ano/1semestre/fp/aula09/countLetters2.py @@ -3,7 +3,7 @@ import sys def main(): letters = countLetters(sys.argv[1]) - + # Print the results for c in sorted(letters, key=letters.get, reverse=True): print(c, letters[c]) @@ -25,7 +25,7 @@ def countLetters(filename): if c not in letters: letters[c] = 0 letters[c] += 1 - + # Returns the dictionary with the letters return letters diff --git a/1ano/1semestre/fp/aula09/findZero.py b/1ano/1semestre/fp/aula09/findZero.py index e4d45c6..a721fe1 100644 --- a/1ano/1semestre/fp/aula09/findZero.py +++ b/1ano/1semestre/fp/aula09/findZero.py @@ -2,7 +2,7 @@ import math 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): diff --git a/1ano/1semestre/fp/aula09/insertionSort.py b/1ano/1semestre/fp/aula09/insertionSort.py index 63305cd..3c71f05 100644 --- a/1ano/1semestre/fp/aula09/insertionSort.py +++ b/1ano/1semestre/fp/aula09/insertionSort.py @@ -1,4 +1,3 @@ - # This function sorts a list (like list.sort) # using the insertion sort algorithm. # Modify it to accept a key= keyword argument that works like in list.sort. @@ -7,7 +6,7 @@ def insertionSort(lst, key=None): # Traverse elements starting at position 1 for i in range(1, len(lst)): # We know that lst[:i] is sorted - x = lst[i] # x is the element to insert next + x = lst[i] # x is the element to insert next # Elements in lst[:i] that are > x must move one position ahead j = i - 1 while j >= 0 and (key(lst[j]) > key(x) if key else lst[j] > x): @@ -37,7 +36,7 @@ def main(): assert lst == sorted(lst0, key=len) # sort by length, than lexicographic order: - myorder = lambda s:(len(s), s) + myorder = lambda s: (len(s), s) lst = lst0.copy() insertionSort(lst, key=myorder) print("lst3", lst) @@ -48,4 +47,3 @@ def main(): if __name__ == "__main__": main() - diff --git a/1ano/1semestre/fp/aula09/integrate.py b/1ano/1semestre/fp/aula09/integrate.py index 7101390..2807344 100644 --- a/1ano/1semestre/fp/aula09/integrate.py +++ b/1ano/1semestre/fp/aula09/integrate.py @@ -1,5 +1,4 @@ import sys -import math def integrate(f, a, b, n): diff --git a/1ano/1semestre/fp/aula09/median.py b/1ano/1semestre/fp/aula09/median.py index 97dd3f2..74cb470 100644 --- a/1ano/1semestre/fp/aula09/median.py +++ b/1ano/1semestre/fp/aula09/median.py @@ -7,7 +7,7 @@ def median(lst): lst = sorted(lst, reverse=True) if len(lst) % 2 == 0: middle = len(lst) // 2 - 1 - return sum(lst[middle:middle+2]) / 2 + return sum(lst[middle:middle + 2]) / 2 else: return lst[len(lst) // 2] diff --git a/1ano/1semestre/fp/aula09/polynomial.py b/1ano/1semestre/fp/aula09/polynomial.py index 9e17695..d7f310c 100644 --- a/1ano/1semestre/fp/aula09/polynomial.py +++ b/1ano/1semestre/fp/aula09/polynomial.py @@ -4,7 +4,7 @@ # polynomial2(a,b,c) deve devolver uma função f tal que # f(x) seja o polinómio de segundo grau ax²+bx+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: @@ -14,26 +14,26 @@ def polynomial2(a, b, c): # 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. 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(): - xx = [0, 1, 2, 3] # Valores de x a testar + xx = [0, 1, 2, 3] # Valores de x a testar print("\nTestes à função polynomial2:") - p = polynomial2(1, 2, 3) # creates p(x)=x²+2x+3 - print([p(x) for x in xx]) # [3, 6, 11, 18] + p = polynomial2(1, 2, 3) # creates p(x)=x²+2x+3 + print([p(x) for x in xx]) # [3, 6, 11, 18] - q = polynomial2(2, 0, -2) # creates q(x)=2x²-2 - print([q(x) for x in xx]) # [-2, 0, 6, 16] + q = polynomial2(2, 0, -2) # creates q(x)=2x²-2 + print([q(x) for x in xx]) # [-2, 0, 6, 16] print("\nTestes à função polynomial:") - r = polynomial([1, 2, 3]) # same as p(x) - print([r(x) for x in xx]) # [3, 6, 11, 18] + r = polynomial([1, 2, 3]) # same as p(x) + print([r(x) for x in xx]) # [3, 6, 11, 18] + + s = polynomial([1, -1, 0, 100]) # creates s(x)=x³-x²+100 + print([s(x) for x in xx]) # [100, 100, 104, 118] - s = polynomial([1, -1, 0, 100]) # creates s(x)=x³-x²+100 - print([s(x) for x in xx]) # [100, 100, 104, 118] if __name__ == "__main__": main() - diff --git a/1ano/1semestre/fp/aula09/tabelaFutebol.py b/1ano/1semestre/fp/aula09/tabelaFutebol.py index 882a5d3..ef18b98 100644 --- a/1ano/1semestre/fp/aula09/tabelaFutebol.py +++ b/1ano/1semestre/fp/aula09/tabelaFutebol.py @@ -1,4 +1,3 @@ - # Tabela classificativa da Primeira Liga de futebol de Portugal em 2018-11-30. # (Descarregada de https://www.resultados.com/futebol/portugal/primeira-liga/) @@ -32,23 +31,22 @@ N, V, E, D, GM, GS = 0, 1, 2, 3, 4, 5 def printTabela(tabela): print() 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: - nome,v,e,d,gm,gs = reg + nome, v, e, d, gm, gs = reg 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, # 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) # 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. # (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(): @@ -57,7 +55,6 @@ def main(): print(tabela[-1][N], pontos(tabela[-1])) # Chaves 7? - # Mostra a tabela classificativa original, não ordenada: printTabela(tabela) @@ -70,14 +67,14 @@ def main(): # c) # Acrescente os argumentos adequados à função sorted para # 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) # d) # Acrescente os argumentos adequados à função sorted para # obter uma tabela ordenada por ordem decrescente de pontos e, # 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) diff --git a/1ano/1semestre/fp/aula10/findFiles.py b/1ano/1semestre/fp/aula10/findFiles.py index 5acb44d..a419f7c 100644 --- a/1ano/1semestre/fp/aula10/findFiles.py +++ b/1ano/1semestre/fp/aula10/findFiles.py @@ -46,4 +46,3 @@ def main(): if __name__ == "__main__": main() - diff --git a/1ano/1semestre/fp/aula10/genWords.py b/1ano/1semestre/fp/aula10/genWords.py index d31dbcd..1b599ed 100644 --- a/1ano/1semestre/fp/aula10/genWords.py +++ b/1ano/1semestre/fp/aula10/genWords.py @@ -1,15 +1,14 @@ - # Generates all length-3 words with symbols taken from the given alphabet. 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. def genWords(symbols, n): if n == 0: return [''] - lista = genWords(symbols, n-1) - return [ x+y for x in symbols for y in lista ] + lista = genWords(symbols, n - 1) + return [x + y for x in symbols for y in lista] def main(): @@ -26,6 +25,6 @@ def main(): lstC = genWords("01", 4) # should return all length-4 binary words print(lstC) + if __name__ == "__main__": main() - diff --git a/1ano/1semestre/fp/aula10/moveLetters.py b/1ano/1semestre/fp/aula10/moveLetters.py index 5471a79..213bea8 100644 --- a/1ano/1semestre/fp/aula10/moveLetters.py +++ b/1ano/1semestre/fp/aula10/moveLetters.py @@ -12,6 +12,7 @@ endX("xxhixx") → "hixxxx" endX("hixhix") → "hihixx" """ + def endX(s): if s == '': return '' diff --git a/1ano/1semestre/fp/aula10/recErrors.py b/1ano/1semestre/fp/aula10/recErrors.py index 21ed87d..06bc9be 100644 --- a/1ano/1semestre/fp/aula10/recErrors.py +++ b/1ano/1semestre/fp/aula10/recErrors.py @@ -1,10 +1,9 @@ - # Calcula o factorial de n, baseado na recorrencia n! = n*(n-1)!. # Mas não termina! Detete a causa e corrija o erro. def fact(n): if n == 0: return 1 - return n*fact(n-1) + return n * fact(n - 1) # 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. def gcd(a, b): assert a > 0 and b > 0 - if a%b == 0: + if a % b == 0: return b - return gcd(b, a%b) + return gcd(b, a % b) def main(): - print( fact(4) ) # 24 - print( fact(5) ) # 120 + print(fact(4)) # 24 + print(fact(5)) # 120 - x = 2*27*53*61 - y = 2*2*17*23*53 + x = 2 * 27 * 53 * 61 + y = 2 * 2 * 17 * 23 * 53 print(x, y, gcd(x, y)) - assert gcd(x, y) == 2*53 + assert gcd(x, y) == 2 * 53 if __name__ == "__main__": diff --git a/1ano/1semestre/fp/aula10/recmickey.py b/1ano/1semestre/fp/aula10/recmickey.py index d7f730c..5334b57 100644 --- a/1ano/1semestre/fp/aula10/recmickey.py +++ b/1ano/1semestre/fp/aula10/recmickey.py @@ -1,4 +1,5 @@ import sys + from ezgraphics import GraphicsWindow diff --git a/1ano/1semestre/fp/aula10/reverseDigits.py b/1ano/1semestre/fp/aula10/reverseDigits.py index f734a83..bdeef6d 100644 --- a/1ano/1semestre/fp/aula10/reverseDigits.py +++ b/1ano/1semestre/fp/aula10/reverseDigits.py @@ -24,4 +24,4 @@ def reverseDigits(value): def reverseAux(partValue, partReversed): if partValue == 0: return partReversed - return reverseAux(partValue//10, partReversed*10 + partValue%10) + return reverseAux(partValue // 10, partReversed * 10 + partValue % 10) diff --git a/1ano/1semestre/fp/aula10/traced.py b/1ano/1semestre/fp/aula10/traced.py index 6c72a84..0ef9444 100644 --- a/1ano/1semestre/fp/aula10/traced.py +++ b/1ano/1semestre/fp/aula10/traced.py @@ -16,7 +16,7 @@ def traced(func): traced.indent += u"\u2502 " print(u"{}{}{!r}{!r}".format(indent, func.__name__, args, kwargs)) try: - r = func(*args, **kwargs) # CALL the func! + r = func(*args, **kwargs) # CALL the func! return r except Exception as e: r = e @@ -25,26 +25,27 @@ def traced(func): if traced.indent != None: print(u"{}\u2514>{!r}".format(indent, r)) traced.indent = indent # restore indentation - + return tracedfunc + # Initial tracing prefix: traced.indent = "" # 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__": - # How to use this module: from traced import traced - + + @traced def func(x): - return x*x + return x * x + func(3) - diff --git a/1ano/1semestre/fp/avaliacao/ap2/ex9.py b/1ano/1semestre/fp/avaliacao/ap2/ex9.py index 1f6cb03..0b234af 100644 --- a/1ano/1semestre/fp/avaliacao/ap2/ex9.py +++ b/1ano/1semestre/fp/avaliacao/ap2/ex9.py @@ -27,4 +27,3 @@ def score(guess, secret): cows_index.append(i) return len(bulls_index), len(cows_index) - diff --git a/1ano/1semestre/fp/avaliacao/apx1/apx1.py b/1ano/1semestre/fp/avaliacao/apx1/apx1.py index 473574f..83eff4e 100755 --- a/1ano/1semestre/fp/avaliacao/apx1/apx1.py +++ b/1ano/1semestre/fp/avaliacao/apx1/apx1.py @@ -4,27 +4,27 @@ def isLeapYear(year): def monthDays(year, month): assert month > 0 - + MONTHDAYS = (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) days = MONTHDAYS[month] - + return days + 1 if (isLeapYear(year) and month == 2) else days def nextDay(year, month, day): if not dateIsValid(year, month, day): return - + # Verifica se é o último dia do ano if (month, day) == (12, 31): year += 1 month = 1 day = 1 - + # Verifica se é o último dia do mês elif (monthDays(year, month) == day): month += 1 day = 1 - + # Dia comum else: day += 1 @@ -38,20 +38,20 @@ def dateIsValid(year, month, day): def previousDay(year, month, day): if not dateIsValid(year, month, day): return - + # Primeiro dia do ano if (month, day) == (1, 1): year -= 1 month = 12 day = 31 - + # Primeiro dia do mês (sem ser janeiro) elif day == 1: day = monthDays(year, month - 1) month -= 1 - + # Dia comum else: day -= 1 - - return year, month, day \ No newline at end of file + + return year, month, day diff --git a/1ano/1semestre/fp/avaliacao/apx2/shop.py b/1ano/1semestre/fp/avaliacao/apx2/shop.py index 7f42456..465f2aa 100644 --- a/1ano/1semestre/fp/avaliacao/apx2/shop.py +++ b/1ano/1semestre/fp/avaliacao/apx2/shop.py @@ -7,20 +7,21 @@ def loadDataBase(fname, produtos): """Lê dados do ficheiro fname e atualiza/acrescenta a informação num dicionário de produtos com o formato {código: (nome, secção, preço, iva), ...}. """ - with open(fname, 'r') as f: # Abre o ficheiro em modo de leitura - productsFileContent = f.read() # Cria uma string com o conteudo do ficheiro + with open(fname, 'r') as f: # Abre o ficheiro em modo de leitura + 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 - productComponents = product.split(';') # Divide as componentes do produto (código, nome, secção, preço, iva) + 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) if len(productComponents) != 5: continue - produtos.update({productComponents[0]: ( # Atualiza a entrada de uma determinada chave (código) - productComponents[1], # Nome - productComponents[2], # Secção - float(productComponents[3]), # Preço - float(productComponents[4].strip('%')) / 100 # IVA + produtos.update({productComponents[0]: ( # Atualiza a entrada de uma determinada chave (código) + productComponents[1], # Nome + productComponents[2], # Secção + float(productComponents[3]), # Preço + float(productComponents[4].strip('%')) / 100 # IVA )}) @@ -29,13 +30,14 @@ def registaCompra(produtos): mostra nome, quantidade e preço final de cada um, 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? ') while userInput != "": try: - code, amount = userInput.split(' ') # Divide o input do utilizador no código e na quantia + code, amount = userInput.split(' ') # Divide o input do utilizador no código e na quantia except ValueError: - code, amount = userInput, 1 # No caso de não ser introduzida quantia, então ela fica 1 + code, amount = userInput, 1 # No caso de não ser introduzida quantia, então ela fica 1 # Caso a segunda parcela da entrada não seja um número, é pedido ao utilizador para introduzir o código de novo try: @@ -45,37 +47,39 @@ def registaCompra(produtos): continue if code in produtos: - if code not in compra: # Se o produto ainda não estiver na lista é adicionado à mesma + if code not in compra: # Se o produto ainda não estiver na lista é adicionado à mesma compra[code] = 0 - compra[code] += amount # Adiciona ao dicionário da compra a quantidade comprada do 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"][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}") + compra[code] += amount # Adiciona ao dicionário da compra a quantidade comprada do 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"][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}") userInput = input('Code? ') - compra["totals"][2] += compra["totals"][0] + compra["totals"][1] # Calcula o total liquido da compra - return compra # Devolve a lista + compra["totals"][2] += compra["totals"][0] + compra["totals"][1] # Calcula o total liquido da compra + return compra # Devolve a lista def fatura(produtos, compra): """Imprime a fatura de uma dada compra.""" # 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 for section in sections: - print(section) # Mostra a secção + print(section) # Mostra a secção # Obtém a lista de codigos usados na compra presentes na secção atual sectionProductsCodes = sorted([code for code in produtos if produtos[code][1] == section and code in compra]) # Itera os códigos para apresentar as informações de cada produto 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 print(f"""{'Total Bruto:':>41}{round(compra["totals"][0], 2):>11} @@ -91,7 +95,7 @@ def main(args): # Juntar bases de dados opcionais (Não altere) for arg in args: loadDataBase(arg, produtos) - + # Use este código para mostrar o menu e ler a opção repetidamente MENU = "(C)ompra (F)atura (S)air ? " compras = {} @@ -102,7 +106,7 @@ def main(args): # Processar opção if op == "C": # Esta opção regista os produtos de uma compra - compras[len(compras)+1] = registaCompra(produtos) + compras[len(compras) + 1] = registaCompra(produtos) elif op == "F": # 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 import sys + if __name__ == "__main__": main(sys.argv[1:]) diff --git a/1ano/1semestre/fp/extra2/telecom.py b/1ano/1semestre/fp/extra2/telecom.py index 0be8801..6e0fd73 100644 --- a/1ano/1semestre/fp/extra2/telecom.py +++ b/1ano/1semestre/fp/extra2/telecom.py @@ -74,7 +74,7 @@ def fatura(calls: dict, phone_number: str) -> None: if phone_number not in calls: print("Cliente não existe\n") return - + total = 0 print("Fatura do cliente", phone_number) @@ -98,8 +98,10 @@ def fatura(calls: dict, phone_number: str) -> None: 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__': - main() \ No newline at end of file + main() diff --git a/1ano/1semestre/fp/extra2/totobola.py b/1ano/1semestre/fp/extra2/totobola.py index 54c88de..00b29b2 100644 --- a/1ano/1semestre/fp/extra2/totobola.py +++ b/1ano/1semestre/fp/extra2/totobola.py @@ -23,7 +23,7 @@ def get_user_input(journeys: dict, budget: int) -> None: print('Jornada inválida') 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: for match in journeys[journey_input]: while True: @@ -32,12 +32,12 @@ def get_user_input(journeys: dict, budget: int) -> None: f.write(f"{match_id},{bet}\n") match_id += 1 if len(bet) != 1: - true_bet_count[len(bet)-2] += 1 + true_bet_count[len(bet) - 2] += 1 break else: 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) @@ -56,11 +56,11 @@ def print_results(journeys: dict, journey: int, budget: int) -> None: for game in games: game = game.strip().split(',') 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 ( - ('1' in bet and game[3] > game[4]) - or ('X' in bet and game[3] == game[4]) - or ('2' 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 ('2' in bet and game[3] < game[4]) ) else 'ERRADO' if result == 'CERTO': right_bets_count += 1 @@ -74,7 +74,8 @@ def print_results(journeys: dict, journey: int, budget: int) -> None: price = 1000 else: 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 get_user_input(journeys, budget) diff --git a/1ano/1semestre/fp/extra2/twitter.py b/1ano/1semestre/fp/extra2/twitter.py index 2441d07..2458cfa 100644 --- a/1ano/1semestre/fp/extra2/twitter.py +++ b/1ano/1semestre/fp/extra2/twitter.py @@ -13,9 +13,9 @@ with open("twitter.json", encoding="utf8") as f: twits = json.load(f) # Analise os resultados impressos para perceber a estrutura dos dados. -print(type(twits)) # deve indicar que é uma lista! -print(type(twits[0])) # cada elemento da lista é um dicionário. -print(twits[0].keys()) # mostra as chaves no primeiro elemento. +print(type(twits)) # deve indicar que é uma lista! +print(type(twits[0])) # cada elemento da lista é um dicionário. +print(twits[0].keys()) # mostra as chaves no primeiro elemento. # Cada elemento contém uma mensagem associada à chave "text": print(twits[0]["text"]) @@ -23,7 +23,6 @@ print(twits[0]["text"]) # Algumas mensagens contêm hashtags: print(twits[880]["text"]) - # A) word_count: dict[str, int] = {} @@ -38,21 +37,18 @@ word_list = list(word_count.keys()) print("A)\n" + str(word_list), end="\n\n") - # B) ordered_list = sorted(word_list, key=lambda t: word_count[t], reverse=True) print("B)\n" + str(ordered_list), end="\n\n") - # C) ordered_hashtag_list = [word for word in ordered_list if word.startswith('#')] print("C)\n" + str(ordered_hashtag_list), end="\n\n") - # D) print("D)\n") most_used = word_count[ordered_hashtag_list[0]] 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)}") diff --git a/1ano/1semestre/fp/extra3/ex01.py b/1ano/1semestre/fp/extra3/ex01.py index 53fa5ef..0bdcb6a 100644 --- a/1ano/1semestre/fp/extra3/ex01.py +++ b/1ano/1semestre/fp/extra3/ex01.py @@ -1,4 +1,3 @@ - # 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 # is white, alternating across a row. Odd rows start with black, even rows start with white. diff --git a/1ano/1semestre/fp/extra3/ex02.py b/1ano/1semestre/fp/extra3/ex02.py index 5809bdc..1b8fb84 100644 --- a/1ano/1semestre/fp/extra3/ex02.py +++ b/1ano/1semestre/fp/extra3/ex02.py @@ -6,7 +6,7 @@ def firstEqualLast(lst): 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:]: n = i return n diff --git a/1ano/1semestre/fp/extra3/ex03.py b/1ano/1semestre/fp/extra3/ex03.py index 1d04ea9..ce6ae7c 100644 --- a/1ano/1semestre/fp/extra3/ex03.py +++ b/1ano/1semestre/fp/extra3/ex03.py @@ -1,4 +1,3 @@ - # 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 # case sensitive. diff --git a/1ano/1semestre/fp/extra3/ex04.py b/1ano/1semestre/fp/extra3/ex04.py index 7658cad..dae1ade 100644 --- a/1ano/1semestre/fp/extra3/ex04.py +++ b/1ano/1semestre/fp/extra3/ex04.py @@ -1,4 +1,3 @@ - # 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 # and is repeated again later. Do not use the find method. @@ -6,9 +5,9 @@ def longestPrefixRepeated(s): # Your code here... 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:]: longest = s[:i] - return longest \ No newline at end of file + return longest diff --git a/1ano/1semestre/fp/extra3/ex05.py b/1ano/1semestre/fp/extra3/ex05.py index b32256b..fbebd49 100644 --- a/1ano/1semestre/fp/extra3/ex05.py +++ b/1ano/1semestre/fp/extra3/ex05.py @@ -1,3 +1,4 @@ def printStocks(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}%") diff --git a/1ano/1semestre/fp/extra3/ex08.py b/1ano/1semestre/fp/extra3/ex08.py index f9a45a4..df00025 100644 --- a/1ano/1semestre/fp/extra3/ex08.py +++ b/1ano/1semestre/fp/extra3/ex08.py @@ -3,5 +3,6 @@ def load(fname): with open(fname, 'r') as f: for stock in f: 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 diff --git a/1ano/1semestre/fp/extra3/ex10.py b/1ano/1semestre/fp/extra3/ex10.py index b5f7f35..1494eea 100644 --- a/1ano/1semestre/fp/extra3/ex10.py +++ b/1ano/1semestre/fp/extra3/ex10.py @@ -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. def unload(t, m, q): @@ -27,23 +28,23 @@ def unload(t, m, q): v[1] -= q q = 0 return q - + def main(): - t = eval(input()) - - print("t: ", t) - q = unload(t, "rice", 40) - print("unload(t, 'rice', 40) ->", q) - - print("t: ", t) - q = unload(t, "coal", 50) - print("unload(t, 'coal', 50) ->", q) - - print("t: ", t) - q = unload(t, "iron", 20) - print("unload(t, 'iron', 20) ->", q) - + t = eval(input()) + + print("t: ", t) + q = unload(t, "rice", 40) + print("unload(t, 'rice', 40) ->", q) + + print("t: ", t) + q = unload(t, "coal", 50) + print("unload(t, 'coal', 50) ->", q) + + print("t: ", t) + q = unload(t, "iron", 20) + print("unload(t, 'iron', 20) ->", q) + if __name__ == "__main__": - main() + main() diff --git a/1ano/1semestre/fp/extra3/ex11.py b/1ano/1semestre/fp/extra3/ex11.py index 46484bf..552208c 100644 --- a/1ano/1semestre/fp/extra3/ex11.py +++ b/1ano/1semestre/fp/extra3/ex11.py @@ -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. """ + def onlyCaps(s): # 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:])) - diff --git a/1ano/2semestre/labi/tema05/src/Actions.py b/1ano/2semestre/labi/tema05/src/Actions.py new file mode 100644 index 0000000..6f16337 --- /dev/null +++ b/1ano/2semestre/labi/tema05/src/Actions.py @@ -0,0 +1,10 @@ +import cherrypy + + +class Actions(object): + @cherrypy.expose + def do_login(self, username=None, password=None): + if username is None or password is None: + return "Preencha os campos!" + else: + return "Bem-vindo, %s!" % username diff --git a/1ano/2semestre/labi/tema05/src/Website.py b/1ano/2semestre/labi/tema05/src/Website.py new file mode 100644 index 0000000..ae61b3d --- /dev/null +++ b/1ano/2semestre/labi/tema05/src/Website.py @@ -0,0 +1,54 @@ +import os +import cherrypy +import Actions + + +PATH = os.path.abspath(os.path.dirname(__file__)) + + +class HTMLDocument(object): + @cherrypy.expose + def index(self): + with open("example1.html", "r") as f: + return f.read() + + +class Node(object): + @cherrypy.expose + def index(self): + return "Eu sou o índice do Node (Node.index)" + + @cherrypy.expose + def page(self): + return "Eu sou um método do Node (Node.page)" + + +class Root(object): + def __init__(self): + self.node = Node() + self.html = HTMLDocument() + self.actions = Actions.Actions() + + @cherrypy.expose + def index(self): + return "Eu sou o índice do Root (Root.index)" + + @cherrypy.expose + def page(self): + return "Eu sou um método do Root (Root.page)" + + @cherrypy.expose + def form(self): + cherrypy.response.headers["Content-Type"] = "text/html" + return open("form1.html") + + +if __name__ == "__main__": + conf = { + "/": { + "tools.staticdir.on": True, + "tools.staticdir.dir": PATH, + } + } + cherrypy.quickstart(Root(), "/", config=conf) + \ No newline at end of file diff --git a/1ano/2semestre/labi/tema05/src/coords_getter.py b/1ano/2semestre/labi/tema05/src/coords_getter.py new file mode 100644 index 0000000..0560ac5 --- /dev/null +++ b/1ano/2semestre/labi/tema05/src/coords_getter.py @@ -0,0 +1,12 @@ +import json +import requests + + +address = "Universidade de Aveiro, 3810-193 Aveiro, Portugal" + +servurl = "https://nominatim.openstreetmap.org/search.php?format=json&q=%s" % address + +r = requests.get(servurl) + +print(json.dumps(r.json(), indent=4, sort_keys=True)) +print("Latitude:", r.json()[0]["lat"], "\nLongitude:", r.json()[0]["lon"]) diff --git a/1ano/2semestre/labi/tema05/src/example1.html b/1ano/2semestre/labi/tema05/src/example1.html new file mode 100644 index 0000000..a11cc84 --- /dev/null +++ b/1ano/2semestre/labi/tema05/src/example1.html @@ -0,0 +1,10 @@ + + +
+ +