21.12.2022 Views

python_para_desenvolvedores_2ed

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Funções 53

if num <= 1:

return 1

else:

return(num * fatorial(num – 1))

# Testando fatorial()

print fatorial(5)

Saída:

120

Exemplo (fatorial sem recursão):

def fatorial(n):

n = n if n > 1 else 1

j = 1

for i in range(1, n + 1):

j = j * i

return j

# Testando...

for i in range(1, 6):

print i, '->', fatorial(i)

Saída:

1 -> 1

2 -> 2

3 -> 6

4 -> 24

5 -> 120

Exemplo (série de Fibonacci com recursão):

def fib(n):

"""Fibonacci:

fib(n) = fib(n - 1) + fib(n - 2) se n > 1

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!