Refractoring and files reformat

This commit is contained in:
TiagoRG 2023-01-30 16:48:43 +00:00
parent b50f73d1b3
commit e552fdf07e
Signed by untrusted user who does not match committer: TiagoRG
GPG Key ID: DFCD48E3F420DB42
18 changed files with 145 additions and 135 deletions

View File

@ -1,5 +1,6 @@
import math import math
def main(): def main():
print("""Introduza as coordenadas (x, y) do dardo. print("""Introduza as coordenadas (x, y) do dardo.
Representa as posicoes horizontal e vertical respetivamente. Representa as posicoes horizontal e vertical respetivamente.
@ -23,7 +24,7 @@ Ambas em milimetros.
return return
score = BasePoint(x, y) score = BasePoint(x, y)
if mod > 99 and mod < 107: if 99 < mod < 107:
score *= 3 score *= 3
if mod > 162: if mod > 162:
score *= 2 score *= 2
@ -31,6 +32,7 @@ Ambas em milimetros.
print(f'Pontuacao: {score} pontos.') print(f'Pontuacao: {score} pontos.')
exit(1) exit(1)
def BasePoint(x, y): def BasePoint(x, y):
angleRad = math.atan2(y, x) angleRad = math.atan2(y, x)
angleDeg = math.degrees(angleRad) - 9 angleDeg = math.degrees(angleRad) - 9
@ -39,5 +41,6 @@ def BasePoint(x, y):
return POINTS[int(angleDeg / 20)] return POINTS[int(angleDeg / 20)]
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,6 +1,2 @@
n = int(input('numero? ')) n = int(input('numero? '))
print("par" if n % 2 == 0 else "impar")
if n % 2 == 0:
print('par')
else:
print('impar')

View File

@ -18,7 +18,7 @@ P = float(input("Pressure (kPa)? "))
# Determine the phase. # Determine the phase.
if (T > 400) and (P > 50): if (T > 400) and (P > 50):
phase = "LIQUID" phase = "LIQUID"
elif (P > 0.125 * T): elif P > 0.125 * T:
phase = "SOLID" phase = "SOLID"
else: else:
phase = "GAS" phase = "GAS"

View File

@ -1,8 +1,12 @@
# Esta função implementa g(x) = 8 - x**3 # Esta função implementa g(x) = 8 - x**3
g = lambda x: 8 - x**3 def g(x):
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
p = lambda x: x**2 + 2*x + 3 def p(x):
return x**2 + 2*x + 3
def main(): def main():
# Mostra alguns valores da função g: # Mostra alguns valores da função g:
@ -19,6 +23,6 @@ p(10) = {p(10)}
g(1 + p(3)) = {g(1 + p(3))} g(1 + p(3)) = {g(1 + p(3))}
""") """)
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,14 +1,14 @@
import math 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):
if x % 2 == 0: increment = 1/(x*2-1)
total -= 1/(x*2-1) total += -increment if x % 2 == 0 else increment
else:
total += 1/(x*2-1)
return total return total
def main(): def main():
num = int(input('Introduza o número de termos: ')) num = int(input('Introduza o número de termos: '))
print(f""" print(f"""
@ -16,5 +16,6 @@ Resultado da série de Leibniz: {leibnizPi4(num)}
Valor do PI/4: {math.pi/4} Valor do PI/4: {math.pi/4}
""") """)
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -1,12 +1,13 @@
# Pede ao utilizadores todas as parcelas e adiciona-as à lista 'values' # Pede ao utilizadores todas as parcelas e adiciona-as à lista 'values'
def GetValues(): def GetValues():
c = 1 count = 1
values = [] values = []
while True: while True:
n = input('n{}: '.format(c)) n = input('n{}: '.format(count))
if n == "": break if n == "":
break
values.append(float(n)) values.append(float(n))
c += 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'

View File

@ -1,10 +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
c = 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
c += 1 count += 1
print('O programa mostrou ', c, ' termos') print('O programa mostrou ', count, ' termos')

View File

@ -14,29 +14,33 @@ def main():
# #
mix() mix()
def inputFloatList(inputMsg = '>>> '):
def inputFloatList(inputMsg='>>> '):
returnList = [] returnList = []
while True: while True:
inpt = input(inputMsg) inpt = input(inputMsg)
if inpt == '': return returnList if inpt == '':
return returnList
try: try:
returnList.append(float(inpt)) returnList.append(float(inpt))
except: except ValueError:
continue continue
def countLower(lst, v): def countLower(lst, v):
returnList = [lst[i] for i in range(len(lst)) if lst[i] < v] return len([lst[i] for i in range(len(lst)) if lst[i] < v])
return len(returnList)
def minmax(lst): def minmax(lst):
mx = 0 mx = lst[0]
mn = 0 mn = lst[0]
for n in lst: for n in lst:
if n > mx: if n > mx:
mx = n mx = n
if n < mn: if n < mn:
mn = n mn = n
return (mn, mx) return mn, mx
# Alinea d) # Alinea d)
def mix(): def mix():
@ -46,5 +50,6 @@ def mix():
count = countLower(lst, med) count = countLower(lst, med)
print(count) print(count)
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -4,25 +4,22 @@ def main():
print(reapeatNumTimes(4)) print(reapeatNumTimes(4))
print(positionOfFirstLargest([1, 624, 123, 34, 12])) print(positionOfFirstLargest([1, 624, 123, 34, 12]))
def evenThenOdd(string): def evenThenOdd(string):
even = '' even = ''
odd = '' odd = ''
index = 0 for index, char in enumerate(string):
for char in string:
if index % 2 == 0: if index % 2 == 0:
even += char even += char
else: else:
odd += char odd += char
index += 1
return even + odd return even + odd
def removeAdjacentDuplicates(s): def removeAdjacentDuplicates(s):
new = '' new = ''
for i in range(len(s)): for i in range(len(s)):
if i == 0: if i == 0 or s[i] != s[i-1]:
new += s[i]
elif s[i] != s[i-1]:
new += s[i] new += s[i]
return new return new
@ -37,14 +34,13 @@ def reapeatNumTimes(n):
def positionOfFirstLargest(arr): def positionOfFirstLargest(arr):
mx = maxArray(arr) mx = maxArray(arr)
index = 0 for index, a in enumerate(arr):
for a in arr:
if a == mx: if a == mx:
return index return index
index += 1
def maxArray(arr): def maxArray(arr):
mx = 0 mx = arr[0]
for a in arr: for a in arr:
if a > mx: if a > mx:
mx = a mx = a

View File

@ -4,23 +4,19 @@
def telToName(tel, telList, nameList): def telToName(tel, telList, nameList):
# your code here # your code here
index = 0 for index, t in enumerate(telList):
for t in telList:
if t == tel: if t == tel:
break return nameList[index]
index += 1 return tel
return tel if index == len(telList) else nameList[index]
# Return list of telephone numbers corresponding to names containing partName. # Return list of telephone numbers corresponding to names containing partName.
def nameToTels(partName, telList, nameList): def nameToTels(partName, telList, nameList):
# your code here # your code here
tels = [] tels = []
index = 0 for index, name in enumerate(nameList):
for name in nameList:
if partName in name: if partName in name:
tels.append(telList[index]) tels.append(telList[index])
index += 1
return tels return tels
def main(): def main():

View File

@ -36,7 +36,7 @@ Numero Nome Nota
39450 RUI BARBOSA SOARES FIGUEIREDO 12.9 39450 RUI BARBOSA SOARES FIGUEIREDO 12.9
39652 FABIO ANDRE SABINO REAL 11.4 39652 FABIO ANDRE SABINO REAL 11.4
39840 JOAO FILIPE MAGALHAES CARVALHO PINTO 17.7 39840 JOAO FILIPE MAGALHAES CARVALHO PINTO 17.7
40000 TIAGO GARCIA 20.0 40000 TIAGO ROCHA GARCIA 20.0
40301 FILIPE MIGUEL FIGUEIREDO DA SILVA 9.5 40301 FILIPE MIGUEL FIGUEIREDO DA SILVA 9.5
40747 JOEL DOS SANTOS MIRANDA 17.0 40747 JOEL DOS SANTOS MIRANDA 17.0
41084 RICARDO JORGE MOREIRA SILVA MACHADO 11.4 41084 RICARDO JORGE MOREIRA SILVA MACHADO 11.4

View File

@ -3,11 +3,9 @@
# a) # a)
def loadFile(fname, lst): def loadFile(fname, lst):
with open(fname, 'r') as f: with open(fname, 'r') as f:
f.readline()
for line in f: for line in f:
line = line.strip('\n') data = line.strip('\n').split('\t')
if not line[0].isnumeric():
continue
data = line.split('\t')
dataTuple = (int(data[0]), data[1], float(data[5]), float(data[6]), float(data[7])) dataTuple = (int(data[0]), data[1], float(data[5]), float(data[6]), float(data[7]))
lst.append(dataTuple) lst.append(dataTuple)
@ -23,6 +21,7 @@ def printPauta(lst, filename=""):
text = f'{"Numero":>6} {"Nome":^50} {"Nota":>4}\n' text = f'{"Numero":>6} {"Nome":^50} {"Nota":>4}\n'
for aluno in lst: for aluno in lst:
text += f'{aluno[0]:>6} {aluno[1]:^50} {notaFinal(aluno):>4.1f}\n' text += f'{aluno[0]:>6} {aluno[1]:^50} {notaFinal(aluno):>4.1f}\n'
print(text) print(text)
with open(filename, 'w') as f: with open(filename, 'w') as f:
f.write(text) f.write(text)

View File

@ -14,6 +14,7 @@ def main():
print(f"A letra mais usada foi '{usedTheMost}', usada {usedTheMostCount} vezes.") print(f"A letra mais usada foi '{usedTheMost}', usada {usedTheMostCount} vezes.")
# This is the same function used in ../aula07/countLetters.py
def countLetters(filename): def countLetters(filename):
# Read the file and count the letters # Read the file and count the letters
letters = {} letters = {}

View File

@ -1,12 +1,13 @@
def main(): def main():
lst = [1, 2, 4, 5] lst = [1, 2, 4, 5, 6]
print(median(lst)) print(median(lst))
def median(lst): def median(lst):
lst = sorted(lst, reverse=True) lst = sorted(lst, reverse=True)
if len(lst) % 2 == 0: if len(lst) % 2 == 0:
return (lst[len(lst) // 2] + lst[len(lst) // 2 - 1]) / 2 middle = len(lst) // 2 - 1
return sum(lst[middle:middle+2]) / 2
else: else:
return lst[len(lst) // 2] return lst[len(lst) // 2]

View File

@ -14,6 +14,7 @@ Fibonacci numbers. For example, if n=6, it should return [0, 1, 1, 2, 3, 5].
The function only has to work for n>=2. The function only has to work for n>=2.
""" """
def genFibonacci(n): def genFibonacci(n):
assert n >= 2 assert n >= 2
# Complete ... # Complete ...
@ -24,10 +25,8 @@ def genFibonacci(n):
elif i == 1: elif i == 1:
lst.append(1) lst.append(1)
else: else:
lst.append(lst[i-2] + lst[i-1]) lst.append(lst[i - 2] + lst[i - 1])
return lst return lst
# NÃO precisa de invocar a função. O codecheck trata disso. # NÃO precisa de invocar a função. O codecheck trata disso.
# You DO NOT need to call the function. Codecheck does that for you. # You DO NOT need to call the function. Codecheck does that for you.

View File

@ -8,6 +8,7 @@ O programa já inclui instruções para ler uma lista de palavras inglesas a
partir do ficheiro wordlist.txt. partir do ficheiro wordlist.txt.
""" """
# This function reads words from a file. # This function reads words from a file.
def load(fname): def load(fname):
with open(fname) as f: with open(fname) as f:
@ -26,6 +27,8 @@ que o padrão nas mesmas posições, exceto onde o padrão tem ?.
Nas posições dos ?, não importa que carateres estão na string s. Nas posições dos ?, não importa que carateres estão na string s.
A correspondência não deve fazer distinção entre maiúsculas e minúsculas. A correspondência não deve fazer distinção entre maiúsculas e minúsculas.
""" """
def matchesPattern(s, pattern): def matchesPattern(s, pattern):
# Complete ... # Complete ...
if len(s) != len(pattern): if len(s) != len(pattern):
@ -35,11 +38,14 @@ def matchesPattern(s, pattern):
return False return False
return True return True
""" b) """ b)
Complete a função filterPattern(lst, pattern) para extrair duma lista de strings Complete a função filterPattern(lst, pattern) para extrair duma lista de strings
as strings que têm o padrão dado. as strings que têm o padrão dado.
Sugestão: use a função matchesPattern para testar cada palavra. Sugestão: use a função matchesPattern para testar cada palavra.
""" """
def filterPattern(lst, pattern): def filterPattern(lst, pattern):
# Complete ... # Complete ...
matches = [] matches = []
@ -51,13 +57,13 @@ def filterPattern(lst, pattern):
def main(): def main():
print("a)") print("a)")
print( matchesPattern("secret", "s?c??t") ) #-> True print(matchesPattern("secret", "s?c??t")) # -> True
print( matchesPattern("secreta", "s?c??t") ) #-> False print(matchesPattern("secreta", "s?c??t")) # -> False
print( matchesPattern("socket", "s?c??t") ) #-> True print(matchesPattern("socket", "s?c??t")) # -> True
print( matchesPattern("soccer", "s?c??t") ) #-> False print(matchesPattern("soccer", "s?c??t")) # -> False
print( matchesPattern("SEcrEt", "?ecr?t") ) #-> True print(matchesPattern("SEcrEt", "?ecr?t")) # -> True
print( matchesPattern("SEcrET", "?ecr?t") ) #-> True print(matchesPattern("SEcrET", "?ecr?t")) # -> True
print( matchesPattern("SecrEt", "?ECR?T") ) #-> True print(matchesPattern("SecrEt", "?ECR?T")) # -> True
words = load("wordlist.txt") words = load("wordlist.txt")
@ -77,4 +83,3 @@ def main():
# Call main function: # Call main function:
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -2,31 +2,35 @@
def matrows(M): def matrows(M):
return len(M) return len(M)
# Complete para devolver o número de colunas da matriz M. # Complete para devolver o número de colunas da matriz M.
def matcols(M): def matcols(M):
return len(M[0]) return len(M[0])
# Complete a função para devolver uma matriz com m×n zeros. # Complete a função para devolver uma matriz com m×n zeros.
def matzeros(m, n): def matzeros(m, n):
M = [] M = []
for i in range(m): for i in range(m):
M.append(n*[0]) M.append(n * [0])
return M return M
def matzerosTEST(m, n): def matzerosTEST(m, n):
M = matzeros(m, n) M = matzeros(m, n)
M[0][1] = 1 # should change just 1 element! M[0][1] = 1 # should change just 1 element!
return M return M
# Complete a função para multiplicar a matriz A pela matriz B. # Complete a função para multiplicar a matriz A pela matriz B.
def matmult(A, B): def matmult(A, B):
assert matcols(A) == matrows(B) assert matcols(A) == matrows(B)
C = [[sum(a*b for a, b in zip(A_row, B_col)) C = [[sum(a * b for a, b in zip(A_row, B_col))
for B_col in zip(*B)] for B_col in zip(*B)]
for A_row in A] for A_row in A]
return C return C
def matmultTEST(A, B): def matmultTEST(A, B):
C = matmult(A, B) C = matmult(A, B)
return A, B, C return A, B, C

View File

@ -1,4 +1,4 @@
# Not passing codecheck tests # Not passing codecheck tests although not sure why :skull:
def hondt(votes, numseats): def hondt(votes, numseats):
v = [vote for vote in votes] v = [vote for vote in votes]