Discuss / Python / 打卡

打卡

Topic source

果味II0

#1 Created at ... [Delete] [Delete and Lock User]

def pi(N):

# 创建奇数数列
natuals = itertools.count(1, 2)
# 获取数列的前N项
ns = itertools.takewhile(lambda x: x <= 2 * N - 1, natuals)
# 用4除并添加正负号,并求和
# 笨办法
# index = 0
# ji_sum = 0
# for n,m in ns,:
#     if index % 2 == 0:
#         n = 4 / n
#     else:
#         n = -4 / n
#     index += 1
#     ji_sum += n
# 高级办法
fuhao = itertools.cycle([1,-1])
data = map(lambda x, y: 4.0 * y / x, list(ns), fuhao)
ji_sum = reduce(lambda x,y:x+y,data)
return ji_sum

  • 1

Reply