From e552fdf07ee499a9911cfb6a31d06df4bcb52102 Mon Sep 17 00:00:00 2001 From: TiagoRG <35657250+TiagoRG@users.noreply.github.com> Date: Mon, 30 Jan 2023 16:48:43 +0000 Subject: [PATCH] Refractoring and files reformat --- 1ano/fp/aula02/darts.py | 9 ++- 1ano/fp/aula02/ex04.py | 6 +- 1ano/fp/aula02/kryptonite.py | 4 +- 1ano/fp/aula03/poly.py | 10 ++- 1ano/fp/aula04/leibnizPi4.py | 11 ++-- 1ano/fp/aula04/media.py | 9 +-- 1ano/fp/aula04/sequenceUn.py | 7 +- 1ano/fp/aula05/ex02.py | 31 +++++---- 1ano/fp/aula05/ex08.py | 16 ++--- 1ano/fp/aula05/telephones.py | 12 ++-- 1ano/fp/aula06/datafiles/schooldata.txt | 2 +- 1ano/fp/aula06/school.py | 7 +- 1ano/fp/aula09/countLetters2.py | 1 + 1ano/fp/aula09/median.py | 5 +- 1ano/fp/extra1/ex01.py | 25 ++++---- 1ano/fp/extra1/ex02.py | 85 +++++++++++++------------ 1ano/fp/extra1/ex03.py | 38 ++++++----- 1ano/fp/extra1/ex04.py | 2 +- 18 files changed, 145 insertions(+), 135 deletions(-) diff --git a/1ano/fp/aula02/darts.py b/1ano/fp/aula02/darts.py index 31fc2cd..fd7ea8f 100755 --- a/1ano/fp/aula02/darts.py +++ b/1ano/fp/aula02/darts.py @@ -1,5 +1,6 @@ import math + def main(): print("""Introduza as coordenadas (x, y) do dardo. Representa as posicoes horizontal e vertical respetivamente. @@ -23,7 +24,7 @@ Ambas em milimetros. return score = BasePoint(x, y) - if mod > 99 and mod < 107: + if 99 < mod < 107: score *= 3 if mod > 162: score *= 2 @@ -31,6 +32,7 @@ Ambas em milimetros. print(f'Pontuacao: {score} pontos.') exit(1) + def BasePoint(x, y): angleRad = math.atan2(y, x) angleDeg = math.degrees(angleRad) - 9 @@ -38,6 +40,7 @@ def BasePoint(x, y): POINTS = (6, 13, 4, 18, 1, 20, 5, 12, 9, 14, 11, 8, 16, 7, 19, 3, 17, 2, 15, 10) return POINTS[int(angleDeg / 20)] - + + if __name__ == '__main__': - main() \ No newline at end of file + main() diff --git a/1ano/fp/aula02/ex04.py b/1ano/fp/aula02/ex04.py index 52fa284..e383798 100755 --- a/1ano/fp/aula02/ex04.py +++ b/1ano/fp/aula02/ex04.py @@ -1,6 +1,2 @@ n = int(input('numero? ')) - -if n % 2 == 0: - print('par') -else: - print('impar') \ No newline at end of file +print("par" if n % 2 == 0 else "impar") diff --git a/1ano/fp/aula02/kryptonite.py b/1ano/fp/aula02/kryptonite.py index 2f54424..2557b60 100755 --- a/1ano/fp/aula02/kryptonite.py +++ b/1ano/fp/aula02/kryptonite.py @@ -18,10 +18,10 @@ P = float(input("Pressure (kPa)? ")) # Determine the phase. if (T > 400) and (P > 50): phase = "LIQUID" -elif (P > 0.125 * T): +elif P > 0.125 * T: phase = "SOLID" else: phase = "GAS" # Output. -print("At {:.1f} K and {:.3f} kPa, Kryptonite is in the {} phase.\n\n".format(T, P, phase)) \ No newline at end of file +print("At {:.1f} K and {:.3f} kPa, Kryptonite is in the {} phase.\n\n".format(T, P, phase)) diff --git a/1ano/fp/aula03/poly.py b/1ano/fp/aula03/poly.py index aa62f8b..f2af98a 100755 --- a/1ano/fp/aula03/poly.py +++ b/1ano/fp/aula03/poly.py @@ -1,8 +1,12 @@ # 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 -p = lambda x: x**2 + 2*x + 3 +def p(x): + return x**2 + 2*x + 3 + def main(): # Mostra alguns valores da função g: @@ -19,6 +23,6 @@ p(10) = {p(10)} g(1 + p(3)) = {g(1 + p(3))} """) + if __name__ == '__main__': main() - diff --git a/1ano/fp/aula04/leibnizPi4.py b/1ano/fp/aula04/leibnizPi4.py index 1fc93d5..c4e036e 100755 --- a/1ano/fp/aula04/leibnizPi4.py +++ b/1ano/fp/aula04/leibnizPi4.py @@ -1,14 +1,14 @@ import math + def leibnizPi4(n): total = 0 for x in range(1, n+1): - if x % 2 == 0: - total -= 1/(x*2-1) - else: - total += 1/(x*2-1) + increment = 1/(x*2-1) + total += -increment if x % 2 == 0 else increment return total + def main(): num = int(input('Introduza o número de termos: ')) print(f""" @@ -16,5 +16,6 @@ Resultado da série de Leibniz: {leibnizPi4(num)} Valor do PI/4: {math.pi/4} """) + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/1ano/fp/aula04/media.py b/1ano/fp/aula04/media.py index d3f6b2f..6af9476 100755 --- a/1ano/fp/aula04/media.py +++ b/1ano/fp/aula04/media.py @@ -1,12 +1,13 @@ # Pede ao utilizadores todas as parcelas e adiciona-as à lista 'values' def GetValues(): - c = 1 + count = 1 values = [] while True: - n = input('n{}: '.format(c)) - if n == "": break + n = input('n{}: '.format(count)) + if n == "": + break values.append(float(n)) - c += 1 + count += 1 return values # Calcula a média dos valores da lista 'values' diff --git a/1ano/fp/aula04/sequenceUn.py b/1ano/fp/aula04/sequenceUn.py index 674d5b1..23908ef 100755 --- a/1ano/fp/aula04/sequenceUn.py +++ b/1ano/fp/aula04/sequenceUn.py @@ -1,10 +1,9 @@ - # This program generates 20 terms of a sequence by a recurrence relation. Un = 100 # Un = each term of the sequence. Initially = U0 -c = 0 +count = 0 while Un > 0: print(round(Un, 4)) 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') diff --git a/1ano/fp/aula05/ex02.py b/1ano/fp/aula05/ex02.py index e9a53b6..ada0ec5 100755 --- a/1ano/fp/aula05/ex02.py +++ b/1ano/fp/aula05/ex02.py @@ -2,41 +2,45 @@ def main(): floatList = inputFloatList() print(floatList) print() - + # Tem de dar print a '4' print(countLower([1321, 143, 1432, 512, 43, 153, 143613], 1000)) print() - + # Tem de dar print a 43, 143613 print(minmax([1321, 143, 1432, 512, 43, 153, 143613])) print() - + # mix() -def inputFloatList(inputMsg = '>>> '): + +def inputFloatList(inputMsg='>>> '): returnList = [] while True: inpt = input(inputMsg) - if inpt == '': return returnList + if inpt == '': + return returnList try: returnList.append(float(inpt)) - except: + except ValueError: continue + def countLower(lst, v): - returnList = [lst[i] for i in range(len(lst)) if lst[i] < v] - return len(returnList) + return len([lst[i] for i in range(len(lst)) if lst[i] < v]) + def minmax(lst): - mx = 0 - mn = 0 + mx = lst[0] + mn = lst[0] for n in lst: if n > mx: mx = n if n < mn: mn = n - return (mn, mx) + return mn, mx + # Alinea d) def mix(): @@ -45,6 +49,7 @@ def mix(): med = (mn_mx[0] + mn_mx[1]) / 2 count = countLower(lst, med) print(count) - + + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/1ano/fp/aula05/ex08.py b/1ano/fp/aula05/ex08.py index dc23ff3..472d49b 100755 --- a/1ano/fp/aula05/ex08.py +++ b/1ano/fp/aula05/ex08.py @@ -4,25 +4,22 @@ def main(): print(reapeatNumTimes(4)) print(positionOfFirstLargest([1, 624, 123, 34, 12])) + def evenThenOdd(string): even = '' odd = '' - index = 0 - for char in string: + for index, char in enumerate(string): if index % 2 == 0: even += char else: odd += char - index += 1 return even + odd def removeAdjacentDuplicates(s): new = '' for i in range(len(s)): - if i == 0: - new += s[i] - elif s[i] != s[i-1]: + if i == 0 or s[i] != s[i-1]: new += s[i] return new @@ -37,14 +34,13 @@ def reapeatNumTimes(n): def positionOfFirstLargest(arr): mx = maxArray(arr) - index = 0 - for a in arr: + for index, a in enumerate(arr): if a == mx: return index - index += 1 + def maxArray(arr): - mx = 0 + mx = arr[0] for a in arr: if a > mx: mx = a diff --git a/1ano/fp/aula05/telephones.py b/1ano/fp/aula05/telephones.py index aeb8745..5239a01 100755 --- a/1ano/fp/aula05/telephones.py +++ b/1ano/fp/aula05/telephones.py @@ -4,23 +4,19 @@ def telToName(tel, telList, nameList): # your code here - index = 0 - for t in telList: + for index, t in enumerate(telList): if t == tel: - break - index += 1 - return tel if index == len(telList) else nameList[index] + return nameList[index] + return tel # Return list of telephone numbers corresponding to names containing partName. def nameToTels(partName, telList, nameList): # your code here tels = [] - index = 0 - for name in nameList: + for index, name in enumerate(nameList): if partName in name: tels.append(telList[index]) - index += 1 return tels def main(): diff --git a/1ano/fp/aula06/datafiles/schooldata.txt b/1ano/fp/aula06/datafiles/schooldata.txt index 4436d69..bbbf811 100755 --- a/1ano/fp/aula06/datafiles/schooldata.txt +++ b/1ano/fp/aula06/datafiles/schooldata.txt @@ -36,7 +36,7 @@ Numero Nome Nota 39450 RUI BARBOSA SOARES FIGUEIREDO 12.9 39652 FABIO ANDRE SABINO REAL 11.4 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 40747 JOEL DOS SANTOS MIRANDA 17.0 41084 RICARDO JORGE MOREIRA SILVA MACHADO 11.4 diff --git a/1ano/fp/aula06/school.py b/1ano/fp/aula06/school.py index d56313a..396ab3b 100755 --- a/1ano/fp/aula06/school.py +++ b/1ano/fp/aula06/school.py @@ -3,11 +3,9 @@ # a) def loadFile(fname, lst): with open(fname, 'r') as f: + f.readline() for line in f: - line = line.strip('\n') - if not line[0].isnumeric(): - continue - data = line.split('\t') + data = line.strip('\n').split('\t') dataTuple = (int(data[0]), data[1], float(data[5]), float(data[6]), float(data[7])) lst.append(dataTuple) @@ -23,6 +21,7 @@ def printPauta(lst, filename=""): text = f'{"Numero":>6} {"Nome":^50} {"Nota":>4}\n' for aluno in lst: text += f'{aluno[0]:>6} {aluno[1]:^50} {notaFinal(aluno):>4.1f}\n' + print(text) with open(filename, 'w') as f: f.write(text) diff --git a/1ano/fp/aula09/countLetters2.py b/1ano/fp/aula09/countLetters2.py index f65bf0d..2032210 100644 --- a/1ano/fp/aula09/countLetters2.py +++ b/1ano/fp/aula09/countLetters2.py @@ -14,6 +14,7 @@ def main(): print(f"A letra mais usada foi '{usedTheMost}', usada {usedTheMostCount} vezes.") +# This is the same function used in ../aula07/countLetters.py def countLetters(filename): # Read the file and count the letters letters = {} diff --git a/1ano/fp/aula09/median.py b/1ano/fp/aula09/median.py index 05803e2..97dd3f2 100644 --- a/1ano/fp/aula09/median.py +++ b/1ano/fp/aula09/median.py @@ -1,12 +1,13 @@ def main(): - lst = [1, 2, 4, 5] + lst = [1, 2, 4, 5, 6] print(median(lst)) def median(lst): lst = sorted(lst, reverse=True) 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: return lst[len(lst) // 2] diff --git a/1ano/fp/extra1/ex01.py b/1ano/fp/extra1/ex01.py index abb5834..d39d1cd 100644 --- a/1ano/fp/extra1/ex01.py +++ b/1ano/fp/extra1/ex01.py @@ -14,20 +14,19 @@ 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. """ + def genFibonacci(n): - assert n >= 2 - # Complete ... - lst = [] - for i in range(n): - if i == 0: - lst.append(0) - elif i == 1: - lst.append(1) - else: - lst.append(lst[i-2] + lst[i-1]) - return lst - + assert n >= 2 + # Complete ... + lst = [] + for i in range(n): + if i == 0: + lst.append(0) + elif i == 1: + lst.append(1) + else: + lst.append(lst[i - 2] + lst[i - 1]) + return lst # 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. - diff --git a/1ano/fp/extra1/ex02.py b/1ano/fp/extra1/ex02.py index 6d8e07d..5bed1d7 100644 --- a/1ano/fp/extra1/ex02.py +++ b/1ano/fp/extra1/ex02.py @@ -8,14 +8,15 @@ O programa já inclui instruções para ler uma lista de palavras inglesas a partir do ficheiro wordlist.txt. """ + # This function reads words from a file. def load(fname): - with open(fname) as f: - lst = [] - for line in f: - words = line.strip().split() - lst.extend(words) - return lst + with open(fname) as f: + lst = [] + for line in f: + words = line.strip().split() + lst.extend(words) + return lst """ a) @@ -26,55 +27,59 @@ 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. A correspondência não deve fazer distinção entre maiúsculas e minúsculas. """ + + def matchesPattern(s, pattern): - # Complete ... - if len(s) != len(pattern): - return False - for i in range(len(s)): - if (s[i].lower() != pattern[i].lower()) and (pattern[i] != "?"): - return False - return True - + # Complete ... + if len(s) != len(pattern): + return False + for i in range(len(s)): + if (s[i].lower() != pattern[i].lower()) and (pattern[i] != "?"): + return False + return True + + """ b) Complete a função filterPattern(lst, pattern) para extrair duma lista de strings as strings que têm o padrão dado. Sugestão: use a função matchesPattern para testar cada palavra. """ + + def filterPattern(lst, pattern): - # Complete ... - matches = [] - for word in lst: - if matchesPattern(word, pattern): - matches.append(word) - return matches + # Complete ... + matches = [] + for word in lst: + if matchesPattern(word, pattern): + matches.append(word) + return matches def main(): - print("a)") - print( matchesPattern("secret", "s?c??t") ) #-> True - print( matchesPattern("secreta", "s?c??t") ) #-> False - print( matchesPattern("socket", "s?c??t") ) #-> True - 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("a)") + print(matchesPattern("secret", "s?c??t")) # -> True + print(matchesPattern("secreta", "s?c??t")) # -> False + print(matchesPattern("socket", "s?c??t")) # -> True + 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 - words = load("wordlist.txt") + words = load("wordlist.txt") - print("b)") - # Solution to "S?C??T" - lst = filterPattern(words, "s?c??t") - print(lst) + print("b)") + # Solution to "S?C??T" + lst = filterPattern(words, "s?c??t") + print(lst) - assert isinstance(lst, list), "result lst should be a list" - assert "secret" in lst, "result should contain 'secret'" + assert isinstance(lst, list), "result lst should be a list" + assert "secret" in lst, "result should contain 'secret'" - # Solution to "?YS???Y" - lst = filterPattern(words, "?ys???y") - print(lst) + # Solution to "?YS???Y" + lst = filterPattern(words, "?ys???y") + print(lst) # Call main function: if __name__ == "__main__": - main() - + main() diff --git a/1ano/fp/extra1/ex03.py b/1ano/fp/extra1/ex03.py index 8bdaf30..0df3c6e 100644 --- a/1ano/fp/extra1/ex03.py +++ b/1ano/fp/extra1/ex03.py @@ -1,32 +1,36 @@ # Devolve o número de linhas da matriz M. def matrows(M): - return len(M) + return len(M) + # Complete para devolver o número de colunas da matriz M. def matcols(M): - return len(M[0]) + return len(M[0]) + # Complete a função para devolver uma matriz com m×n zeros. def matzeros(m, n): - M = [] - for i in range(m): - M.append(n*[0]) - return M + M = [] + for i in range(m): + M.append(n * [0]) + return M + def matzerosTEST(m, n): - M = matzeros(m, n) - M[0][1] = 1 # should change just 1 element! - return M + M = matzeros(m, n) + M[0][1] = 1 # should change just 1 element! + return M + # Complete a função para multiplicar a matriz A pela matriz B. def matmult(A, B): - assert matcols(A) == matrows(B) - C = [[sum(a*b for a, b in zip(A_row, B_col)) - for B_col in zip(*B)] - for A_row in A] - return C + assert matcols(A) == matrows(B) + C = [[sum(a * b for a, b in zip(A_row, B_col)) + for B_col in zip(*B)] + for A_row in A] + return C + def matmultTEST(A, B): - C = matmult(A, B) - return A, B, C - + C = matmult(A, B) + return A, B, C diff --git a/1ano/fp/extra1/ex04.py b/1ano/fp/extra1/ex04.py index 9b24744..ae1fc91 100644 --- a/1ano/fp/extra1/ex04.py +++ b/1ano/fp/extra1/ex04.py @@ -1,4 +1,4 @@ -# Not passing codecheck tests +# Not passing codecheck tests although not sure why :skull: def hondt(votes, numseats): v = [vote for vote in votes]