本系列为加州伯克利大学著名 Python 基础课程 CS61A 的课堂笔记整理,全英文内容,文末附词汇解释。
目录
Example 1-1: Prime Factorization 质因数分解
Example 1-2: The Fibonacci Sequence 斐波那契数列
Example 2-1: Sum Digits Without a While Statement
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

最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



