Trying to print the factorial of a number as (5 x 4 x 3 x 2 x1 =120) in python

Viewed 449

I am trying to print the factorial of a number using recursion by printing like this:

5 x 4 x 3 x 2 x 1=120

I just want this (5 X 4 x 3 x 2 x 1) part. I am trying a list comprehension, but not able to join with the "x" sign.

def factorial(n):
    if n==0 or n==1:
        return 1
    else:
        return n*factorial(n-1)

n=(int(input()))
print(([i for i in range(n,0,-1)]),"=",factorial(n))
4 Answers

Try .join:

print((" X ".join(str(i) for i in range(n, 0, -1))), "=", factorial(n))

output:

5 X 4 X 3 X 2 X 1 = 120

.join() will help.

def factorial(n):
        if n==0 or n==1:
            return 1
        else:
            return n*factorial(n-1)

n=(int(input()))
list1=[str(i) for i in range(n,0,-1)]
print(" x ".join(list1),"=",factorial(n))

What you are looking for is join. If you have a list of strings integers = ["1", "2", "3", "4", "5"], you can obtain the string "1 X 2 X 3 X 4 X 5" with the expression " X ".join(integers).

To answer your exact problem the following code works:

n=(int(input()))
print(" X ".join([str(i) for i in range(n,0,-1)]),"=",factorial(n))

note the str(i) part, join would not work with a list of integers

Here is a possible recursive solution (just one line, but you need Python 3.8+):

print((f := lambda n: f'{n} x {f(n - 1)}' if n > 1 else n)(n), '=', factorial(n))
Related