⚡ 60 segundos
funcoes
Entender recursão com um exemplo simples
Recursão é quando uma função chama a si mesma. Ideal para árvores, fatoriais e problemas dividíveis.
recursao.py
def fatorial(n):
if n <= 1:
return 1
return n * fatorial(n - 1)
print(fatorial(5)) # 120
# 5 * 4 * 3 * 2 * 1
# Fibonacci
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
print([fib(i) for i in range(8)])
# [0, 1, 1, 2, 3, 5, 8, 13]