if not isinstance(N, int):
raise ValueError("请输入一个整数!")
L = [x for x in range(2 * N + 1) if x % 2 != 0]
s = 0
n = 0
for i in L:
s += 4 / (((-1) ** n) * i)
n += 1
return s
测试结果:
3.0418396189294032
3.1315929035585537
3.140592653839794
3.1414926535900345
ok
然后倒回去参考了一部分答案
自己也写了一个符合题目的:
def pi_2(N):
odd = itertools.count(1, 2) # 从一开始 每隔一位取一次
nl = itertools.takewhile(lambda x: x <= 2 * N - 1, odd)
temp = map(lambda x: 4 / x if (x + 1) % 4 != 0 else -4 / x, nl)
s = 0
for i in temp:
s += i
return s
I-cpp
这是...都还没用到itertools的想法:
def pi(N):
测试:
print(pi(10)) print(pi(100)) print(pi(1000)) print(pi(10000)) assert 3.04 < pi(10) < 3.05 assert 3.13 < pi(100) < 3.14 assert 3.140 < pi(1000) < 3.141 assert 3.1414 < pi(10000) < 3.1415 print('ok')
测试结果: 3.0418396189294032 3.1315929035585537 3.140592653839794 3.1414926535900345 ok
然后倒回去参考了一部分答案 自己也写了一个符合题目的:
def pi_2(N):
测试:
print(pi_2(10)) print(pi_2(100)) print(pi_2(1000)) print(pi_2(10000)) assert 3.04 < pi_2(10) < 3.05 assert 3.13 < pi_2(100) < 3.14 assert 3.140 < pi_2(1000) < 3.141 assert 3.1414 < pi_2(10000) < 3.1415 print('ok')
测试结果:
3.0418396189294032 3.1315929035585537 3.140592653839794 3.1414926535900345 ok
ps:匿名函数在这里还是蛮有用的