(PPT) Variables, Conditional Statements, and Recursion in Python
(PPT) Variables, Conditional Statements, and Recursion in Python
x = 1000
y=x
x = "a"
tax_rate = 0.1
def after_tax(amount):
return amount * (1 - tax_rate)
Errors with global variables
• Consider the following program:
grade = 87
def increase_grade(inc):
grade = grade + inc
>>> increase_grade(5)
𝑛 !=
{ 1 , 𝑛= 0
𝑛× ( 𝑛 − 1 ) ! , 𝑛>0
def fac(n):
if n == 0:
return 1
else:
return n * fac(n - 1)
Example: sum of powers
def sn(n):
if n == 0:
return 1
else:
return 2 ** n + sn(n - 1)
“Countdown” template
def countdown_template(n):
if n==0:
return base_answer
else:
answer = ... n ... ... countdown_template(n-1) ...
return answer
Do countA(5) and countB(5) print the same
result?
def countA(n): def countB(n):
if n == 0: if n == 0:
return return
else: else:
print(n) countB(n - 1)
countA(n - 1) print(n)
Some limitations to the recursive approach
• CountA(10000)
• “builtins.RecursionError: maximum recursion depth exceeded while calling a
Python object”
• There is a limit to how much recursion Python “can remember”
• Still fine for small problem sizes
• We’ll see a new approach for bigger problems.
Combination number
𝑚
{
1,𝑚=0𝑜𝑟 𝑚=𝑛
𝐶 = 𝑚 𝑚−1
𝑛
𝐶𝑛−1 +𝐶𝑛 −1 , 𝑜𝑡h𝑒𝑟𝑤𝑖𝑠𝑒
Fibonacci sequence
How many times is fib(0) called to calculate
fib(n)?
• Consider fib (10):
• fib(9) is called 1 time
• fib(8) is called 2 times
• fib(7) is called 3 times
• …
• matrix multiplication
• List
• A type of data in Python
List in Python
• Python lists can store
• any number of values
• any types of values (even in one list)
• Creating lists
• Use square brackets to begin and end list, and separate elements with a comma
• Concatenate (using +) existing lists to create a new list
• Examples:
num_list = [4, 5, 0]
str_list = ['a', 'b’]
empty_list = []
mixed_list = ['abc', 12, True, '',-12.4]
Useful Information about Python Lists
• len(L) number of items in the list L
• L[i] item at position i
• Called indexing the list
• Causes an error if i is out of range
• Positions: 0 <= i < len(L)
• Actual valid range: -len(L) <= i < len(L)
• "Slicing"a list
• L[i : j] [L[i], L[i + 1], ... , L[j - 1]]
• L[i : j : k] [L[i], L[i + k], ... , L[i + m * k]]
• includes all the positions up to (but not including) j
Other list operations
• in
• x in L True if x is in L, False otherwise
• 5 in [10,2,4,5]
• "a" in ["hello", "there", "anyone"]
• sum
• Returns the sum of all values in a list of numbers
• sum([1, 2.25, 0, -1]) 2.25
• sum([])
• sum([0,1,2,'3'])
• min, max
• consume lists as well
More list operations
>>> dir(list)
[ ..., 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort’]
• Example z “ab”
x=2
y=2–3
z = “a” + “b”
Representing lists in memory
p = [1, 0] + [3]
p 1 0 3
m
Mutate a list
p = []
m = [1, 0] + [3]
null
m.append(5)
p 1 0 3 5
m
Mutate a list
m = [1, 0] + [3]
m.append(5)
m.extend([’a’, 0]) null
p 1 0 3 5 ‘a’ 0
m
Sharing list values
m.append(5)
m.extend([’a’, 0])
null
p=m
p 1 0 3 5 ‘a’ 0
m
You can mutate the existing list with either p or m
m.extend([’a’, 0])
p=m
null
p[1] = 4
p 1 4 3 5 ‘a’ 0
m
What’s the memory like after p = [’abc’] is executed?
m.extend([’a’, 0])
p=m
null
p[1] = 4
p 1 4 3 5 ‘a’ 0
m
What’s the memory like after p = [’abc’] is executed?
p=m
p[1] = 4
null
p = [‘abc’]
p 1 4 3 5 ‘a’ 0
m ‘abc’
Exercise: memory management
def dec(t): n=1
m=n
t=t–1
n=2*m
return t L = [3, 6, 9]
Q=L
p = L[2]
Q[0] = dec(m)
L[1] = dec(Q[2])
L[2] = [True, False]
m = L.append(n)
L = "x"
Functions and List Parameters
def change_first_to_1(L):
L[0] = 1 L
my_list
What is different here?
def change_second_to_1(L):
L = [L[0], 1] + L[2:]
return L
1 2 ‘c’
1 2 ‘c’
m
Example: multiply_by
def multiply_by(vals, multiplier):
‘’’ multiplies each value in vals by multiplier
restrictions: vals contain exactly three Ints
Effects: mutates vals
• matrix multiplication