Recursive Pattern

Description Given a positive integer 'n' and another positive integer 'k' (<n),  print the following pattern using recursion.

Example:
Input 1: n = 12, k = 5
Output 2: 12, 7, 2, -3, 2, 7, 12

Input 2: n = 10, k =2
Output 2: 10, 8, 6, 4, 2, 0, 2, 4, 6, 8, 10

Basically, you need to keep decrementing the given value of 'n' by 'k' until you encounter 0 or a negative number, in which case, you need to start incrementing by 'k' until you reach 'n' again.

Format:
Input: The first line contains the positive integer 'n'. The second line contains the positive integer 'k'.
Output: The required pattern as comma-separated-values as shown in the examples above.

Jun 22, 2020 in Python 6,371 views

## 2 answers to this question.

+1 vote
```n = int(input("please enter your no:"))
k = int(input("please enter ypur no:"))
m = []
for i in range(0,n*2+k,k):
if n-i >= 0:
a = n-i
m.append(a)
elif n-i < 0:
a = n-i
a = a + a*-2
m.append(a)
for i in m:
print(i,end=",")```
• 340 points
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)
answered Aug 31, 2020 by Shweta Patil

## How to create the following pattern using Python?

Hi, @Roshni, You can use two for-loops for ...READ MORE

## How to make a laplacian pyramid using OpenCV python?

down voteacceptTheeThe problem is that you're iterating ...READ MORE

## How can I play an audio file in the background using Python?

down voteacceptedFor windows: you could use  winsound.SND_ASYNC to play them ...READ MORE

## how can i randomly select items from a list?

You can also use the random library's ...READ MORE

+1 vote

## how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE