[2021 Spring] CS61A 学习笔记 lecture 9 Function Examples

Posted ikventure

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[2021 Spring] CS61A 学习笔记 lecture 9 Function Examples相关的知识,希望对你有一定的参考价值。

lecture 9 Function Examples
课本: http://composingprograms.com/pages/16-higher-order-functions.html

Exercise: Reversing Digits

反转数字(不使用字符串、数组)

def reverse_digits(n):
    """Assuming N >= 0 is an integer.  Return the number whose
    base-10 representation is the reverse of that of N.
    >>> reverse_digits(0)
    0
    >>> reverse_digits(1)
    1
    >>> reverse_digits(123)
    321
    >>> reverse_digits(10)
    1
    >>> reverse_digits(12321)
    12321
    >>> reverse_digits(2222222)
    2222222
    >>> reverse_digits(102)
    201
    """
    assert type(n) is int and n >= 0
    if n < 10:
        return n
    return reverse_digits(n // 10) + (n % 10) * 10 ** (num_digits(n) - 1)

def num_digits(x):
    """Return the number of decimal digits in the positive integer X."""
    x_count = 1
    while x >= 10:
        x_count += 1
        x //= 10
    return x_count

Exercise: Interleaving Digits

交错数字

def interleave(a, b):
    """Assuming A and B are non-negative integers with the same 
    number of base-10 digits, return the number whose base-10 
    representation is the interleaving of A\'s and B\'s digits,
    starting with A.
    >>> interleave(1, 2)
    12
    >>> interleave(0, 1)
    1
    >>> interleave(1, 0)
    10
    >>> interleave(123,456)
    142536
    >>> interleave(111111, 222222)
    121212121212
    """
    if a <= 9:
        return a * 10 + b
    return interleave(a // 10, b // 10) * 100 + interleave(a % 10, b %10)

Environment Detective

从环境模型推导原始代码

Exercise: Tracing

(课件上有,要下课了,大概率推到lecture 10)

以上是关于[2021 Spring] CS61A 学习笔记 lecture 9 Function Examples的主要内容,如果未能解决你的问题,请参考以下文章

[2021 Spring] CS61A 学习笔记 lecture 10 containers and sequences

CS61A学习笔记 lecture1 Computer science

[2021 Spring] CS61A Discussion 5: Python Lists, Trees, Mutability

[2021 spring] CS61A Lab 2: Higher-Order Functions, Lambda Expressions

CS61A 学习笔记 lecture 6 recursion

[2021 Spring] CS61A Project 1: The Game of Hog (Phase 3)