212k views
3 votes
Write a recursive function called print_num_pattern() to output the following number pattern. Given a positive integer as input (Ex: 12), subtract another positive integer (Ex: 3) continually until 0 or a negative value is reached, and then continually add the second integer until the first integer is again reached. For coding simplicity, output a space after every integer, including the last. Do not end output with a newline. Ex. If the input is: 12 3 the output is: 12 9 6 3 0 3 6 9 12

# TODO: Write recursive print_num_pattern() function

if __name__ == "__main__":
num1 = int(input())
num2 = int(input())
print_num_pattern(num1, num2)

2 Answers

2 votes

Final answer:

The student is asked to write a recursive function named print_num_pattern() in Python to output a specific numerical pattern. The function reduces the first input by the second input recursively until reaching 0 or negative, then increases back to the original value.

Step-by-step explanation:

The question involves writing a recursive function named print_num_pattern() that outputs a number pattern by taking two positive integers. The function needs to decrement the first integer by the second integer until it reaches 0 or a negative value, then increment by the second integer until it reaches the original first integer. Here's a Python example of how such a function could be written:

def print_num_pattern(n, m):
if n <= 0:
print(n, end=' ')
return n
else:
print(n, end=' ')
val = print_num_pattern(n-m, m)
if val == n:
return val
else:
print(n, end=' ')
return n

When calling print_num_pattern with the example given (12, 3), it will output: 12 9 6 3 0 3 6 9 12, following the required pattern without ending the output with a newline.

User Eudore
by
3.5k points
5 votes

Answer:

See attachment

Step-by-step explanation:

def print_num_pattern(num1,num2):

if (num1 == 0 or num1 < 0):

print(num1, end = ' ')

return


print(num1, end = ' ')

if num1 - num2 <= 0:

return

print_num_pattern(num1 - num2, num2)

print(num1, end = ' ')

if __name__ == "__main__":

num1 = int(input())

num2 = int(input())

print_num_pattern(num1, num2)

User Dragoon
by
3.2k points