SICP-2-序列

序列


  • 序列是值的有序集合
  • 序列的共同特性
    • 序列的长度
    • 序列的选择器

LIST

 - list相互之间可以进行+,list可以与整数相乘
digits = [1,8,2,8]
[2, 7] + digits * 2
[2, 7, 1, 8, 2, 8, 1, 8, 2, 8]
 - 任何值都可以包含在list之内包括另一个list
>>> pairs = [[10, 20], [30, 40]]
>>> pairs[1]
[30, 40]
>>> pairs[1][0]
30

列表的迭代


>>> def count(s, value):
        """Count the number of occurrences of value in sequence s."""
        total, index = 0, 0
        while index < len(s):
            if s[index] == value:
                total = total + 1
            index = index + 1
        return total
>>> count(digits, 8)
2
def count(s, value):
        """Count the number of occurrences of value in sequence s."""
        total = 0
        for elem in s:
            if elem == value:
                total = total + 1
        return total
>>> count(digits, 8)
2
  • 序列中的for循环
for <name> in <expression>:
    <suite>
 - 评估<expression>
 - 将<expression>中的值与name绑定
 - 执行<suite>

序列的解包

>>> pairs = [[1, 2], [2, 2], [2, 3], [4, 4]]
>>> same_count = 0
>>> for x, y in pairs:
        if x == y:
            same_count = same_count + 1
>>> same_count
2

Ranges——range(,)

>>> range(1, 10)  # Includes 1, but not 10
>>> list(range(5, 8))
[5, 6, 7]

如果只给定一个参数,这个参数默认为end,而start默认为0

>>> list(range(4))
[0, 1, 2, 3]

Ranges也经常出现在表头,用于指定迭代的次数

>>> for _ in range(3):
        print('Go Bears!')

Go Bears!
Go Bears!
Go Bears!

对序列进行操作

  • 对于序列操作的理解
    • 对列表的中的每个元素执行相应的操作
    • 操作的结果返回到列表相应的位置
>>> odds = [1, 3, 5, 7, 9]
>>> [x+1 for x in odds]
[2, 4, 6, 8, 10]
 - [<map expression> for <name> in <sequence expression> if <filter expression>]

     - <map expression>为对序列中的每个元素进行的操作
     - <filter expression>满足该条件执行操作
  • 例如:完美数——其本身等于他的所有除数之和
>>> def divisors(n):
        return [1] + [x for x in range(2, n) if n % x == 0]
>>> [n for n in range(1, 1000) if sum(divisors(n)) == n]
[6, 28, 496]
  • 例如:给定一个矩形的面积,求这个矩形的最小周长
>>> def width(area, height):
        assert area % height == 0
        return area // height

>>> def perimeter(width, height):
        return 2 * width + 2 * height

>>> def minimum_perimeter(area):
        heights = divisors(area)
        perimeters = [perimeter(width(area, h), h) for h in heights]
        return min(perimeters)

>>> area = 80
>>> minimum_perimeter(area)
36
  • 高阶函数形式
def apply_to_all(map_fn,s):
    return [map_fn(x) for x in s]

def keep_if(filter_fn,s):
    return [x for x in s if filter_fn(x)]

def reduce(reduce_fn,s,initial):
    reduced = initial
    for x in s
        reduced = reduce_fn(reduced,x)
    return reduced

reduce(mul,[2,4,8],1)
64
def divisors_of():
    divisors_n = lambda x : n % x == 0
    return [1] + keep_if(divisors_n,range(2,n))

from operator import add
def sum_of_divisors(n):
    return reduce(add,divisors_of(n),0)

def perfect_num():
    perfect_n = lambda n : sum_of_divisors(n) == n
    return keep_if(perfect_n,divisors_of(n))

序列的抽象


  • 成员
    • in 和 not in
  • 切片

猜你喜欢

转载自blog.csdn.net/a245293206/article/details/73716904