0

I have stumbled across a problem that requires the use of the "Unknown formula".

Referenced here: http://www.murderousmaths.co.uk/books/unknownform.htm

I have looked high and low and have not found an equivalent python symbol for "!" in the manner the author is using it.

# Example of authors use of '!'
5! == 5x4x3x2x1

I know that I could use a loop to create it, like in this post: Sum consecutive numbers in a list. Python

But I am hoping to make this a learning moment.


edit

There is a great thread about factorials (Function for Factorial in Python), however I much prefer The solution answer provided below. Very clear and concise.

Cory
  • 49
  • 6
  • 1
    [`math.factorial()`](https://docs.python.org/3/library/math.html?highlight=factorial#math.factorial) – AChampion Feb 05 '19 at 01:41
  • 1
    The ! represents the [factorial](https://en.wikipedia.org/wiki/Factorial). It’s in Python as [`math.factorial`](https://docs.python.org/3/library/math.html#math.factorial). – Ry- Feb 05 '19 at 01:41

1 Answers1

1

This is a mathematical function called a factorial, and is covered in depth in another question.

The simplest approach is:

import math
math.factorial(5)

A functional approach:

from functools import reduce
import operator
answer = reduce(operator.mul, range(1, 6))

Loop approach:

answer = 1
for i in range(5):
    answer *= i+1

Another answer uses a list comprehension.

ajrwhite
  • 7,728
  • 1
  • 11
  • 24