Write a function that sums all of the elements in a list (use a for or while loop)
def sum_list(l):
sum_so_far = 0
for n in l:
sum_so_far += n
return sum_so_far
def sum_list(l):
i = 0
sum_so_far = 0
while i < len(l):
sum_so_far += l[i]
return sum_so_far
Use slicing to return:
l = ['a','b','c','d','e','f','g']
print(l[0])
print(l[-1])
print(l[1:])
print(l[:-1])
['a', 'b', 'c', 'd', 'e', 'f']
We decide how many arguments a function has when we define it
For example:
$f(x) = x$
$g(x,y) = x + y$
$h(x,y,z) = x+y+z$
# This is an example of a function with two arguments
def sum_two(x, y):
return x + y
print(sum_two(1, 2))
3
# This is a function with three arguments
def sum_three(x,y,z):
return x + y + z
print(sum_three(3,4,5))
Can you define sum_three
using sum_two
?
def sum_three(x,y,z):
return x + sum_two(x,y)
print(sum_three(3,4,5))
Can you define sum_four
using sum_three
?
def sum_four(a, b, c, d):
return sumThree(a, b, c) + d
print(sumFour(1, 2, 3, 4))
10
We'll practice with adding up all the numbers in a list
Use recursion to write a function that adds all the elements in a list
Don't look at your notes!
def recSumList(x):
if len(x) == 1: #4,3,2,1
return x[0]
return x[0] + recSumList(x[1:])
# NOTE: if there is a board, do this on the board
# 0 + recSumList([1, 2, 3])
# 1 + recSumList([2, 3])
# 2 + recSumList([3])
# 3
# -> 3 + 2 + 1 + 0
# -> 6
# Also do without base case
# In addition to being able to call other functions, a function can call itself!
# A function calling itself is "recursion"
# NOTE: bewarned. As with while loops, these can go on forever
# YOU MUST HAVE A BASE CASE!!
# This works in general!
recSumList([1, 10, 2, 4])
17
Write a function to find the factorial of an input using recursion
Remember:
$n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1$
Don't look at your notes
# Definition of factorial: n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1
# Also, 1! = 1
# How can you turn this into a recursion?
# Recursive case:
# Base case: 1! = 1
#n! = n * (n - 1)!
def factorial(n):
#n=5
#n=4
#n=3
#n=2
#n=1
if n==1:
return 1
return n*factorial(n-1)
#factorial(5)
#return 5*factorial(5-1)
#return 4*factorial(4-1)
#retrun 3*factorial(3-1)
#return 2*factorial(2-1)
#return 1
print(factorial(5))
def factorial2(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(1))
print(factorial(2))
print(factorial(3))
print(factorial(4))
1 2 6 24