In [9]:
import numpy as np
In [3]:
def recursive_add(a, b):
if b == 0:
return a
else:
return 1 + recursive_add(a, b-1)
In [8]:
assert recursive_add(2, 3) == 5
assert recursive_add(0, 0) == 0
assert recursive_add(1, 1) == 2
assert recursive_add(10, 12) == 22
In [62]:
def recursive_avg(array):
n = len(array)
if n == 1:
return array[0]
elif n == 2:
return (array[0] + array[1]) / 2.0
else:
return (array[n-1] + (n-1) * recursive_avg(array[0:n-1])) / n
In [63]:
for a in [np.arange(10), np.ones(15), np.zeros(4), np.array([5]), np.array([1, 17.2])]:
assert recursive_avg(a) == np.mean(a)
In [122]:
def a(m, n):
if m == 0:
print 'a({}, {}) = {}'.format(m, n, n+1)
return n + 1
elif (m != 0) and (n == 0):
print 'a({}, {}) = a({}, {})'.format(m, n, m-1, 1)
return a(m-1, 1)
else:
print 'a({}, {}) = a({}, a({}, {}))'.format(m, n, m-1, m, n-1)
return a(m-1, a(m, n-1))
In [123]:
a(2, 2)
Out[123]:
In [90]:
def gcd(x, y):
if (y <= x) and (x % y == 0):
return y
elif (x < y):
return gcd(y, x)
else:
return gcd(y, x%y)
In [95]:
gcd(20, 10)
Out[95]:
In [64]:
def gfib(f0, f1, n):
if n == 0:
return f0
elif n == 1:
return f1
else:
return gfib(f0, f1, n-1) + gfib(f0, f1, n-2)
In [72]:
gfib(0, 1, 6)
Out[72]:
In [75]:
def M(x, y):
print x, y
if x == y:
return x
elif y > x:
return M(x, y-x)
elif x > y:
return M(x-y, y)
In [80]:
M(20, 10)
Out[80]: