Can you write a factorial function?

11 replies on 1 page. Most recent reply: Jan 14, 2017 12:50 PM by frederick 99

 Flat View: This topic has 11 replies on 1 page
 Ivo Rocha Posts: 4 Nickname: silicio Registered: Oct, 2004
Can you write a factorial function? Posted: Oct 18, 2004 9:53 AM
Show that Python is THE language and write a wild function different from the ones posted here ( and i mean different in philosofy, not the names of the variables or the algorithm... ).

Above all, try to make it humourous, like a good "pythoneer"...

 Ivo Rocha Posts: 4 Nickname: silicio Registered: Oct, 2004
The " i'm to tired to move my fingers" style! Posted: Oct 18, 2004 9:57 AM
`def factorial(n):return reduce(lambda x,y:x*y,range(1,n+1))`

 Ivo Rocha Posts: 4 Nickname: silicio Registered: Oct, 2004
Look at me, mom!! Recursively!! Posted: Oct 18, 2004 10:09 AM
`def factorial(n,acumulator=1):	if n:		return acumulator	else:		return factorial(n-1,acumulator*n)`

 Matt Gerrans Posts: 1153 Nickname: matt Registered: Feb, 2002
Re: Look at me, mom!! Recursively!! Posted: Oct 18, 2004 4:34 PM
You might want to add some unit tests, especially for your second implementation...

 Andy Posts: 28 Nickname: adn Registered: Jul, 2004
Re: Look at me, mom!! Recursively!! Posted: Oct 18, 2004 5:52 PM
I guess this is outside of the box.

`def factorial(x):    """ Work out x! (with a little help from the google calculator...) """    import re    import urllib    import time    time.sleep(2)    class AppURLopener(urllib.FancyURLopener):        def __init__(self, *args):            # *Cough* *Cough*            self.version = 'Mozilla 1.3'            urllib.FancyURLopener.__init__(self, *args)    opener = AppURLopener()    page = opener.open('http://www.google.com/search?q=%d!' % x).read()    result = re.findall('<b>%d ! = (.*?)</b>' % x, page)    if result:        return int(result[0].replace('<font size=-2> </font>', ''))    else:        raise Exception, "Google not willing today!:\n\n %s" % page`

Go easy with it though eh?

Also it won't work past 15! - that's when google starts expressing it in scientific notation and I can't be bothered to parse that.

 Ivo Rocha Posts: 4 Nickname: silicio Registered: Oct, 2004
Re: Look at me, mom!! Recursively!! Posted: Oct 19, 2004 11:44 AM
> You might want to add some unit tests, especially for your
> second implementation...

You are absolutely right! This old habit of making code on the run...

In the first one insert a ",1" between the two last parenthesis ")".

And the second needs a "if not n" instead of "if n".

 Greg Jorgensen Posts: 65 Nickname: gregjor Registered: Feb, 2004
Re: Can you write a factorial function? Posted: Oct 21, 2004 3:21 AM
Recursive textbook version:

`def factorial(n):     if n == 0:         return 1     else:         return n * factorial(n-1)>>> factorial(5)120>>> factorial(30)265252859812191058636308480000000L`

Looping non-recursive version:

`def factorial(n):    f = 1    while (n > 0):        f = f * n        n = n - 1    return f`

Both can calculate factorial(100) in less than a second on my iBook G4.

Greg Jorgensen

 acid burn Posts: 2 Nickname: acidburn Registered: Mar, 2009
Re: Can you write a factorial function? Posted: Mar 12, 2009 2:05 PM
#Newbie programmer
def factorial(x):
if x == 0:
return 1
else:
return x * factorial(x - 1)
print factorial(6)

#First year programmer, studied Pascal
def factorial(x):
result = 1
i = 2
while i <= x:
result = result * i
i = i + 1
return result
print factorial(6)

#First year programmer, studied C
def fact(x): #{
result = i = 1;
while (i <= x): #{
result *= i;
i += 1;
#}
return result;
#}
print(fact(6))

#First year programmer, SICP
@tailcall
def fact(x, acc=1):
if (x > 1): return (fact((x - 1), (acc * x)))
else: return acc
print(fact(6))

#First year programmer, Python
def Factorial(x):
res = 1
for i in xrange(2, x + 1):
res *= i
return res
print Factorial(6)

 acid burn Posts: 2 Nickname: acidburn Registered: Mar, 2009
Re: Can you write a factorial function? Posted: Mar 12, 2009 2:05 PM
#Lazy Python programmer
def fact(x):
return x > 1 and x * fact(x - 1) or 1
print fact(6)

#Lazier Python programmer
f = lambda x: x and x * f(x - 1) or 1
print f(6)

#Python expert programmer
import operator as op
import functional as f
fact = lambda x: f.foldl(op.mul, 1, xrange(2, x + 1))
print fact(6)

#Python hacker
import sys
@tailcall
def fact(x, acc=1):
if x: return fact(x.__sub__(1), acc.__mul__(x))
return acc
sys.stdout.write(str(fact(6)) + '\n')

#EXPERT PROGRAMMER
import c_math
fact = c_math.fact
print fact(6)

#ENGLISH EXPERT PROGRAMMER
import c_maths
fact = c_maths.fact
print fact(6)

#Web designer
def factorial(x):
#-------------------------------------------------
#--- Code snippet from The Math Vault ---
#--- Calculate factorial (C) Arthur Smith 1999 ---
#-------------------------------------------------
result = str(1)
while i <= x:
#result = result * i #It's faster to use *=
#result = str(result * result + i)
#result = int(result *= i) #??????
result str(int(result) * i)
#result = int(str(result) * i)
i = i + 1
return result
print factorial(6)

#Unix programmer
import os
def fact(x):
os.system('factorial ' + str(x))
fact(6)

#Windows programmer
NULL = None
def CalculateAndPrintFactorialEx(dwNumber,
hOutputDevice,
lpLparam,
lpWparam,
lpsscSecurity,
*dwReserved):
if lpsscSecurity != NULL:
return NULL #Not implemented
dwResult = dwCounter = 1
while dwCounter <= dwNumber:
dwResult *= dwCounter
dwCounter += 1
hOutputDevice.write(str(dwResult))
hOutputDevice.write('\n')
return 1
import sys
CalculateAndPrintFactorialEx(6, sys.stdout, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)

 Ringo Doe Posts: 1 Nickname: ringo48 Registered: Mar, 2009
Re: Can you write a factorial function? Posted: Mar 19, 2009 1:02 AM
`def fact(n):    return eval('*'.join(map(lambda x: `x`, range(1,n+1))))`

 zeno of elea Posts: 1 Nickname: zeno1 Registered: Apr, 2012
Re: Can you write a factorial function? Posted: Apr 19, 2012 1:06 PM
@acidburn

you are awesome for writing that. extra tip of the hat for the web designer one. who are you???

 frederick 99 Posts: 1 Nickname: frederick9 Registered: Jan, 2017
Re: Can you write a factorial function? Posted: Jan 14, 2017 12:50 PM
its not that i hate acid burn... but the right guy should get the credit.
As far as i know, this piece belongs to Fernando Meyer (fmeyer on github).