'Writing a recursive case
How do I complete this recursive function at output_string += ? Output should be: 5! = 5 * 4 * 3 * 2 * 1 = 120
def print_factorial(fact_counter, fact_value):
output_string = ''
if fact_counter == 0: # Base case: 0! = 1
output_string += '1'
elif fact_counter == 1: # Base case: print 1 and result
output_string += str(fact_counter) + ' = ' + str(fact_value)
else: # Recursive case
output_string += str(fact_counter) + ' * '
next_counter = fact_counter - 1
next_value = next_counter * fact_value
output_string +=
return output_string
user_val = 5
print('%d! = ' % user_val, end="")
print(print_factorial(user_val, user_val))
Solution 1:[1]
def print_factorial(fact_counter, fact_value):
output_string = ''
if fact_counter == 0: # Base case: 0! = 1 #This line will never execute, no recursive call will ever be made with fact_counter = 0 and there shouldn't be anyways, so its harmless.
output_string += '1'
elif fact_counter == 1: # Base case: print 1 and result
output_string += str(fact_counter) + ' = ' + str(fact_value)
else: # Recursive case
output_string += str(fact_counter) + ' * '
next_counter = fact_counter - 1
next_value = next_counter * fact_value
output_string += print_factorial(next_counter, next_value)
return output_string
user_val = 5
print('%d! = ' % user_val, end="")
print(print_factorial(user_val, user_val))
You needed to compute the next number in the factorial then add it with "*" too. So a recursive call should be made at the concatenation statement.
Umm, if fact_counter == 0, will NEVER execute and I've written a comment to point this out inside the code.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Raafat Abualazm |