def factorial(n):
"""
Calculate n!.
Run in O(n) time, as there are n + 1 activations, each of which accounts for O(1) operations.
"""
if n==0:
return 1
else:
return n*factorial(n-1)
def binary_search(data, target, low, high):
"""
Return True if target is found in indicated portion of a Python list.
Run in O(log n) time.
"""
if low > high:
return False
else:
mid = (low + high) // 2
if target == data[mid]:
return True
elif target < data[mid]:
binary_search(data, target, low, mid - 1)
else:
binary_search(data, target, mid + 1, high)
def disk_usage(path):
"""
Return the number of bytes used by a file/folder and any descendents.
"""
import os
total = os.path.getsize(path)
if os.path.isdir(path):
for filename in os.listdir(path):
child_path = os.path.join(path, filename)
total += disk_usage(child_path)
return total
def fibonacci(n):
"""
Return pair of Fibonacci numbers, F(n) and F(n - 1).
"""
if n <= 1:
return (n, 0)
else:
a, b = fibonacci(n - 1)
print("a, b: ", a, b)
return (a + b, a)
def linear_sum(S, n):
"""
Return the sum of the first n numbers of sequence S.
"""
if n==0:
return 0
else:
return S[n - 1] + linear_sum(S, n - 1)