My approach:
def pattern(n):
if n<0:
return n
print(n)
else:
print(n)
print(", ")
pattern(n-k)
print(", ")
print(n)
Read the instructions again, and think about what you have to do.
I would write two functions: one to go "down", and one to go "up". Then call them both, one after the other.
Pass it three values: a current value, a decrement, and a "separator". In this case, a return value isn't needed (nor is recursion, this is a load simpler as a loop).
The first time you call down, pass it n and an empty string.
in the function, print the separator, then the current value.
Now decrement the current value and check it. If it's less than zero, return.
Otherwise, call the function again with the new current value, the same decrement, and teh separator of ", ".
The "Up" function is the same, but going the other way.
Try it on paper manually first, and you'll see what I mean - then start coding.
# Reading the input
n = int(input())
k = int(input())
# Define the function
def pattern(n, m, k):
# Base case. If m <= 0, print m and return from the function
if m <= 0:
print(m, end = ", ")
return
# Print m, call the recursive function with (n, m-k, k), and then print m again
print(m, end = ", ")
pattern(n, m-k, k)
# This conditional statement has been used so that you do not print a comma
# after the last element.
if(n != m):
print(m, end = ", ")
else:
print(m)
# Declaring another variable m equal to n
m = n
# Calling the function with 3 arguments - n, m, and k. The extra m will be used
# for recursive calls. The n will be preserved because if you check the output
# format, you will see that after the last element, you shouldn't print a comma.
# The value of 'n' in the function will be used primarily for that.
pattern(n, m, k)
Hi All,
After the above logics it's perfectly works but I see None is appended with it. How to handle with that.
def pattern(n):
if n<=0: # test must include 0
print(n, end= '')
else:
print(n, end= '')
print(", ", end= '')
pattern(n-k)
print(", ", end= '')
print(n, end= '')
Output:
Solution output
10, 8, 6, 4, 2, 0, 2, 4, 6, 8, 10None
Expected output
10, 8, 6, 4, 2, 0, 2, 4, 6, 8, 10
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)