The problem goes like :
Print a sequence of numbers starting with N, without using loop, in which
A[i+1] = A[i] - 5, if A[i]>0, else A[i+1]=A[i] + 5 repeat it until 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 -> 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"
. Reread your problem and verify the rules.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.