CS 61A lect11
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 | def mul_rational(x, y): |
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 | def rational(n, 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
