import itertools
def pi(N):
# step 1: 创建一个奇数序列: 1, 3, 5, 7, 9, ...
jishu=itertools.count(1,2)
# step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1.
jishu_n=itertools.takewhile(lambda x:x<=(2*N-1),jishu)
# step 3: 添加正负符号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ...
end=map(lambda x:(-1)**((x+1)/2+1)*(4/x),jishu_n)
# step 4: 求和:
return sum(end)
复习了map()函数。map(x,y)是把y变为x,而itertools.takewhile是从y里面挑出x。所以如果把step 3中map改为itertools.takewhile就会报错。
Sign in to make a reply
XERIN24040
import itertools
def pi(N):
# step 1: 创建一个奇数序列: 1, 3, 5, 7, 9, ...
jishu=itertools.count(1,2)
# step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1.
jishu_n=itertools.takewhile(lambda x:x<=(2*N-1),jishu)
# step 3: 添加正负符号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ...
end=map(lambda x:(-1)**((x+1)/2+1)*(4/x),jishu_n)
# step 4: 求和:
return sum(end)
复习了map()函数。map(x,y)是把y变为x,而itertools.takewhile是从y里面挑出x。所以如果把step 3中map改为itertools.takewhile就会报错。