[FP] Code reformat

- Performed code reformat to the entire directory '/1ano/1semestre/fp/'
This commit is contained in:
TiagoRG 2023-05-16 21:00:37 +01:00
parent 1866c6f4bc
commit 1076777203
102 changed files with 105833 additions and 386 deletions

View File

@ -1,13 +1,17 @@
# Fundamentos de Programação # Fundamentos de Programação
### Projetos + resoluções de exercícios organizados por aulas ### Projetos + resoluções de exercícios organizados por aulas
### Linguagem usada: [Python](https://www.python.org/) ### Linguagem usada: [Python](https://www.python.org/)
## [Finished] ## [Finished]
--- ---
## Índice ## Índice
| Aula nº | Tópicos |
|--------------------------------------------------------------------------|----------------------------------------| | Aula nº | Tópicos |
|------------------------------------------------------------------------------------|----------------------------------------|
| [01](https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/1semestre/fp/aula01) | Introduction, Basics | | [01](https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/1semestre/fp/aula01) | Introduction, Basics |
| [02](https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/1semestre/fp/aula02) | Conditionals, Boolean expressions | | [02](https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/1semestre/fp/aula02) | Conditionals, Boolean expressions |
| [03](https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/1semestre/fp/aula03) | Functions, Lambda expressions | | [03](https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/1semestre/fp/aula03) | Functions, Lambda expressions |
@ -18,5 +22,6 @@
| [08](https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/1semestre/fp/aula08) | List Comprehensions, Sets | | [08](https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/1semestre/fp/aula08) | List Comprehensions, Sets |
| [09](https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/1semestre/fp/aula09) | Searching, Sorting, Lambda Expressions | | [09](https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/1semestre/fp/aula09) | Searching, Sorting, Lambda Expressions |
| [10](https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/1semestre/fp/aula10) | Recursive Functions | | [10](https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/1semestre/fp/aula10) | Recursive Functions |
--- ---
*Pode conter erros, caso encontre algum, crie um* [*ticket*](https://github.com/TiagoRG/uaveiro-leci/issues/new) *Pode conter erros, caso encontre algum, crie um* [*ticket*](https://github.com/TiagoRG/uaveiro-leci/issues/new)

View File

@ -1,12 +1,12 @@
| Expressão | Valor | Tipo | | Expressão | Valor | Tipo |
|---------------|-----------|-----------| |---------------|----------|-----------|
| 1 + 2 * 5 | 11 | int | | 1 + 2 * 5 | 11 | int |
| 17 / 3.0 | 5.666667 | float | | 17 / 3.0 | 5.666667 | float |
| 17 / 3 | 5.666667 | float | | 17 / 3 | 5.666667 | float |
| 17 // 3 | 5 | int | | 17 // 3 | 5 | int |
| 17 % 3.0 | 2.0 | float | | 17 % 3.0 | 2.0 | float |
| 5.0 / 0.75 | 6.666667 | float | | 5.0 / 0.75 | 6.666667 | float |
| 5.0 // 0.75 | 6.0 | float | | 5.0 // 0.75 | 6.0 | float |
| 'tau' + 'rus' | 'taurus' | str | | 'tau' + 'rus' | 'taurus' | str |
| 'tau' + 2 | ? | TypeError | | 'tau' + 2 | ? | TypeError |
| 'tau' * 2 | 'tautau' | str | | 'tau' * 2 | 'tautau' | str |

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

@ -1,5 +1,7 @@
# Fundamentos de Programação # Fundamentos de Programação
## Aula 01 - [Slides](https://github.com/TiagoRG/uaveiro-leci/blob/master/1ano/1semestre/fp/slides/tp01-intro.pdf) ## Aula 01 - [Slides](https://github.com/TiagoRG/uaveiro-leci/blob/master/1ano/1semestre/fp/slides/tp01-intro.pdf)
### Tópico principal da aula: Introduction, Basics ### Tópico principal da aula: Introduction, Basics
--- ---

View File

@ -2,4 +2,4 @@ nome = input('Como te chamas? ')
anoNascenca = int(input('Em que ano nasceste? ')) anoNascenca = int(input('Em que ano nasceste? '))
ano = int(input('Ano para verificar: ')) ano = int(input('Ano para verificar: '))
print(f'{nome}, em {ano} farás {ano - anoNascenca} anos.') print(f'{nome}, em {ano} farás {ano - anoNascenca} anos.')

View File

@ -2,4 +2,4 @@ celcius = float(input('°C: '))
fahrenheit = 1.8 * celcius + 32 fahrenheit = 1.8 * celcius + 32
print(f'\n{celcius} °C = {fahrenheit} °F') print(f'\n{celcius} °C = {fahrenheit} °F')

View File

@ -3,4 +3,4 @@ v2 = float(input('Velocidade de regresso (v2): '))
vm = (2 * v1 * v2) / (v1 + v2) vm = (2 * v1 * v2) / (v1 + v2)
print('\nA velocidade média da viagem completa foi: ', vm) print('\nA velocidade média da viagem completa foi: ', vm)

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,5 +1,7 @@
# Fundamentos de Programação # Fundamentos de Programação
## Aula 02 - [Slides](https://github.com/TiagoRG/uaveiro-leci/blob/master/1ano/1semestre/fp/slides/tp02-selection.pdf) ## Aula 02 - [Slides](https://github.com/TiagoRG/uaveiro-leci/blob/master/1ano/1semestre/fp/slides/tp02-selection.pdf)
### Tópico principal da aula: Conditionals, Boolean expressions ### Tópico principal da aula: Conditionals, Boolean expressions
--- ---
*Pode conter erros, caso encontre algum, crie um* [*ticket*](https://github.com/TiagoRG/uaveiro-leci/issues/new) *Pode conter erros, caso encontre algum, crie um* [*ticket*](https://github.com/TiagoRG/uaveiro-leci/issues/new)

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.
@ -11,15 +10,15 @@ age = int(input("Age? "))
if age < 0: if age < 0:
print("ERROR: invalid age!") print("ERROR: invalid age!")
exit(1) # this terminates the program exit(1) # this terminates the program
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"
else: else:
cat = "grown-up" cat = "grown-up"
print("Category: ", cat) print("Category: ", cat)

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

@ -11,4 +11,4 @@ if x2 > mx:
if x3 > mx: if x3 > mx:
mx = x3 mx = x3
print("Maximum: ", mx) print("Maximum: ", mx)

View File

@ -7,4 +7,4 @@ if duracao < 60:
else: else:
custo = duracao * tarifario_sec custo = duracao * tarifario_sec
print('Custo: ', custo) print('Custo: ', custo)

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):
@ -16,4 +15,4 @@ NF = round(0.3 * ATPR + 0.7 * ATP)
if NF >= 10: if NF >= 10:
print('Aprovado com nota ', NF) print('Aprovado com nota ', NF)
else: else:
print('Continua reprovado, nota ', NF) print('Continua reprovado, nota ', NF)

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")
@ -23,4 +23,4 @@ elif imc < 30:
else: else:
categoria = "Obeso" categoria = "Obeso"
print("Categoria:", categoria) print("Categoria:", categoria)

View File

@ -1,5 +1,7 @@
# Fundamentos de Programação # Fundamentos de Programação
## Aula 03 - [Slides](https://github.com/TiagoRG/uaveiro-leci/blob/master/1ano/1semestre/fp/slides/tp03-functions.pdf) ## Aula 03 - [Slides](https://github.com/TiagoRG/uaveiro-leci/blob/master/1ano/1semestre/fp/slides/tp03-functions.pdf)
### Tópico principal da aula: Functions ### Tópico principal da aula: Functions
--- ---
*Pode conter erros, caso encontre algum, crie um* [*ticket*](https://github.com/TiagoRG/uaveiro-leci/issues/new) *Pode conter erros, caso encontre algum, crie um* [*ticket*](https://github.com/TiagoRG/uaveiro-leci/issues/new)

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'
@ -25,7 +25,7 @@ def bmiCategory(bmi):
# This is the main function # This is the main function
def main(): def main():
print("Índice de Massa Corporal") print("Índice de Massa Corporal")
altura = float(input("Altura (m)? ")) altura = float(input("Altura (m)? "))
if altura < 0: if altura < 0:
print("ERRO: altura inválida!") print("ERRO: altura inválida!")
@ -46,4 +46,4 @@ def main():
# Program starts executing here # Program starts executing here
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -1,26 +1,28 @@
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
MONTHDAYS = (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) MONTHDAYS = (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
days = MONTHDAYS[month] days = MONTHDAYS[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):
year += 1 year += 1
month = 1 month = 1
day = 1 day = 1
# Verifica se é o último dia do mês # Verifica se é o último dia do mês
elif (monthDays(year, month) == day): elif monthDays(year, month) == day:
month += 1 month += 1
day = 1 day = 1
# Dia comum # Dia comum
else: else:
day += 1 day += 1
@ -30,28 +32,29 @@ def nextDay(year, month, day):
# This is the main function # This is the main function
def main(): def main():
print("Was", 2017, "a leap year?", isLeapYear(2017)) # False? print("Was", 2017, "a leap year?", isLeapYear(2017)) # False?
print("Was", 2016, "a leap year?", isLeapYear(2016)) # True? print("Was", 2016, "a leap year?", isLeapYear(2016)) # True?
print("Was", 2000, "a leap year?", isLeapYear(2000)) # True? print("Was", 2000, "a leap year?", isLeapYear(2000)) # True?
print("Was", 1900, "a leap year?", isLeapYear(1900)) # False? print("Was", 1900, "a leap year?", isLeapYear(1900)) # False?
print("January 2017 had", monthDays(2017, 1), "days") # 31? print("January 2017 had", monthDays(2017, 1), "days") # 31?
print("February 2017 had", monthDays(2017, 2), "days") # 28? print("February 2017 had", monthDays(2017, 2), "days") # 28?
print("February 2016 had", monthDays(2016, 2), "days") # 29? print("February 2016 had", monthDays(2016, 2), "days") # 29?
print("February 2000 had", monthDays(2000, 2), "days") # 29? print("February 2000 had", monthDays(2000, 2), "days") # 29?
print("February 1900 had", monthDays(1900, 2), "days") # 28? print("February 1900 had", monthDays(1900, 2), "days") # 28?
y, m, d = nextDay(2017, 1, 30) 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) 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) 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) 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) 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

@ -1,6 +1,9 @@
#### Exercícios propostos no [CodeCheck](https://horstmann.com/codecheck/index.html) #### Exercícios propostos no [CodeCheck](https://horstmann.com/codecheck/index.html)
___ ___
## Ex 1. ## Ex 1.
height = 4.5<br /> height = 4.5<br />
width = 3<br /> width = 3<br />
volume1 = balloonVolume(width, height)<br /> volume1 = balloonVolume(width, height)<br />
@ -11,7 +14,9 @@ print("Change: ", change)<br />
change = balloonVolume(width + 2, height + 2) - volume2<br /> change = balloonVolume(width + 2, height + 2) - volume2<br />
print("Change: ", change) print("Change: ", change)
___ ___
## Ex 2. ## Ex 2.
def balloonVolume(width, height):<br /> def balloonVolume(width, height):<br />
&emsp;pi = 3.1415926<br /> &emsp;pi = 3.1415926<br />
&emsp;a = height / 2<br /> &emsp;a = height / 2<br />
@ -19,11 +24,15 @@ def balloonVolume(width, height):<br />
&emsp;volume = 4 * pi * a * c * c / 3<br /> &emsp;volume = 4 * pi * a * c * c / 3<br />
&emsp;return volume &emsp;return volume
___ ___
## Ex 3. ## Ex 3.
def hideCharacters(string) :<br /> def hideCharacters(string) :<br />
&emsp;return "*" * len(string) &emsp;return "*" * len(string)
___ ___
## Ex 4. ## Ex 4.
def isEven(n):<br /> def isEven(n):<br />
&emsp;if n % 2 == 0:<br /> &emsp;if n % 2 == 0:<br />
&emsp;&emsp;return True<br /> &emsp;&emsp;return True<br />
@ -39,7 +48,9 @@ def main() :<br />
<br /> <br />
main() main()
___ ___
## Ex 5. ## Ex 5.
def countSpaces(string):<br /> def countSpaces(string):<br />
&emsp;spaces = 0<br /> &emsp;spaces = 0<br />
&emsp;for char in string:<br /> &emsp;for char in string:<br />

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: '))
@ -21,4 +23,4 @@ def main():
if __name__ == "__main__": if __name__ == "__main__":
main() main()

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

@ -1,11 +1,16 @@
#### Exercícios propostos no [CodeCheck](https://horstmann.com/codecheck/index.html) #### Exercícios propostos no [CodeCheck](https://horstmann.com/codecheck/index.html)
___ ___
## Ex 10. ## Ex 10.
def hms2sec(h, m, s):<br /> def hms2sec(h, m, s):<br />
&emsp;sec = h * 3600 + m * 60 + s &emsp;sec = h * 3600 + m * 60 + s
&emsp;return sec &emsp;return sec
___ ___
## Ex 11. ## Ex 11.
def sec2hms(sec):<br /> def sec2hms(sec):<br />
&emsp;h = sec // 3600<br /> &emsp;h = sec // 3600<br />
&emsp;m = (sec // 60) % 60<br /> &emsp;m = (sec // 60) % 60<br />

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

@ -1,5 +1,7 @@
# Fundamentos de Programação # Fundamentos de Programação
## Aula 04 - [Slides](https://github.com/TiagoRG/uaveiro-leci/blob/master/1ano/1semestre/fp/slides/tp04-iteration.pdf) ## Aula 04 - [Slides](https://github.com/TiagoRG/uaveiro-leci/blob/master/1ano/1semestre/fp/slides/tp04-iteration.pdf)
### Tópico principal da aula: Iteration, Loops ### Tópico principal da aula: Iteration, Loops
--- ---
*Pode conter erros, caso encontre algum, crie um* [*ticket*](https://github.com/TiagoRG/uaveiro-leci/issues/new) *Pode conter erros, caso encontre algum, crie um* [*ticket*](https://github.com/TiagoRG/uaveiro-leci/issues/new)

View File

@ -4,7 +4,7 @@ def main():
div_list_array = divList(n) div_list_array = divList(n)
div_list = ", ".join(div_list_array) div_list = ", ".join(div_list_array)
print(f""" 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 # 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
@ -35,7 +37,8 @@ def category(n, divs):
total += int(div) total += int(div)
if total < n: return 'deficiente' if total < n: return 'deficiente'
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

@ -1,9 +1,9 @@
# This program generates 20 terms of a sequence by a recurrence relation. # 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 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,39 +2,40 @@
# 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[."""
for year in listLeapYears(year1, year2): for year in listLeapYears(year1, year2):
print(year) print(year)
def numLeapYears(year1, year2): def numLeapYears(year1, year2):
"""Return the number of leap years in range [year1, year2[.""" """Return the number of leap years in range [year1, year2[."""
return len(listLeapYears(year1, year2)) return len(listLeapYears(year1, year2))
def listLeapYears(year1, year2): def listLeapYears(year1, year2):
"""Return a list of leap years in range [year1, year2[.""" """Return a list of leap years in range [year1, year2[."""
# (We'll get back to lists later in the course.) # (We'll get back to lists later in the course.)
lst = [] lst = []
for year in range(year1, year2): for year in range(year1, year2):
if isLeapYear(year): if isLeapYear(year):
lst.append(year) lst.append(year)
return lst return lst
# MAIN PROGRAM: # MAIN PROGRAM:
def main(): def main():
printLeapYears(1870, 1921) printLeapYears(1870, 1921)
x = numLeapYears(1679, 2079) x = numLeapYears(1679, 2079)
print("In [1679, 2079[ there are", x, "leap years") print("In [1679, 2079[ there are", x, "leap years")
print(listLeapYears(1970, 2002)) print(listLeapYears(1970, 2002))
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -3,17 +3,19 @@
def inputTotal(): def inputTotal():
"""Read numbers until empty string is entered and return the sum.""" """Read numbers until empty string is entered and return the sum."""
tot = 0.0 tot = 0.0
while True: while True:
n = input("valor? ") # input("valor? ") n = input("valor? ") # input("valor? ")
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

@ -4,7 +4,8 @@
# For a summary of the available methods: # For a summary of the available methods:
# https://runestone.academy/runestone/books/published/thinkcspy/PythonTurtle/SummaryofTurtleMethods.html # 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 # Make turtle t draw a square with the given side length
def square(t, side): def square(t, side):
@ -12,6 +13,7 @@ def square(t, side):
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).
@ -26,24 +28,24 @@ def spiral(t, start, end, incr):
t.forward(start) t.forward(start)
t.left(90) t.left(90)
start += incr start += incr
def main(): def main():
print("This program opens a window with a graphical user interface.") print("This program opens a window with a graphical user interface.")
wn = turtle.Screen() # creates a graphics window wn = turtle.Screen() # creates a graphics window
alex = turtle.Turtle() # create a turtle named alex alex = turtle.Turtle() # create a turtle named alex
alex.forward(150) # tell alex to move forward by 150 units alex.forward(150) # tell alex to move forward by 150 units
alex.right(90) # turn by 90 degrees alex.right(90) # turn by 90 degrees
alex.forward(75) # complete the second side alex.forward(75) # complete the second side
beth = turtle.Turtle() # another turtle beth = turtle.Turtle() # another turtle
beth.shape("turtle") # with another shape beth.shape("turtle") # with another shape
beth.color("blue") # and color beth.color("blue") # and color
beth.up() # pen up beth.up() # pen up
beth.goto(-200, -100) # move to given point beth.goto(-200, -100) # move to given point
beth.down() # pen down beth.down() # pen down
square(beth, 100) # draw a square square(beth, 100) # draw a square
# This should draw a spiral # This should draw a spiral
alex.up() alex.up()
@ -57,7 +59,7 @@ def main():
alex.down() alex.down()
spiral(alex, 200, 0, -5) 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!") print("The window was closed. Bye!")

View File

@ -1,5 +1,7 @@
# Fundamentos de Programação # Fundamentos de Programação
## Aula 05 - [Slides](https://github.com/TiagoRG/uaveiro-leci/blob/master/1ano/1semestre/fp/slides/tp05-sequences.pdf) ## Aula 05 - [Slides](https://github.com/TiagoRG/uaveiro-leci/blob/master/1ano/1semestre/fp/slides/tp05-sequences.pdf)
### Tópico principal da aula: Tuples, Lists ### Tópico principal da aula: Tuples, Lists
--- ---
*Pode conter erros, caso encontre algum, crie um* [*ticket*](https://github.com/TiagoRG/uaveiro-leci/issues/new) *Pode conter erros, caso encontre algum, crie um* [*ticket*](https://github.com/TiagoRG/uaveiro-leci/issues/new)

View File

@ -16,4 +16,4 @@ def allMatches(teamList):
if __name__ == "__main__": if __name__ == "__main__":
main() main()

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

@ -2,11 +2,11 @@ def main():
s = input('Introduza uma string >> ') s = input('Introduza uma string >> ')
print(ispalindrome(s)) print(ispalindrome(s))
def ispalindrome(s): def ispalindrome(s):
pal_s = s[::-1] pal_s = s[::-1]
return pal_s == s return pal_s == s
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -9,6 +9,7 @@ def shorten(string):
if char.isupper(): if char.isupper():
abv += char abv += char
return abv return abv
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -19,22 +19,23 @@ 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']
nameList = ['Angelina', 'Brad', 'Claudia', 'Bruna'] nameList = ['Angelina', 'Brad', 'Claudia', 'Bruna']
# 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']
@ -25,4 +24,4 @@ print(week[2:])
# E para obter os dias úteis de dois em dois ['seg', 'qua', 'sex']? # E para obter os dias úteis de dois em dois ['seg', 'qua', 'sex']?
print(week[2::2]) print(week[2::2])
# JMR@ua.pt 2021 # JMR@ua.pt 2021

View File

@ -20,4 +20,4 @@ train2 = [4, 6, 5]
train += train2 train += train2
print(train) print(train)
# JMR@ua.pt # JMR@ua.pt

View File

@ -15,18 +15,20 @@ 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]
train3 = [14, 34, 24] train3 = [14, 34, 24]
print(train1, train2, train3) print(train1, train2, train3)
print('\nTesting passengers') print('\nTesting passengers')
print(passengers(train1, 2)) print(passengers(train1, 2))
print(passengers(train2, 1)) print(passengers(train2, 1))
print(passengers(train3, 0)) print(passengers(train3, 0))
# Run tests: # Run tests:
test() test()
# JMR@ua.pt 2021 # JMR@ua.pt 2021

View File

@ -6,13 +6,14 @@
def transfer1car(t1, t2): 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]
train3 = [14, 34, 24] train3 = [14, 34, 24]
print(train1, train2, train3) print(train1, train2, train3)
print("\nTesting transfer1car") print("\nTesting transfer1car")
transfer1car(train1, train2) transfer1car(train1, train2)
print(train1, train2, train3) print(train1, train2, train3)
@ -20,8 +21,9 @@ def test():
print(train1, train2, train3) print(train1, train2, train3)
transfer1car(train3, train1) transfer1car(train3, train1)
print(train1, train2, train3) print(train1, train2, train3)
# Run tests: # Run tests:
test() test()
# JMR@ua.pt 2021 # JMR@ua.pt 2021

View File

@ -17,13 +17,14 @@ def match(t1, t2, g1, g2):
else: else:
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]
team3 = ["Juventus", 0, 0, 0] team3 = ["Juventus", 0, 0, 0]
print(team1, team2, team3) print(team1, team2, team3)
match(team1, team2, 2, 1) match(team1, team2, 2, 1)
print(team1, team2, team3) print(team1, team2, team3)
match(team2, team3, 1, 1) match(team2, team3, 1, 1)
@ -31,7 +32,8 @@ 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()
# JMR@ua.pt 2021 # JMR@ua.pt 2021

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,20 +19,22 @@ 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()
print("natal:", natal) print("natal:", natal)
p1 = inputPerson("Introduza os dados de p1") p1 = inputPerson("Introduza os dados de p1")
print("p1:", p1) print("p1:", p1)
p2 = inputPerson("Introduza os dados de p2") p2 = inputPerson("Introduza os dados de p2")
print("p2:", p2) print("p2:", p2)
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()
# JMR@ua.pt 2021 # JMR@ua.pt 2021

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).
@ -23,4 +25,4 @@ def parseDMY(s):
# No CodeCheck estas funções são testadas com argumentos pré-programados. # 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. # Se quiser testar offline, tem de acrescentar as suas intruções de chamada.
# JMR@ua.pt 2021 # JMR@ua.pt 2021

View File

@ -1,5 +1,7 @@
# Fundamentos de Programação # Fundamentos de Programação
## Aula 06 - [Slides](https://github.com/TiagoRG/uaveiro-leci/blob/master/1ano/1semestre/fp/slides/tp06-files+args+exceptions.pdf) ## Aula 06 - [Slides](https://github.com/TiagoRG/uaveiro-leci/blob/master/1ano/1semestre/fp/slides/tp06-files+args+exceptions.pdf)
### Tópico principal da aula: Files, Exceptions ### Tópico principal da aula: Files, Exceptions
--- ---

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

@ -4,10 +4,10 @@ from tkinter import filedialog
def main(): def main():
# 1) Pedir nome do ficheiro (usando alternativa #B): # 1) Pedir nome do ficheiro (usando alternativa #B):
name = filedialog.askopenfilename(title="Choose File") name = filedialog.askopenfilename(title="Choose File")
# 2) Calcular soma dos números no ficheiro: # 2) Calcular soma dos números no ficheiro:
total = fileSum(name) total = fileSum(name)
# 3) Mostrar a soma: # 3) Mostrar a soma:
print("Sum:", total) print("Sum:", total)

View File

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

View File

@ -34,7 +34,7 @@ def main():
loadFile("datafiles/school1.csv", lst) loadFile("datafiles/school1.csv", lst)
loadFile("datafiles/school2.csv", lst) loadFile("datafiles/school2.csv", lst)
loadFile("datafiles/school3.csv", lst) loadFile("datafiles/school3.csv", lst)
# ordenar a lista # ordenar a lista
lst.sort() lst.sort()
# mostrar a pauta # mostrar a pauta
@ -44,5 +44,3 @@ def main():
# Call main function # Call main function
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -1,5 +1,7 @@
# Fundamentos de Programação # Fundamentos de Programação
## Aula 07 - [Slides](https://github.com/TiagoRG/uaveiro-leci/blob/master/1ano/1semestre/fp/slides/tp07-dictionaries.pdf) ## Aula 07 - [Slides](https://github.com/TiagoRG/uaveiro-leci/blob/master/1ano/1semestre/fp/slides/tp07-dictionaries.pdf)
### Tópico principal da aula: Dictionaries ### Tópico principal da aula: Dictionaries
--- ---

View File

@ -1,20 +1,21 @@
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
partidas = allMatches(equipas) # cria a lista de partidas partidas = allMatches(equipas) # cria a lista de partidas
resultados = getResults(partidas) # pede os resultados ao utilizador resultados = getResults(partidas) # pede os resultados ao utilizador
tabela = getTable(equipas, resultados) # cria a tabela de classificação 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(): def getTeams():
teams = [] # cria uma lista vazia para as equipas teams = [] # cria uma lista vazia para as equipas
while True: # Ciclo para obter as equipas while True: # Ciclo para obter as equipas
team = input("Nome da equipa: ") 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 continue
if team == "": if team == "":
if len(teams) < 2: if len(teams) < 2:
@ -26,25 +27,25 @@ def getTeams():
def getResults(matches): 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: for match in matches:
team1, team2 = match # desempacota a partida team1, team2 = match # desempacota a partida
print("Resultado do jogo entre", team1, "e", team2) print("Resultado do jogo entre", team1, "e", team2)
goals1 = int(input("Golos da equipa 1: ")) goals1 = int(input("Golos da equipa 1: "))
goals2 = int(input("Golos da equipa 2: ")) 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 return results
def getTable(teams, 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: 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: for match in results:
team1, team2 = match # desempacota a partida team1, team2 = match # desempacota a partida
goals1, goals2 = results[match] # desempacota os resultados goals1, goals2 = results[match] # desempacota os resultados
# atualiza os resultados da equipa 1 # atualiza os resultados da equipa 1
updateStats(table, team1, goals1, goals2) 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. # 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][3] += gm # adiciona os golos marcados table[team][math.trunc(2 - points / 2)] += 1 # determina o index ao qual atribui o jogo (V/E/D)
table[team][4] += gs # adiciona os golos marcados table[team][3] += gm # 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,11 +56,11 @@ 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):
"""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 # You may want to change this to produce a more user-friendly
# representation such as "4x200+3x50+1x5+3x1=958". # representation such as "4x200+3x50+1x5+3x1=958".
string = "" string = ""
@ -82,29 +81,29 @@ def main():
assert value({1: 7, 5: 2, 20: 4, 100: 1}) == 197 assert value({1: 7, 5: 2, 20: 4, 100: 1}) == 197
# Test the strbag function. # 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(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("bag1:", strbag(bag1)) # bag1: 1x200+2x100+4x50+5x20+1x5+4x1=709
print("bag2:", strbag(bag2)) # bag2: =0 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(transfer1coin(bag1, 20, bag2)) # True print(transfer1coin(bag1, 10, bag2)) # False!
print("bag1:", strbag(bag1)) # bag1: 1x200+2x100+4x50+4x20+1x5+4x1=689 print("bag1:", strbag(bag1)) # bag1: 1x200+2x100+4x50+5x20+1x5+4x1=709
print("bag2:", strbag(bag2)) # bag2: 1x20=20 print("bag2:", strbag(bag2)) # bag2: =0
print(transfer1coin(bag1, 20, bag2)) # True print(transfer1coin(bag1, 20, bag2)) # True
print("bag1:", strbag(bag1)) # bag1: 1x200+2x100+4x50+3x20+1x5+4x1=669 print("bag1:", strbag(bag1)) # bag1: 1x200+2x100+4x50+4x20+1x5+4x1=689
print("bag2:", strbag(bag2)) # bag2: 2x20=40 print("bag2:", strbag(bag2)) # bag2: 1x20=20
print(transfer(bag1, 157, bag2)) # True (should be easy) print(transfer1coin(bag1, 20, bag2)) # True
print("bag1:", strbag(bag1)) # bag1: 1x200+1x100+3x50+3x20+2x1=512 print("bag1:", strbag(bag1)) # bag1: 1x200+2x100+4x50+3x20+1x5+4x1=669
print("bag2:", strbag(bag2)) # bag2: 1x100+1x50+2x20+1x5+2x1=197 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("bag1:", strbag(bag1))
print("bag2:", strbag(bag2)) print("bag2:", strbag(bag2))
@ -113,4 +112,3 @@ def main():
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -3,11 +3,11 @@ import sys
def main(): def main():
letters = countLetters(sys.argv[1]) letters = countLetters(sys.argv[1])
# Print the results # Print the results
for c in sorted(letters.keys()): for c in sorted(letters.keys()):
print(c, letters[c]) print(c, letters[c])
# Print the most used letter and the number of times it's used # Print the most used letter and the number of times it's used
usedTheMostCount = max(letters.values()) usedTheMostCount = max(letters.values())
usedTheMost = [letter for letter in letters.keys() if letters[letter] == usedTheMostCount][0] usedTheMost = [letter for letter in letters.keys() if letters[letter] == usedTheMostCount][0]
@ -24,7 +24,7 @@ def countLetters(filename):
if c not in letters: if c not in letters:
letters[c] = 0 letters[c] = 0
letters[c] += 1 letters[c] += 1
# Returns the dictionary with the letters # Returns the dictionary with the letters
return letters return letters

View File

@ -9,6 +9,7 @@ value = input("Enter value: ")
# Última vez (quando aparecer 0 em Key: # Última vez (quando aparecer 0 em Key:
print(data[3]) print(data[3])
``` ```
<div style="text-align: center"> <div style="text-align: center">
| Key | Value | Size | Output | | Key | Value | Size | Output |
@ -19,4 +20,5 @@ print(data[3])
| 3 | Y | 3 | | | 3 | Y | 3 | |
| 7 | Q | 4 | | | 7 | Q | 4 | |
| 0 | | | Y | | 0 | | | Y |
</div> </div>

View File

@ -1,5 +1,7 @@
# Fundamentos de Programação # Fundamentos de Programação
## Aula 08 - [Slides 1](https://github.com/TiagoRG/uaveiro-leci/blob/master/1ano/1semestre/fp/slides/tp08-comprehensions.pdf) - [Slides 2](https://github.com/TiagoRG/uaveiro-leci/blob/master/1ano/1semestre/fp/slides/tp08-sets.pdf) ## Aula 08 - [Slides 1](https://github.com/TiagoRG/uaveiro-leci/blob/master/1ano/1semestre/fp/slides/tp08-comprehensions.pdf) - [Slides 2](https://github.com/TiagoRG/uaveiro-leci/blob/master/1ano/1semestre/fp/slides/tp08-sets.pdf)
### Tópicos principais da aula: List Comprehensions, Sets ### Tópicos principais da aula: List Comprehensions, Sets
--- ---

View File

@ -1,17 +1,16 @@
# 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():
# Lista de pessoas com nome, peso em kg, altura em metro. # Lista de pessoas com nome, peso em kg, altura em metro.
people = [("John", 64.5, 1.757), people = [("John", 64.5, 1.757),
("Berta", 64.0, 1.612), ("Berta", 64.0, 1.612),
("Maria", 45.1, 1.715), ("Maria", 45.1, 1.715),
("Andy", 98.3, 1.81), ("Andy", 98.3, 1.81),
("Lisa", 46.8, 1.622), ("Lisa", 46.8, 1.622),
("Kelly", 83.2, 1.78)] ("Kelly", 83.2, 1.78)]
print("People:", people) print("People:", people)
@ -19,7 +18,7 @@ def main():
names = [n for n, w, h in people] names = [n for n, w, h in people]
# = [p[0] for p in people] # equivalente # = [p[0] for p in people] # equivalente
print("Names:", names) print("Names:", names)
# Usando list comprehensions, obtenha: # Usando list comprehensions, obtenha:
# a) Uma lista com os valores de imc de todas as pessoas. # a) Uma lista com os valores de imc de todas as pessoas.
imcs = [imc(w, h) for n, w, h in people] 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. # 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] 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. # 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] midimc = [n for n, w, h in people if 18 <= imc(w, h) <= 25]

View File

@ -1,4 +1,3 @@
def main(): def main():
A = "reading" A = "reading"
B = "eating" B = "eating"
@ -16,7 +15,7 @@ def main():
"Paolo": {B, D, F}, "Paolo": {B, D, F},
"Frank": {D, B, E, F, A}, "Frank": {D, B, E, F, A},
"Teresa": {F, H, C, D} "Teresa": {F, H, C, D}
} }
print("a) Table of common interests:") print("a) Table of common interests:")
commoninterests = {(p1, p2): interests[p1].intersection(interests[p2]) commoninterests = {(p1, p2): interests[p1].intersection(interests[p2])

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,5 +1,7 @@
# Fundamentos de Programação # Fundamentos de Programação
## Aula 09 - [Slides](https://github.com/TiagoRG/uaveiro-leci/blob/master/1ano/1semestre/fp/slides/tp09-searching+sorting.pdf) ## Aula 09 - [Slides](https://github.com/TiagoRG/uaveiro-leci/blob/master/1ano/1semestre/fp/slides/tp09-searching+sorting.pdf)
### Tópicos principais da aula: Searching, Sorting, Lambda Expressions ### Tópicos principais da aula: Searching, Sorting, Lambda Expressions
--- ---

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

@ -3,7 +3,7 @@ import sys
def main(): def main():
letters = countLetters(sys.argv[1]) letters = countLetters(sys.argv[1])
# Print the results # Print the results
for c in sorted(letters, key=letters.get, reverse=True): for c in sorted(letters, key=letters.get, reverse=True):
print(c, letters[c]) print(c, letters[c])
@ -25,7 +25,7 @@ def countLetters(filename):
if c not in letters: if c not in letters:
letters[c] = 0 letters[c] = 0
letters[c] += 1 letters[c] += 1
# Returns the dictionary with the letters # Returns the dictionary with the letters
return letters return letters

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.
@ -7,7 +6,7 @@ def insertionSort(lst, key=None):
# Traverse elements starting at position 1 # Traverse elements starting at position 1
for i in range(1, len(lst)): for i in range(1, len(lst)):
# We know that lst[:i] is sorted # 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 # Elements in lst[:i] that are > x must move one position ahead
j = i - 1 j = i - 1
while j >= 0 and (key(lst[j]) > key(x) if key else lst[j] > x): 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) 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,26 +14,26 @@ 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():
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:") print("\nTestes à função polynomial2:")
p = polynomial2(1, 2, 3) # creates p(x)=x²+2x+3 p = polynomial2(1, 2, 3) # creates p(x)=x²+2x+3
print([p(x) for x in xx]) # [3, 6, 11, 18] print([p(x) for x in xx]) # [3, 6, 11, 18]
q = polynomial2(2, 0, -2) # creates q(x)=2x²-2 q = polynomial2(2, 0, -2) # creates q(x)=2x²-2
print([q(x) for x in xx]) # [-2, 0, 6, 16] print([q(x) for x in xx]) # [-2, 0, 6, 16]
print("\nTestes à função polynomial:") print("\nTestes à função polynomial:")
r = polynomial([1, 2, 3]) # same as p(x) r = polynomial([1, 2, 3]) # same as p(x)
print([r(x) for x in xx]) # [3, 6, 11, 18] 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__": 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/)
@ -32,23 +31,22 @@ N, V, E, D, GM, GS = 0, 1, 2, 3, 4, 5
def printTabela(tabela): def printTabela(tabela):
print() print()
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

@ -1,5 +1,7 @@
# Fundamentos de Programação # Fundamentos de Programação
## Aula 10 - [Slides](https://github.com/TiagoRG/uaveiro-leci/blob/master/1ano/1semestre/fp/slides/tp10-Recursion.pdf) ## Aula 10 - [Slides](https://github.com/TiagoRG/uaveiro-leci/blob/master/1ano/1semestre/fp/slides/tp10-Recursion.pdf)
### Tópicos principais da aula: Recursive Functions ### Tópicos principais da aula: Recursive Functions
--- ---

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

@ -16,7 +16,7 @@ def traced(func):
traced.indent += u"\u2502 " traced.indent += u"\u2502 "
print(u"{}{}{!r}{!r}".format(indent, func.__name__, args, kwargs)) print(u"{}{}{!r}{!r}".format(indent, func.__name__, args, kwargs))
try: try:
r = func(*args, **kwargs) # CALL the func! r = func(*args, **kwargs) # CALL the func!
return r return r
except Exception as e: except Exception as e:
r = e r = e
@ -25,26 +25,27 @@ def traced(func):
if traced.indent != None: if traced.indent != None:
print(u"{}\u2514>{!r}".format(indent, r)) print(u"{}\u2514>{!r}".format(indent, r))
traced.indent = indent # restore indentation traced.indent = indent # restore indentation
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

@ -4,27 +4,27 @@ def isLeapYear(year):
def monthDays(year, month): def monthDays(year, month):
assert month > 0 assert month > 0
MONTHDAYS = (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) MONTHDAYS = (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
days = MONTHDAYS[month] days = MONTHDAYS[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):
if not dateIsValid(year, month, day): return if not dateIsValid(year, month, day): return
# Verifica se é o último dia do ano # Verifica se é o último dia do ano
if (month, day) == (12, 31): if (month, day) == (12, 31):
year += 1 year += 1
month = 1 month = 1
day = 1 day = 1
# Verifica se é o último dia do mês # Verifica se é o último dia do mês
elif (monthDays(year, month) == day): elif (monthDays(year, month) == day):
month += 1 month += 1
day = 1 day = 1
# Dia comum # Dia comum
else: else:
day += 1 day += 1
@ -38,20 +38,20 @@ def dateIsValid(year, month, day):
def previousDay(year, month, day): def previousDay(year, month, day):
if not dateIsValid(year, month, day): return if not dateIsValid(year, month, day): return
# Primeiro dia do ano # Primeiro dia do ano
if (month, day) == (1, 1): if (month, day) == (1, 1):
year -= 1 year -= 1
month = 12 month = 12
day = 31 day = 31
# Primeiro dia do mês (sem ser janeiro) # Primeiro dia do mês (sem ser janeiro)
elif day == 1: elif day == 1:
day = monthDays(year, month - 1) day = monthDays(year, month - 1)
month -= 1 month -= 1
# Dia comum # Dia comum
else: else:
day -= 1 day -= 1
return year, month, day return year, month, day

View File

@ -7,20 +7,21 @@ def loadDataBase(fname, produtos):
"""Lê dados do ficheiro fname e atualiza/acrescenta a informação num """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), ...}. 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 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')[
productComponents = product.split(';') # Divide as componentes do produto (código, nome, secção, preço, iva) 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: if len(productComponents) != 5:
continue continue
produtos.update({productComponents[0]: ( # Atualiza a entrada de uma determinada chave (código) produtos.update({productComponents[0]: ( # Atualiza a entrada de uma determinada chave (código)
productComponents[1], # Nome productComponents[1], # Nome
productComponents[2], # Secção productComponents[2], # Secção
float(productComponents[3]), # Preço float(productComponents[3]), # Preço
float(productComponents[4].strip('%')) / 100 # IVA float(productComponents[4].strip('%')) / 100 # IVA
)}) )})
@ -29,13 +30,14 @@ 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:
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: 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 # Caso a segunda parcela da entrada não seja um número, é pedido ao utilizador para introduzir o código de novo
try: try:
@ -45,37 +47,39 @@ def registaCompra(produtos):
continue continue
if code in produtos: 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] = 0
compra[code] += amount # Adiciona ao dicionário da compra a quantidade comprada do produto 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 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? ')
compra["totals"][2] += compra["totals"][0] + compra["totals"][1] # Calcula o total liquido da compra compra["totals"][2] += compra["totals"][0] + compra["totals"][1] # Calcula o total liquido da compra
return compra # Devolve a lista return compra # Devolve a lista
def fatura(produtos, compra): 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:
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 # 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]) 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 # 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}
@ -91,7 +95,7 @@ def main(args):
# Juntar bases de dados opcionais (Não altere) # Juntar bases de dados opcionais (Não altere)
for arg in args: for arg in args:
loadDataBase(arg, produtos) loadDataBase(arg, produtos)
# Use este código para mostrar o menu e ler a opção repetidamente # Use este código para mostrar o menu e ler a opção repetidamente
MENU = "(C)ompra (F)atura (S)air ? " MENU = "(C)ompra (F)atura (S)air ? "
compras = {} compras = {}
@ -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

@ -74,7 +74,7 @@ def fatura(calls: dict, phone_number: str) -> None:
if phone_number not in calls: if phone_number not in calls:
print("Cliente não existe\n") print("Cliente não existe\n")
return return
total = 0 total = 0
print("Fatura do cliente", phone_number) 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: 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__':
main() 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,11 +56,11 @@ 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])
or ('2' in bet and game[3] < game[4]) or ('2' in bet and game[3] < game[4])
) else 'ERRADO' ) else 'ERRADO'
if result == 'CERTO': if result == 'CERTO':
right_bets_count += 1 right_bets_count += 1
@ -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)

File diff suppressed because one or more lines are too long

View File

@ -13,9 +13,9 @@ with open("twitter.json", encoding="utf8") as f:
twits = json.load(f) twits = json.load(f)
# Analise os resultados impressos para perceber a estrutura dos dados. # Analise os resultados impressos para perceber a estrutura dos dados.
print(type(twits)) # deve indicar que é uma lista! print(type(twits)) # deve indicar que é uma lista!
print(type(twits[0])) # cada elemento da lista é um dicionário. print(type(twits[0])) # cada elemento da lista é um dicionário.
print(twits[0].keys()) # mostra as chaves no primeiro elemento. print(twits[0].keys()) # mostra as chaves no primeiro elemento.
# Cada elemento contém uma mensagem associada à chave "text": # Cada elemento contém uma mensagem associada à chave "text":
print(twits[0]["text"]) print(twits[0]["text"])
@ -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.
@ -6,9 +5,9 @@
def longestPrefixRepeated(s): 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]
return longest return longest

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

Some files were not shown because too many files have changed in this diff Show More