使用递归方法,设计一个函数,用交替的(+)和(-)运算符计算一系列整数1..N的和



根据标题,我被赋予了这个任务来解决。虽然使用传统循环很容易做到这一点,但我仍然不知道如何使用递归来实现这一点。如有任何帮助,我们将不胜感激!

以下是预期结果:

Input: 4
Output: -2
Explanation: 1 -2 + 3 - 4 = -2
Input 9 
Output: -3
Explanation: 1 - 2 + 3 - 4 + 5 - 6 + 7 - 8 + 9 = 5
  1. 您只有一个参数n,它是给定的输入
  2. 你需要记录上一次使用的数字和当前的总和。这可以分别使用参数CCD_ 2和CCD_
  3. 奇数相加,偶数相减

使用以上几点,您可以导出这个简单的算法:

total(i, n, sum):
if i is odd -> sum += i
else -> sum -= i
if i == n -> return sum
else -> return total(i+1, n, sum)
answer = total(1, input, 0)

使用以下逻辑

  1. 如果数字是偶数
  2. 如果数字是奇数,则减去

以下是同一的代码

def summation(n, index=2, total=1):
"""
Summation of alternate (+) and (-) operator
:param n: Input number for which you need a summation of alternate (+) and (-) operator
:param index: Last number which was added in summation.
:param total: Summation of number
"""
if n == 1:
return 1
if index % 2 == 0:
total += index
else:
total -= index
if index == n:
return total
return summation(n, index + 1, total)

print(summation(4)) #It will print output 4
print(summation(9)) #It will print output -3

最新更新