Week6 of CS61A

Last updated on

3 lectures, 1 lab, 1disc, 1 hw 1. lecture 1. 14. Trees 2. 15. Mutability 3. 16. Iterators 2. lab 1. lab 04 3. disc 1. disc 06 4. hw 1. hw 04


14. Trees

Learning the knowledge of tree abstraction and combining tree and recursion.

And introduce the basic python tree built-in function.

In addition to that, it also talk about the "tree processing".

Reviewing the "key" argument of "min" and "max" function in using on the final mini practice.

image

image

for example as following.

image

image

the diffcult point of lab4

def divide(quotients: list[int], divisors: list[int]) -> dict[int, list[int]]:

"""Return a dictonary in which each quotient q is a key for the list of

divisors that it divides evenly.

  

>>> divide([3, 4, 5], [8, 9, 10, 11, 12])

{3: [9, 12], 4: [8, 12], 5: [10]}

>>> divide(list(range(1, 5)), list(range(20, 25)))

{1: [20, 21, 22, 23, 24], 2: [20, 22, 24], 3: [21, 24], 4: [20, 24]}

"""

return {q: [d for d in divisors if d % q == 0] for q in quotients}

  
  

def buy(fruits_to_buy: list[str], prices: dict[str, int], total_amount: int) -> None:

"""Print ways to buy some of each fruit so that the sum of prices is amount.

  

>>> prices = {'oranges': 4, 'apples': 3, 'bananas': 2, 'kiwis': 9}

>>> buy(['apples', 'oranges', 'bananas'], prices, 12) # We can only buy apple, orange, and banana, but not kiwi

[2 apples][1 orange][1 banana]

>>> buy(['apples', 'oranges', 'bananas'], prices, 16)

[2 apples][1 orange][3 bananas]

[2 apples][2 oranges][1 banana]

>>> buy(['apples', 'kiwis'], prices, 36)

[3 apples][3 kiwis]

[6 apples][2 kiwis]

[9 apples][1 kiwi]

"""

def add(fruits: list[str], amount: int, cart: str) -> None:

if fruits == [] and amount == 0:

print(cart)

elif fruits and amount > 0:

fruit = fruits[0]

price = prices[fruit]

for k in range(1, amount // price + 1):

# Hint: The display function will help you add fruit to the cart.

add(fruits[1:], amount - price * k, cart + display(fruit, k))

add(fruits_to_buy, total_amount, '')

15. Mutability

totally, learning the list mutability.

image

image

the diffcult point of disc04

def has_path(t, p): 

"""

Return whether tree t has a path from the root with labels p. 

>>> t2 = tree(5, [tree(6), tree(7)]) 
>>> t1 = tree(3, [tree(4), t2]) 
>>> 
>>> has_path(t1, [5, 6]) # This path is not from the root of t1 
>>> False 
>>> 
>>> has_path(t2, [5, 6]) # This path is from the root of t2 
>>> True 
>>> 
>>> has_path(t1, [3, 5]) # This path does not go to a leaf, but that's ok >>> True 
>>> 
>>> has_path(t1, [3, 5, 6]) # This path goes to a leaf 
>>> True 
>>> 
>>> has_path(t1, [3, 4, 5, 6]) # There is no path with these labels 
>>> False 

""" 
if p == [lable(t)]: # when len(p) is 1 
	return True 
elif label(t) != p[0]: 
	return False 
else: 
"*** YOUR CODE HERE ***"
	for b in branches(t)
		if has_path(b, p[1:])
			return True
	return False
def only_paths(t, n):

"""Return a tree with only the nodes of t along paths from the root to a leaf of t

for which the node labels of the path sum to n. If no paths sum to n, return None.

>>> print_tree(only_paths(tree(5, [tree(2), tree(1, [tree(2)]), tree(1, [tree(1)])]), 7))

5
	2
	1
		1

>>> t = tree(3, [tree(4), tree(1, [tree(3, [tree(2)]), tree(2, [tree(1)]), tree(5), tree(3)])])

>>> print_tree(only_paths(t, 7))

3
	4
	1
		2
			1
		3

>>> print_tree(only_paths(t, 9))

3
	1
		3
			2
		5

>>> print(only_paths(t, 3))

None

"""

if is_leaf(t) and label(t) == n:
	return t
new_branches = [only_paths(b, n - label(t)) for b in branches(t)]
if any(new_branches):
	return tree(label(t), [b for b in new_branches if b])

A mutation operator and function that modifies the value of an object.

A pure function is a function that does not modify its arguments or other external state.

16. Iterators

learning about iterator, map function, all and any function.

iterator is a class that is iterable.

map function, all and any function are too simple, I don't want to record.

the example is a little difficult for me

image

the difficult point of hw04

def shuffle(s):
"""Return a shuffled list that interleaves the two halves of s.
>>> shuffle(range(6))
[0, 3, 1, 4, 2, 5]
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
>>> shuffle(letters)
['a', 'e', 'b', 'f', 'c', 'g', 'd', 'h']
>>> shuffle(shuffle(letters))
['a', 'c', 'e', 'g', 'b', 'd', 'f', 'h']
>>> letters # Original list should not be modified
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
"""
assert len(s) % 2 == 0, 'len(seq) must be even'
"*** YOUR CODE HERE ***"
# if len(s) == 0 or len(s) == 2:
#     return s
# result = []
# l = len(s)
# s0 = []
# s1 = []
# for i in range(0, l//2):
#     s0.append(s[i])
# for j in range(l//2, l):
#     s1.append(s[j])
# for k in range(0, l):
#     if k % 2 == 0:
#         result.append(s0.pop(0))
#     else:
#         result.append(s1.pop(0))
# return result
half = len(s) // 2
shuffled = []
for i in range(half):
	shuffled.append(s[i])
	shuffled.append(s[half + i])
return shuffled
def max_path_sum(t):
"""Return the maximum root-to-leaf path sum of a tree.
>>> t = tree(1, [tree(5, [tree(1), tree(3)]), tree(10)])
>>> max_path_sum(t) # 1, 10
11
>>> t2 = tree(5, [tree(4, [tree(1), tree(3)]), tree(2, [tree(10), tree(3)])])
>>> max_path_sum(t2) # 5, 2, 10
17
"""
"*** YOUR CODE HERE ***"
if is_leaf(t):
	return label(t)
return label(t) + max(max_path_sum(b) for b in branches(t))
  • Abstraction Barriers: Separate the use of data from its underlying representation.

  • Selectors: Functions that retrieve specific parts of an abstract data object.