Discuss / Python / itertools工具

itertools工具

Topic source

Kirto先森

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

def pi(N): p = itertools.count(1,2) ns = itertools.takewhile(lambda x:x<=2*N-1,p) return sum(map(lambda x:4/x if (x-1)/2%2 == 0 else 4/-x,ns))

遇到的问题:如何将4/x,和4/-x分别作用在ns上 最开始的解决方法是用for循环构造列表生成式,但是怎么弄也弄不出来,最后想了下貌似和之前学的Map吻合。。。

ls平常心

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

def pi(N): ' 计算pi的值 '

# step 1: 创建一个奇数序列: 1, 3, 5, 7, 9, ...
# step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1.
ns = itertools.count(1,2)
n = list(itertools.takewhile(lambda x: x < (2*N-1), ns))
# step 3: 添加正负符号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ...
# step 4: 求和:
return sum(map(lambda x: -4/x if n.index(x)%2 != 0 else 4/x, n))

希泥泥

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

请问最后一行的 n.index(x) 是什么意思?我百度了一下,发现index(x)是查找列表里有无x这个字符串的意思呀


  • 1

Reply