Python Forum
computing the factorial of N
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
computing the factorial of N
#11
Functools is built into python: https://docs.python.org/3/library/functools.html
Reduce (other languages call it fold) takes a callable (normally a function), and applies it to two elements from a collection of things repeatedly until there's only one thing left.  ie, it Reduces a collection of things into a single thing.  https://docs.python.org/3/library/functo...ols.reduce

That same snippet, spread out a bit, would look like this:
>>> # the same as lambda x, y: x*y
>>> def multiply(x, y):
...   return x * y
...
>>> fact = 4
>>> items = range(1, fact+1)
>>> # set the starting value to whatever the first element of items is (...hint, it's "1")
>>> answer = next(items)
>>> # iterate over the rest of the range (2, 3, 4) and multiply them together
>>> for num in items:
...   answer = multiply(answer, num)
...
>>> answer
24
Reply
#12
Well, if we're doing factorials, I have to give my evil answer:

def factorial(n, factorials = [1, 1, 2, 6, 24]):
    while n + 1 > len(factorials):
        factorials.append(factorials[-1] *  len(factorials))
    return factorials[n]
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#13
Self-caching, neat.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python Program to Find the Factorial of a Number elisahill 2 1,383 Nov-21-2022, 02:25 PM
Last Post: DeaD_EyE
  computing average in nested loops cap510 5 5,108 Sep-11-2020, 12:33 PM
Last Post: deanhystad
  Fork the process (factorial) vndywarhol 3 3,361 Sep-07-2018, 03:28 AM
Last Post: ichabod801
  Computing average vestkok 2 2,480 Aug-12-2018, 10:02 AM
Last Post: vestkok
  Computing factorials Truman 6 4,013 Mar-14-2018, 06:38 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020