asked 56.8k views
3 votes
I have some of the code down, but I need to figure out what I am missing... The code output is 12 9 6 3 6 9 12, when I need the additional 3 and 0 included in the output.

----
Original prompt:
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

------
Code - Python:

# TODO: Write recursive print_num_pattern() function
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)

asked
User Hamed Aj
by
8.9k points

1 Answer

2 votes

Answer:

To get the additional 3 and 0 included in the output, you can modify the code as follows:

# TODO: Write recursive print_num_pattern() function

def print_num_pattern(num1,num2):

if num1 < 0:

print(num1, end = ' ')

return

print(num1, end = ' ')

print_num_pattern(num1 - num2, num2)

print(num1, end = ' ')

if num1 == num2:

print(0, end = ' ')

return

print_num_pattern(num1 + num2, num2)

print(num1, end = ' ')

if __name__ == "__main__":

num1 = int(input())

num2 = int(input())

print_num_pattern(num1, num2)

Step-by-step explanation:

answered
User Mandela
by
8.3k points

No related questions found