Discuss / Python / 作业

### 作业

Topic source

#### 月半意

#1 Created at ... [Delete] [Delete and Lock User]
def pi(N):

' 计算pi的值 '
# step 1: 创建一个奇数序列: 1, 3, 5, 7, 9, ...
odd = itertools.count(1,2)
# step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1.
natuals = itertools.takewhile(lambda x: x<=2*N-1,odd)
# step 3: 添加正负符号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ...
# step 4: 求和:
result = 0
i = 0
for x in natuals:
result += 4/x * pow(-1,i)
i += 1
return result

#### 月半意

#2 Created at ... [Delete] [Delete and Lock User]
from functools import reduce
def pi(N):

' 计算pi的值 '
# step 1: 创建一个奇数序列: 1, 3, 5, 7, 9, ...
odd = itertools.count(1,2)
# step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1.
natuals = itertools.takewhile(lambda x: x<=2*N-1,odd)
# step 3: 添加正负符号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ...
# step 4: 求和:
result = reduce(lambda x:(-1)**round(x%4/4)*4/x,natuals)
return result

#### BigPistachio

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

result = reduce(lambda x, y:(-1)**round(x%4/4)*4/x + (-1)**round(y%4/4)*4/y, natuals)

• 1