Algorithmically
: divide-and-conquer
Semantically
: function calls itself
In programming, goal is to not have infinite recursion
: must hae 1 ro more base cases
: must soleve the same problem on some other input with the goal of simplifying the larger problem input
def mult_iter(a, b) :
result = 0
while b > 0:
result += a
b -= 1
return result
def mult(a,b) :
if b == 1:
return a
else :
return a + mult(a, b-1)
def factorial_iter(n) :
prod = 1
for i in range(1, n+1) :
prod *= i
return prod
def factorial(n) :
if n == 1 :
return 1
else :
return n * factorial(n-1)
Base cases
: F(0) = 1
: F(1) = 1
Recursive case
: F(n) = F(n-1) + F(n-2)
def fib(x) :
"""
assumes x an int >= 0
returns Fibonacci of x
"""
if x == 0 or x == 1 :
return 1
else :
return fib(x-1) + fib(x-2)
자료구조나 알고리즘에서 배우겠지만, 이미 계산했던 base case나 fibonacci value를 다시 계산해야하는 자원 낭비가 일어난다.
my_dict = {} # empty dictionary
grades = {'Ana' : 'B', 'John' : 'A+', 'Denise' : 'A', 'Katy' : 'A'}
print(grades['John']) # A+
# print(grades['Sylvan']) : this code will give error
my_dict = {} # empty dictionary
grades = {'Ana' : 'B', 'John' : 'A+', 'Denise' : 'A', 'Katy' : 'A'}
# add an entry
grades['Sylvan'] = 'A'
print(grades) # {'Ana': 'B', 'John': 'A+', 'Denise': 'A', 'Katy': 'A', 'Sylvan': 'A'}
# test if key is in dictionary
print('John' in grades) # True
print('Daniel' in grades) # False
# delete entry
del(grades['Ana'])
print(grades) # {'John': 'A+', 'Denise': 'A', 'Katy': 'A', 'Sylvan': 'A'}
# get all keys
print(grades.keys()) # dict_keys(['John', 'Denise', 'Katy', 'Sylvan'])
# no guaranteed order
print(type(grades.keys())) # <class 'dict_keys'>
# get all values
print(grades.values()) # dict_values(['A+', 'A', 'A', 'A'])
# no guaranteed order
print(type(grades.values())) # <class 'dict_values'>