Discuss / Python / 测试通过

测试通过

Topic source
from functools import reduce

def add(x, y):
    return x + y 
def pi(N):
    ' 计算pi的值 '
    # step 1: 创建一个奇数序列: 1, 3, 5, 7, 9, ...
    natual = itertools.count(1,2)
    # step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1.
    selectArr=[]
    i=0
    for n in natual:
        if(i>=N):
            break
        selectArr.append(n)
        i+=1
    print(selectArr)
    # step 3: 添加正负符号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ...
    anther=[]
    onebyone=itertools.cycle([1,-1])
    processdata=map(lambda x,y:4.0*y/x,selectArr,onebyone )
    # step 4: 求和:
    sum=reduce(add,processdata)
    return sum

  • 1

Reply