CS61A lect11 data abstraction

•rational(n, d) returns a rational number x
•numer(x) returns the numerator of x
•denom(x) returns the denominator of x
(These functions implement an abstract representation for rational numbers)
for whole data:

1
2
3
4
5
6
7
8
9
10
11
def mul_rational(x, y): 
return rational(numer(x) * numer(y),
denom(x) * denom(y))
def add_rational(x, y):
nx, dx = numer(x), denom(x)
ny, dy = numer(y), denom(y)
return rational(nx * dy + ny * dx, dx * dy)
def print_rational(x):
print(numer(x), '/', denom(x))
def rational(n, d):
"""Construct a rational number that represents N/D."""

for a part of data:(do not combine these with above)

1
2
3
4
5
6
7
8
 return [n, d]
def numer(x):
"""Return the numerator of rational number X."""
return x[0]
def denom(x):
"""Return the denominator of rational number X."""
return x[1]
'''

实际操作:尽量不要用直接赋值, 要用constructor和dominator!!!
another approach: use dictionary-like functions

1
2
3
4
5
6
7
8
9
10
11
def rational(n, d): 
def select(name):
if name == 'n':
return n
elif name == 'd':
return d
return select
def numer(x):
return x('n')
def denom(x):
return x('d')

dictionary(taught in high school)
different:
dic.keys()—list of all the keys
dic.values()—list of all the values
dic.items()—list of all the items
dict(items)—from list to dict

Dictionaries are unordered collections of key-value pairs
Dictionary keys do have two restrictions:
•A key of a dictionary cannot be a list or a dictionary (or any mutable type)
•Two keys cannot be equal; There can be at most one value for a given key
This first restriction is tied to Python’s underlying implementation of dictionaries
The second restriction is part of the dictionary abstraction
If you want to associate multiple values with a key, store them all in a sequence value