I have a function that prints the first multiples of a number (n) starting with zero and stopping at num_multiples, but it keeps printing out one too many multiples. I'm hoping someone can explain what I'm doing wrong so I can understand recursion a bit more.
def print_first_multiples(n, num_multiples):
if num_multiples < 0:
return
else:
print_first_multiples(n, num_multiples - 1)
print(n * num_multiples, end=' ')
for example, passing 5 as n and 10 as num_multiples, it should print:
0 5 10 15 20 25 30 35 40 45
but is instead printing an extra "50" at the end.
CodePudding user response:
First, 0 is not a multiple of 5. The first multiple of 5 is 5 (5*1). The problem with your code is that you only stop when num_multiples
is negative (less than 0). Instead, you want to stop when it is zero. Like this:
def print_first_multiples(n, num_multiples):
if num_multiples == 0:
return
else:
print_first_multiples(n, num_multiples - 1)
print(n * num_multiples, end=' ')
print_first_multiples(5, 10)
If you do want to start at 0 and go up to 45, then you can subtract one from num_multiples
. Like this:
def print_first_multiples(n, num_multiples):
if num_multiples == 0:
return
else:
print_first_multiples(n, num_multiples - 1)
print(n * (num_multiples-1), end=' ')
print_first_multiples(5, 10)
CodePudding user response:
Try if num_multiples <= 0: instead
CodePudding user response:
It prints until it doesn't enter if num_multiples < 0
. So e.x. with the initial value num_multiples = 3
you print for num_multiples=3
, num_multiples=2
, num_multiples=1
, and num_multiples=0
so 4 times. Replace if num_multiples < 0
with if num_multiples == 0
and you'd get what you expect