Discuss / Python / 作业(第一次自己比CopilotX写的简洁)

作业(第一次自己比CopilotX写的简洁)

Topic source

Super-String

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

我写的:

def pi(N):

    odds=itertools.count(1,2)
    ns=itertools.takewhile(lambda x: x<=2*N-1,odds)
    return sum(4/n*(-1)**((n-1)//2) for n in ns)

CopilotX:

def pi(N):
    '计算pi的值'
    # step 1: 创建一个奇数序列: 1, 3, 5, 7, 9, ...
    odd_numbers = itertools.count(1, 2)
    # step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1.
    odd_numbers = itertools.islice(odd_numbers, N)
    # step 3: 添加正负符号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ...
    series = (4 / n * (-1) ** (i % 2) for i, n in enumerate(odd_numbers))
    # step 4: 求和:
    return sum(series)

其实也差不多,就是copilot用了不少其他方法,值得学习


  • 1

Reply