Aula 10 added

This commit is contained in:
TiagoRG 2022-12-20 17:57:02 +00:00
parent 945aa3b607
commit 427942c647
Signed by untrusted user who does not match committer: TiagoRG
GPG Key ID: DFCD48E3F420DB42
8 changed files with 209 additions and 0 deletions

BIN
1ano/fp/aula10/aula10.pdf Normal file

Binary file not shown.

View File

@ -0,0 +1,49 @@
import os
def printDirFiles(d):
lst = os.listdir(d)
for fname in lst:
path = os.path.join(d, fname)
if os.path.isfile(path):
ftype = "FILE"
elif os.path.isdir(path):
ftype = "DIR"
else:
ftype = "?"
print(ftype, path)
return
def findFiles(path, ext) -> list:
# Complete...
if not os.path.isdir(path):
if ext == path[-len(ext):]:
return [path.split('/')[-1][:-len(ext)]]
return []
lst = []
for fname in os.listdir(path):
d = os.path.join(os.path.abspath(path), fname)
lst += findFiles(d, ext)
return lst
def main():
print("Testing printDirFiles('..'):")
printDirFiles("..")
print("\nTesting findFiles('.', '.py'):")
lst = findFiles(".", ".py")
print(lst)
assert isinstance(lst, list)
print("\nTesting findFiles('..', '.csv'):")
lst = findFiles("..", ".csv")
print(lst)
assert isinstance(lst, list)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,31 @@
# 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 ]
# 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 ]
def main():
lstA = genWords3("abc")
print(lstA)
lstB = genWords("abc", 3) # should return the same words, maybe in other order
print(lstB)
assert sorted(lstA) == sorted(lstB)
print(genWords("ab", 1))
print(genWords("ab", 0))
lstC = genWords("01", 4) # should return all length-4 binary words
print(lstC)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,21 @@
"""
Dada uma string, construa e devolva uma nova string onde
todas as letras 'x' apareçam movidas para o fim da string.
A função tem de ser recursiva. Não pode usar ciclos.
Given a string, return a new string where all the
'x' chars have been moved to the end of the string.
The function must be recursive. You cannot use loops.
endX("xxre") "rexx"
endX("xxhixx") "hixxxx"
endX("hixhix") "hihixx"
"""
def endX(s):
if s == '':
return ''
elif s[0] == 'x':
return endX(s[1:]) + 'x'
else:
return s[0] + endX(s[1:])

View File

@ -0,0 +1,31 @@
# 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)
# Calcula o maximo divisor comum entre a e b.
# Baseia-se no algoritmo de Euclides.
# 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:
return b
return gcd(b, a%b)
def main():
print( fact(4) ) # 24
print( fact(5) ) # 120
x = 2*27*53*61
y = 2*2*17*23*53
print(x, y, gcd(x, y))
assert gcd(x, y) == 2*53
if __name__ == "__main__":
main()

View File

@ -0,0 +1,27 @@
"""
Pretendemos um método que inverta a ordem dos dígitos de um número inteiro.
Por exemplo `reverseDigits(1234)` deve devolver 4321.
Deve fazê-lo através da função _recursiva_ auxiliar `reverseAux`.
Eis um exemplo do cálculo:
reverseAux(1234, 0)
= reverseAux(123, 4)
= reverseAux(12, 43)
= reverseAux(1, 432)
= reverseAux(0, 4321)
= 4321
Não pode usar strings nem ciclos.
Note que `1234%10 = 4` e `1234//10 = 123`.
"""
def reverseDigits(value):
return reverseAux(value, 0)
def reverseAux(partValue, partReversed):
if partValue == 0:
return partReversed
return reverseAux(partValue//10, partReversed*10 + partValue%10)

50
1ano/fp/aula10/traced.py Normal file
View File

@ -0,0 +1,50 @@
# New decorator: @traced
#
# PLEASE NOTE:
# This is not a required subject!
# You don't need to understand how this works.
# Just use the module as a service to trace the execution of functions.
#
# Decorator @traced modifies the function so that an execution trace is shown.
# jmr@ua.pt 2016-10-14 (v2)
# 2017-12-03: Name changed from trace -> traced
def traced(func):
def tracedfunc(*args, **kwargs):
if traced.indent != None:
indent = traced.indent # save current indentation
traced.indent += u"\u2502 "
print(u"{}{}{!r}{!r}".format(indent, func.__name__, args, kwargs))
try:
r = func(*args, **kwargs) # CALL the func!
return r
except Exception as e:
r = e
raise e
finally:
if traced.indent != None:
print(u"{}\u2514>{!r}".format(indent, r))
traced.indent = indent # restore indentation
return tracedfunc
# Initial tracing prefix:
traced.indent = ""
# Uncomment to turn off tracing by default:
#traced.indent = None
#traced.indent = traced.__dict__.get("indent")
if __name__ == "__main__":
# How to use this module:
from traced import traced
@traced
def func(x):
return x*x
func(3)

Binary file not shown.