Discuss / Python / (⊙v⊙)写得复杂,还是要贴

(⊙v⊙)写得复杂,还是要贴

Topic source

烈可烈

#1 Created at ... [Delete] [Delete and Lock User]
# 生成奇数
def init_odd():
    n = 1
    while True:
        yield n
        n = n + 2

# 生成4、-4
natural_num = itertools.count(1)
def operate(num):
    n = next(natural_num)
    if n % 2 != 0:
        return 4 / num
    else:
        return -4 / num

# 前戏准备完毕
def pi(N):
    # step 1: 创建一个奇数序列: 1, 3, 5, 7, 9, ...
    o = init_odd()
    # step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1.
    odd_n = itertools.takewhile(lambda x: x <= 2*N-1, o)
    # step 3: 添加正负符号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ...
    map_n = map(operate, odd_n)
    # step 4: 求和:
    result = reduce(lambda x, y: x + y, map_n)
    return result

`


  • 1

Reply