factorial(0) = 1 factorial(n) = n * factorial(n-1) factorial(3) = 3 * factorial(2) = 3 * 2 * factorial(1) = 3 * 2 * 1 * factorial(0) = 3 * 2 * 1 * 1 = 6 factorial(n) = 1 * 2 * ... * (n-1) * n
def factorial(n):
if n < 0:
return None
elif (n == 0):
return 1
return n * factorial(n-1)
print(factorial(-5))
None
def my_sum(nums):
answer = 0
for num in nums:
answer = answer + num
return answer
my_sum([1,2,3])
6
# my_sum2([]) = 0
# my_sum2(xs) = xs[0] + my_sum2(xs[1:])
def my_sum2(nums):
if nums == []:
return 0
return nums[0] + my_sum2(nums[1:])
my_sum2([1,2,3,4])
10
my_sum2([1,2,3,4]) = 1 + my_sum2([2,3,4]) = 1 + 2 + my_sum2([3,4]) = 1 + 2 + 3 + my_sum2([4]) = 1 + 2 + 3 + 4 + my_sum2([]) = 1 + 2 + 3 + 4 + 0 = 10
def my_max(nums):
if nums == []:
return None
answer = nums[0]
for num in nums[1:]:
if num > answer:
answer = num
return answer
my_max([10,5,16,24,2])
24
def my_max2(nums):
if nums == []:
return None
if len(nums) == 1:
return nums[0]
return max(nums[0],my_max2(nums[1:]))
max(10,20)
20
max([10,20])
20
my_max([10,5,16,24,2]) = max(10,my_max([5,16,24,2])) = max(10,max(5,my_max([16,24,2]))) = max(10,max(5,max(16,my_max([24,2])))) = max(10,max(5,max(16,max(24,my_max([2]))))) = max(10,max(5,max(16,max(24,2)))) = max(10,max(5,max(16,24))) = max(10,max(5,24)) = max(10,24) = 24