>>> empty = 'empty'>>> defis_link(s):"""s is a linked list if it is empty or a (first, rest) pair."""return s == empty or (len(s) == 2and is_link(s[1]))
>>> deflink(first, rest):"""Construct a linked list from its first element and the rest."""assert is_link(rest), "rest must be a linked list."return [first, rest]
>>> deffirst(s):"""Return the first element of a linked list s."""assert is_link(s), "first only applies to linked lists."assert s != empty, "empty linked list has no first element."return s[0]
>>> defrest(s):"""Return the rest of the elements of a linked list s."""assert is_link(s), "rest only applies to linked lists."assert s != empty, "empty linked list has no rest."return s[1]
>>> deflen_link(s):"""Return the length of linked list s."""
length = 0while s != empty:
s, length = rest(s), length + 1return length
>>> defgetitem_link(s, i):"""Return the element at index i of linked list s."""while i > 0:
s, i = rest(s), i - 1return first(s)
树的递归定义
>>> deflen_link_recursive(s):"""Return the length of a linked list s."""if s == empty:
return0return1 + len_link_recursive(rest(s))
>>> defgetitem_link_recursive(s, i):"""Return the element at index i of linked list s."""if i == 0:
return first(s)
return getitem_link_recursive(rest(s), i - 1)
>>> len_link_recursive(four)
4>>> getitem_link_recursive(four, 1)
2
Trees闭包 如果一个组合后的结果可以通过相同的方法对自身再次进行组合,这就是闭包闭包提供给我们对数据进行层次化的能力以树的形式可以规则性的展示具有层次的数据复合结构>>> empty = 'empty'>>> def is_link(s): """s is a linked list if it is empty or a (first, rest) pair."""