伯克利 CS61A 课堂笔记 04 —— Iteration and Recursive Functions

本系列为加州伯克利大学著名 Python 基础课程 CS61A 的课堂笔记整理,全英文内容,文末附词汇解释。

目录

01 Iteration 迭代

Example 1-1: Prime Factorization 质因数分解

Example 1-2: The Fibonacci Sequence 斐波那契数列

02 Recursive Functions 递归函数

Example 2-1: Sum Digits Without a While Statement

Example 2-2: Inverse Cascade

Example 2-3: Fibonacci Number

Example 2-4: Counting Partitions

附:词汇解释


01 Iteration 迭代

i, total = 0, 0
while i < 3:
    i = i + 1
    total = total +i
i
total
Example 1-1: Prime Factorization 质因数分解

Each positive integer n has a set of prime factors: primes whose product is n.

def prime_factors(n):
    """Print the prime factors of n in non-decreasing order.
    
    >>> prime_factor(8)
    2
    2
    2
    >>> prime_factor(9)
    3
    3
    >>> prime_factor(10)
    2
    5
    >>> prime_factor(11)
    11
    >> prime_factor(12)
    2
    2
    3
    >> prime_factor(858)
    2
    3
    11
    13
    """
    
    while n > 1:
        k = smallest_prime_order(n)
        n = n // k
        print(k)
       
def smallest_prime_order(n):
    """Return the smallest k > 1 that evently divideds n"""
    k = 2
    while n % k != 0:
        k = k+1
    return k
Example 1-2: The Fibonacci Sequence 斐波那契数列

0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987

def fib(n):
    """Compute the nth Fibonacci number, for N >= 1."""
    pred, curr = 0, 1
    k = 1
    while k < n:
        pred, curr = curr, pred + curr
    return curr

def fib2(n):
    """Comp
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值