PROGRAMMING

m9/ PYTHON
REMEMBERS




Factorial

p110 The definition of the factorial is that 0! is 1, and n! = n(n-1)! So 3! is 3 times 2!, which is 2 times 1!, which is 1 times 0!.
 
def factorial(n):
    
    if (n == 0): return 1

    n = n * factorial(n-1)
    return n

print(factorial(3)) # 6
print(factorial(0)) # 1
print(factorial(4)) # 24
... 1 lines
 

Fibonacci

p113 ! The most common example of recursively defined mathemetical function. The definition is: fb(0) = 0 / fb(1) =1 / fb(n) = fb(n-1) + fb(n-2)
 
def fibonacci(n):

    if (n==0): return 0
    if (n==1): return 1

    return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(0)) # 0
print(fibonacci(1)) # 1
print(fibonacci(2)) # 1
print(fibonacci(3)) # 2
print(fibonacci(4)) # 3
print(fibonacci(5)) # 5
print(fibonacci(6)) # 8
... 5 lines
 

Questions    
Reassignment

        A B C D E F
🔔
1/1