翻阅古今
def calculateFraction(num): if (num > 0): return (-1)**(num) * 1/(num*2+1) + calculateFraction(num-1) else: return 1print(4 * calculateFraction(10))编辑奥利维尔的回答非常好,我希望我可以多次投票。鉴于此,我认为 OP 可能会从上述方法的二进制实现中受益。也就是说,每当递归时,将问题的一半发送到一个分支,另一半发送到另一个分支。 (这意味着,例如,要求 num=15 将导致深度为 4 而不是深度为 16。)import inspectdef calculateFraction(num, end=0): result = 0 depth = 'Depth({:d}){:s}>'.format(len(inspect.stack())-1, '='*(len(inspect.stack())-1)*2) # If there are an odd number of parts to calculate, do the highest one now if (((num-end+1)&1) == 1): result += ((-1)**(num)) / (num*2+1) print('{:s} Fraction part {:d} = {:f}'.format(depth, num, result)) num-=1 # If there are still any parts to calculate, do them recursively # (There must be an even number, as we did the odd one previously) # (That may leave 0 still to do, in which case the recursion is skipped) if (num > end): mid = ((num-end)>>1) + end # Do the upper half of the remaining parts print('{:s} Recursing to {:d},{:d}'.format(depth, num, mid+1)) result += calculateFraction(num, mid+1) # Do the lower half of the remaining parts print('{:s} Recursing to {:d},{:d}'.format(depth, mid, end)) result += calculateFraction(mid, end) return resultprint('Result: {:f}'.format(4*calculateFraction(10)))