In [142]:
def fibonacci (n):
if not isinstance(n, int):
print "Need an integer I'm afraid"
elif n < 0:
print "Not defined for negative numbers"
elif n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
In [200]:
fibonacci(2)
Out[200]:
In [149]:
fibonacci(-1)
In [1]:
def compare(x, y):
if x > y:
return 1
elif x < y:
return -1
else:
return 0
In [2]:
compare(1,2)
Out[2]:
In [3]:
compare(2,1)
Out[3]:
In [4]:
compare(1,1)
Out[4]:
In [10]:
import math
In [11]:
def hypotenuse(leg1, leg2):
sides_squared = leg1 ** 2 + leg2 ** 2
print sides_squared
result = math.sqrt(sides_squared)
print result
return result
In [12]:
hypotenuse(3,4)
Out[12]:
In [13]:
def hypotenuse(leg1, leg2):
return math.sqrt(leg1 ** 2 + leg2 ** 2)
In [14]:
hypotenuse(3,4)
Out[14]:
In [17]:
def is_between(x, y, z):
return x <= y and y <= z
In [18]:
is_between(1.5, math.pi, 4)
Out[18]:
In [19]:
is_between(1.5, 4, math.pi)
Out[19]:
In [20]:
def ack(m, n):
if m < 0 or n < 0:
print "m and n must be nonnegative"
return None
elif m == 0:
return n + 1
elif m > 0 and n == 0:
return ack(m - 1, 1)
elif m > 0 and n > 0:
return ack(m - 1, ack(m, n - 1))
In [21]:
print ack(3, 4)
In [23]:
print ack(3, 3)
In [25]:
def first(word):
return word[0]
def last(word):
return word[-1]
def middle(word):
return word[1:-1]
In [26]:
middle('ab')
Out[26]:
In [27]:
middle('a')
Out[27]:
In [28]:
middle('')
Out[28]:
In [37]:
def is_palindrome(word):
if len(word) <= 1:
return True
else:
return first(word) == last(word) and is_palindrome(middle(word))
In [38]:
is_palindrome('amanaplanacanalpanama')
Out[38]:
In [42]:
is_palindrome('abcdefg')
Out[42]:
In [194]:
Out[194]:
In [47]:
def is_power(a, b):
return math.log(a, b) % 1 == 0
In [51]:
is_power(8, 2)
Out[51]:
In [50]:
is_power(8, 3)
Out[50]:
In [214]:
def is_power(a, b):
if a == 1:
return True
else:
return a % b == 0 and is_power(a/b, b)
In [215]:
%timeit is_power(2**25,2)
In [72]:
is_power(17,2)
Out[72]:
In [14]:
def gcd_v1(a, b):
if a == b:
return a
elif a > b:
return gcd_v1(a - b, b)
else:
return gcd_v1(a, b - a)
In [15]:
def gcd_v2(a, b):
if a < b:
a, b = b, a
r = a % b
if r == 0:
return b
else:
return gcd_v2(a, r)
In [20]:
gcd_v1(91, 91*17)
Out[20]:
In [19]:
gcd_v2(8, 4)
Out[19]: