[2021 Spring] CS61A 學習筆記 lecture 11 Sequences (II) and Data Abstraction
阿新 • • 發佈:2021-06-25
課本: http://composingprograms.com/pages/22-data-abstraction.html
這節課主要內容是序列的特性和資料抽象。
Sequence(II)
Multiple Variables
for迴圈中的迭代變數就像是賦值語句的左半邊式子:
Two Iterations at Once!(zip函式)
zip函式可以將多個序列進行組合,實際上返回一個生成器
Modifying Lists
列表是可變序列,可以分配元素和切片。
List Comprehensions
列表的完整形式:
[<expression> for <var> in <sequence expression> if <boolean expression>]
exercise
def matches(a, b): """Return the number of values k such that A[k] == B[k]. >>> matches([1, 2, 3, 4, 5], [3, 2, 3, 0, 5]) 3 >>> matches("abdomens", "indolence") 4 >>> matches("abcd", "dcba") 0 >>> matches("abcde", "edcba") 1 >>> matches("abcdefg", "edcba") 1 """ return sum([1 for x, y in zip(a, b) if x==y]) def triangle(n): """Assuming N >= 0, return the list consisting of N lists: [1], [1, 2], [1, 2, 3], ... [1, 2, ... N]. >>> triangle(0) [] >>> triangle(1) [[1]] >>> triangle(5) [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]] """ return [list(range(1, i + 1)) for i in range(1, n+1)]
Data Abstraction
Philosophy
ADT(abstract data type): 抽象資料型別
Classification
分類:構造器、訪問器、修改器
Rational Numbers
書中將有理數作為ADT的例子。
# Rationals from math import gcd def make_rat(n, d): """The rational number N/D, assuming N, D are integers, D!=0""" g = gcd(n, d) n //= g; d //= g return (n, d) def numer(r): """The numerator of rational number R in lowest terms.""" return r[0] def denom(r): """The denominator of rational number R in lowest terms. Always positive.""" return r[1] def add_rat(x, y): return make_rat(numer(x) * denom(y) + numer(y) * denom(x), denom(x) * denom(y)) def mul_rat(x, y): return make_rat(numer(x) * numer(y), denom(x) * denom(y)) def str_rat(r): # (For fun: a little new Python string magic) return str(numer(r)) if denom(r) == 1 else f"{numer(r)}/{denom(r)}" def equal_rat(x, y): return numer(x) * denom(y) == numer(y) * denom(x)
Layers of Abstraction
抽象界限:界限上層不會用到下層的操作,界限下層只用到上一層的操作。