Wednesday, October 5, 2016

[ Functional Programming ] Recursion

Recursion => self-reference
factorial function

base case => a case that doesn't involve any further calls to that function

>>>
def factorial(x):
    if x ==1:  # base case
      return 1
    else:
      return x * fractorial (x-1)

print(factorial(5))


Recursion can also be indirect . One function can call a second , which calls the first , which calls the second, and so on .

>>>
def is_even(x):
    if x == 0:
      return True
    else:
      return is_odd(x-1)

def is_odd(x):
    return not is_even(x)


print(is_odd(17))
print(is_even(23))

No comments:

Post a Comment