Merge pull request #64 from TiagoRG/dev-tiagorg

Fundamentos de Programação:
- [FP] Code reformat
- Revert "[FP] Code reformat"
- [FP] Code reformat
- [FP] Quick simplifications

Laboratório de Sistemas Digitais:
- [LSD] Main README update

Laboratórios de Informática:
- [LABI] tema05 part1 added
- [LABI] guides for tema06 added
This commit is contained in:
Tiago Garcia 2023-05-19 16:17:26 +01:00 committed by GitHub
commit 4a411bd3de
Signed by untrusted user who does not match committer: TiagoRG
GPG Key ID: DFCD48E3F420DB42
99 changed files with 531 additions and 377 deletions

View File

@ -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)

View File

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

View File

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

View File

@ -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)}°')
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
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)

View File

@ -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

View File

@ -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,13 +10,13 @@ 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"

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)
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)]

View File

@ -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):

View File

@ -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")

View File

@ -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'

View File

@ -1,6 +1,7 @@
def isLeapYear(year):
return year % 400 == 0 if year % 100 == 0 else year % 4 == 0
def monthDays(year, month):
assert month > 0
@ -9,6 +10,7 @@ def monthDays(year, month):
return days + 1 if (isLeapYear(year) and month == 2) else days
def nextDay(year, month, day):
# Verifica se é o último dia do ano
if (month, day) == (12, 31):
@ -30,27 +32,28 @@ 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("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("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__":

View File

@ -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: '))

View File

@ -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)))

View File

@ -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))
try:
print(intersects(a1, b1, a2, b2))
except AssertionError as e:
print(e)
main()

View File

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

View File

@ -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()

View File

@ -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():

View File

@ -20,6 +20,7 @@ Este é um número {category(n, div_list_array)}.
""")
# Obtém uma lista com todos os dividores de um número
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
@ -37,5 +39,6 @@ def category(n, divs):
if total == n: return 'perfeito'
if total > n: return 'abundante'
if __name__ == "__main__":
main()

View File

@ -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()

View File

@ -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()

View File

@ -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()

View File

@ -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}
""")

View File

@ -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()

View File

@ -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')

View File

@ -1,7 +1,7 @@
# Show a table of the squares of the first four numbers
print(" {:1s} | {:>3s} | {:>7s}".format("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.

View File

@ -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 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 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()
main()

View File

@ -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()
main()

View File

@ -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()
main()

View File

@ -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).
@ -30,20 +32,20 @@ def spiral(t, start, end, 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!")

View File

@ -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

View File

@ -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()

View File

@ -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__":

View File

@ -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']

View File

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

View File

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

View File

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

View File

@ -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,6 +19,7 @@ def inputPerson(msg):
birth = inputDate()
return (name, birth)
def test():
print("Natal de 2020")
natal = inputDate()
@ -31,6 +33,7 @@ def test():
older = p1[1] < p2[1]
print("p1 é mais velha que p2:", older)
# Run tests:
test()

View File

@ -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).

View File

@ -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__":

View File

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

View File

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

View File

@ -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:

View File

@ -37,7 +37,6 @@ def transfer(bag1, amount, bag2):
def transferProcess(bag1, amount, bag2, coins):
bagBackup = (bag1.copy(), bag2.copy())
amountBackup = amount
@ -57,7 +56,7 @@ 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):
@ -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("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(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+4x20+1x5+4x1=689
print("bag2:", strbag(bag2)) # bag2: 1x20=20
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, 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+3x20+1x5+4x1=669
print("bag2:", strbag(bag2)) # bag2: 2x20=40
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, 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(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()

View File

@ -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)

View File

@ -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])

View File

@ -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

View File

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

View File

@ -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):

View File

@ -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()

View File

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

View File

@ -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]

View File

@ -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()

View File

@ -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)

View File

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

View File

@ -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()

View File

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

View File

@ -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__":

View File

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

View File

@ -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)

View File

@ -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
@ -28,23 +28,24 @@ def traced(func):
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)

View File

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

View File

@ -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}
@ -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:])

View File

@ -98,7 +98,9 @@ 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__':

View File

@ -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)

View File

@ -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)}")

View File

@ -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.

View File

@ -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

View File

@ -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.

View File

@ -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.
@ -7,7 +6,7 @@ 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]

View File

@ -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}%")

View File

@ -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

View File

@ -14,6 +14,7 @@ Se não, deve devolver a quantidade que não conseguiu descarregar.
"""
# Se w=['coal', 45], então w[0]='coal' e w[1]=45.
def unload(t, m, q):
@ -30,20 +31,20 @@ def unload(t, m, q):
def main():
t = eval(input())
t = eval(input())
print("t: ", t)
q = unload(t, "rice", 40)
print("unload(t, 'rice', 40) ->", q)
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, "coal", 50)
print("unload(t, 'coal', 50) ->", q)
print("t: ", t)
q = unload(t, "iron", 20)
print("unload(t, 'iron', 20) ->", q)
print("t: ", t)
q = unload(t, "iron", 20)
print("unload(t, 'iron', 20) ->", q)
if __name__ == "__main__":
main()
main()

View File

@ -4,7 +4,7 @@ Por exemplo, onlyCaps("John Fitzgerald Kennedy") deve devolver "JFK".
A solução tem de ser recursiva e não pode usar ciclos.
"""
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:]))

View File

@ -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

View File

@ -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)

View File

@ -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"])

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Exemplo HTML 1</title>
</head>
<body>
<h1>Exemplo HTML 1</h1>
</body>
</html>

View File

@ -0,0 +1,10 @@
import cherrypy
class HelloWorld(object):
@cherrypy.expose
def index(self):
return "You have successfully reached " + cherrypy.request.headers["Host"]
cherrypy.quickstart(HelloWorld())

View File

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form 1</title>
</head>
<body>
<form action="actions/do_login" method="post">
<p>Username</p>
<input type="text" name="username" value="" size="15" maxlength="40"/>
<p>Password</p>
<input type="password" name="password" value="" size="10" maxlength="40"/>
<p><input type="submit" value="Login"/></p>
<p><input type="reset" value="Clear"/></p>
</form>
</body>
</html>

View File

@ -0,0 +1,5 @@
import requests
f = requests.get("https://www.ua.pt")
print(f.text)

View File

@ -0,0 +1,7 @@
import requests
url = "http://127.0.0.1:8080/form"
data = {"username": "admin", "password": "admin"}
f = requests.post(url, data=data)
print(f.status_code)

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -1,4 +1,4 @@
# Laboratórios de Sistemas Digitais
# Laboratório de Sistemas Digitais
### Projetos, exercícios e material organizados por aulas
---
@ -12,6 +12,8 @@
| [05](https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/2semestre/lsd/pratica05) | Parametrização de componentes |
| [06](https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/2semestre/lsd/pratica06) | Modelação em VHDL e implementação de registos e módulos combinatórios de deslocamento |
| [07](https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/2semestre/lsd/pratica07) | Construção e utilização de testbenches em VHDL<br>Simulação comportamental e temporal<br>Depuração de circuitos em FPGA |
| [08](https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/2semestre/lsd/pratica08) | Modelação, simulação e síntese de Máquinas de Estados Finitos<br>Aspetos gerais e modelo de Moore |
| [09](https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/2semestre/lsd/pratica09) | Modelação, simulação e síntese de Máquinas de Estados Finitos - Modelo de Mealy<br>MEFs comunicantes |
| [10](https://github.com/TiagoRG/uaveiro-leci/tree/master/1ano/2semestre/lsd/pratica10) | Modelação em VHDL de Memórias ROM e RAM de um Porto e Multi-porto |
---
*Pode conter erros, caso encontre algum, crie um* [*ticket*](https://github.com/TiagoRG/uaveiro-leci/issues/new)