I have implemented a function to calculate the factorial from 1 to n(where n is the user input) by making a list, using recursion. And I want to print a line of k factorial stars for each integer k in range of 1 to n by defining a new function that calls itself recursively inside the main function. The output should be as follows if n=3:
*
**
******
Here is my code so far to calculate the factorial using recursion:
#Ask the user to input a positive integer n
n=int(input("Enter positive integer: "))
#Defining a function to calculate the factorial of a input number
def factorialN(n):
#Defining the base case
if n==1:
#If it satisfy the base condition return a list containing 1
return [1]
#Calling the function factorialN() recursively
list_1=factorialN(n-1)
new_factorial=list_1[-1]*n
list_1.append(new_factorial)
return list_1
So I'm having a hard time in implementing the function to print the factorial stars("*"). Any help is much appreciated, as I'm a beginner in Python. Thanks in advance.
The function you wrote returns a list containing which line should have how many '*'s.
For n = 3
it returns: [1, 2, 6]
so to print them:
for x in output:
print('*'*x) # print * x times
I agree with @Anonta's printing solution (+1), but if your only goal is to print stars, and not collect factorials into a list, then you can incorporate the printing into your code and simplify everything:
def factorialN(n):
if n != 1:
n *= factorialN(n - 1)
print(n * '*')
return n
number = int(input("Enter positive integer: "))
factorialN(number)
USAGE
Enter positive integer: 4
*
**
******
************************
Plus, as a bonus, factorialN(n)
returns the factorial of n
as a number!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.