解决方案¶
Wallis 公式求 Pi 的解¶
使用 Wallis 公式计算 Pi 的小数位数
"""
The correction for the calculation of pi using the Wallis formula.
"""
from functools import reduce
pi = 3.14159265358979312
my_pi = 1.0
for i in range(1, 100000):
    my_pi *= 4 * i**2 / (4 * i**2 - 1.0)
my_pi *= 2
print(pi)
print(my_pi)
print(abs(pi - my_pi))
###############################################################################
num = 1
den = 1
for i in range(1, 100000):
    tmp = 4 * i * i
    num *= tmp
    den *= tmp - 1
better_pi = 2 * (num / den)
print(pi)
print(better_pi)
print(abs(pi - better_pi))
print(abs(my_pi - better_pi))
###############################################################################
# Solution in a single line using more advanced constructs (reduce, lambda,
# list comprehensions
print(
    2
    * reduce(
        lambda x, y: x * y,
        [float(4 * (i**2)) / ((4 * (i**2)) - 1) for i in range(1, 100000)],
    )
)
快速排序解决方案¶
实现快速排序算法,如维基百科定义
function quicksort(array)
    var list less, greater
    if length(array) ≤ 1
        return array
    select and remove a pivot value pivot from array
    for each x in array
        if x ≤ pivot then append x to less
        else append x to greater
    return concatenate(quicksort(less), pivot, quicksort(greater))
"""
Implement the quick sort algorithm.
"""
def qsort(lst):
    """Quick sort: returns a sorted copy of the list."""
    if len(lst) <= 1:
        return lst
    pivot, rest = lst[0], lst[1:]
    # Could use list comprehension:
    # less_than      = [ lt for lt in rest if lt < pivot ]
    less_than = []
    for lt in rest:
        if lt < pivot:
            less_than.append(lt)
    # Could use list comprehension:
    # greater_equal  = [ ge for ge in rest if ge >= pivot ]
    greater_equal = []
    for ge in rest:
        if ge >= pivot:
            greater_equal.append(ge)
    return qsort(less_than) + [pivot] + qsort(greater_equal)
# And now check that qsort does sort:
assert qsort(range(10)) == range(10)
assert qsort(range(10)[::-1]) == range(10)
assert qsort([1, 4, 2, 5, 3]) == sorted([1, 4, 2, 5, 3])
斐波那契数列¶
编写一个函数,显示 n 斐波那契数列的前 n 项,定义如下:
- u_0 = 1; u_1 = 1
- u_(n+2) = u_(n+1) + u_n
>>> def fib(n):
...     """Display the n first terms of Fibonacci sequence"""
...     a, b = 0, 1
...     i = 0
...     while i < n:
...         print(b)
...         a, b = b, a+b
...         i +=1
...
>>> fib(10)
1
1
2
3
5
8
13
21
34
55
目录列表解决方案¶
实现一个脚本,以目录名称作为参数,返回 ‘.py’ 文件列表,按名称长度排序。
提示:尝试理解 list.sort 的文档字符串
"""
Script to list all the '.py' files in a directory, in the order of file
name length.
"""
import os
import sys
def filter_and_sort(file_list):
    """Out of a list of file names, returns only the ones ending by
    '.py', ordered with increasing file name length.
    """
    file_list = [filename for filename in file_list if filename.endswith(".py")]
    def key(item):
        return len(item)
    file_list.sort(key=key)
    return file_list
if __name__ == "__main__":
    file_list = os.listdir(sys.argv[-1])
    sorted_file_list = filter_and_sort(file_list)
    print(sorted_file_list)
数据文件 I/O 解决方案¶
编写一个函数,加载 data.txt 中的数字列,并计算最小值、最大值和总和。
数据文件
10.2
43.1
32.6
32.5
61.3
58.2
解决方案
"""
===================
I/O script example
===================
Script to read in a column of numbers and calculate the min, max and sum.
Data is stored in data.txt.
"""
def load_data(filename):
    fp = open(filename)
    data_string = fp.read()
    fp.close()
    data = []
    for x in data_string.split():
        # Data is read in as a string. We need to convert it to floats
        data.append(float(x))
    # Could instead use the following one line with list comprehensions!
    # data = [float(x) for x in data_string.split()]
    return data
if __name__ == "__main__":
    data = load_data("data.txt")
    # Python provides these basic math functions
    print(f"min: {min(data):f}")
    print(f"max: {max(data):f}")
    print(f"sum: {sum(data):f}")
PYTHONPATH 搜索解决方案¶
编写一个程序,在你的 PYTHONPATH 中搜索模块 site.py。
"""Script to search the PYTHONPATH for the module site.py"""
import os
import sys
import glob
def find_module(module):
    result = []
    # Loop over the list of paths in sys.path
    for subdir in sys.path:
        # Join the subdir path with the module we're searching for
        pth = os.path.join(subdir, module)
        # Use glob to test if the pth is exists
        res = glob.glob(pth)
        # glob returns a list, if it is not empty, the pth exists
        if len(res) > 0:
            result.append(res)
    return result
if __name__ == "__main__":
    result = find_module("site.py")
    print(result)