[英]Recursion…I'm stuck
The problem goes like : 问题如下:
Print a sequence of numbers starting with N, without using loop, in which 打印以N开头的数字序列,不使用循环,其中
A[i+1] = A[i] - 5, if A[i]>0, else A[i+1]=A[i] + 5 repeat it until A[i]=N A [i + 1] = A [i] - 5,如果A [i]> 0,否则A [i + 1] = A [i] + 5重复直到A [i] = N
So for input = 16
output is 16 11 6 1 -4 1 6 11 16
input = 10
output is 10 5 0 5 10
I am trying to analyse the solution how it is working once the number gets negative . 我试图分析解决方案,一旦数字变为负数,它是如何工作的。
Here is the solution : 这是解决方案:
def print_pattern(n):
print(n, end=' ')
if n > 0:
print_pattern(n - 5)
else:
return
print(n, end=' ')
T = int(input())
for case in range(T):
N = int(input())
print_pattern(N)
print()
As described, this appears to be an infinite recursion. 如上所述,这似乎是无限递归。 For input = 16: 输入= 16:
16 -> 11 # A[i+1] = A[i] - 5 (> 0)
11 -> 6 # A[i+1] = A[i] - 5 (> 0)
6 -> 1 # A[i+1] = A[i] - 5 (> 0)
1 -> -4 # A[i+1] = A[i] - 5 (> 0)
-4 -> 1 # A[i+1] = A[i] + 5 (<= 0)
1 -> -4 # A[i+1] = A[i] - 5 (> 0)
-4 -> 1 # A[i+1] = A[i] + 5 (<= 0)
etc.
so you'll never get an output of "16 11 6 1 -4 1 6 11 16"
. 所以你永远不会得到"16 11 6 1 -4 1 6 11 16"
。 Reread your problem and verify the rules. 重新阅读您的问题并验证规则。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.