- A+

Category：Languages

I want to do a loop that gives factorials from 10 to 1.

So I have this code:

`factorial = 1 for i in range(1,11): factorial = factorial * i print(i,'!=', factorial) `

But this shows results like this:

`1 != 1 2 != 2 3 != 6 `

However I want them this way:

`10 != 3628800 9 != 362880 8 != 40320 `

I've tried few different things but nothing really works, any ideas please?

`results = [] factorial = 1 for i in range(1,11): factorial = factorial * i results.append('{:2,}! = {:,}'.format(i, factorial)) print('/n'.join(reversed(results))) `

Output:

`10! = 3,628,800 9! = 362,880 8! = 40,320 7! = 5,040 6! = 720 5! = 120 4! = 24 3! = 6 2! = 2 1! = 1 `

To reduce the amount of memory required, you could do it like this instead:

`results = [] factorial = 1 for i in range(1, 11): factorial *= i results.append(factorial) for i, value in enumerate(reversed(results)): print('{:2,}! = {:,}'.format(len(results)-i, value)) `

If you like list comprehensions, it could also be done in this somewhat hacky way:

`res = [] res = [res[-1] for x in range(1, 11) if not res.append(x*res[-1] if res else 1)] for i, value in enumerate(reversed(res)): print('{:2,}! = {:,}'.format(len(res)-i, value)) `