Can you write a factorial function?

15 replies on 2 pages. Most recent reply: Mar 19, 2019 5:26 AM by Robert Thompson

 Previous Topic Next Topic
 Flat View: This topic has 15 replies on 2 pages [ 1 2 | » ]
 Ivo Rocha Posts: 4 Nickname: silicio Registered: Oct, 2004
Can you write a factorial function? Posted: Oct 18, 2004 6: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 6: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 7: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 1: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 2: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 8: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 12: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 11:05 AM
#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 11:05 AM
#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 18, 2009 10:02 PM
`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 10:06 AM
@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 9:50 AM
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).

 Vijay Khatri Posts: 2 Nickname: vijay1994 Registered: Dec, 2018
Re: Can you write a factorial function? Posted: Dec 12, 2018 2:05 AM
here is my Code:
n = 23
fact = 1

for i in range(1,n+1):
fact = fact * i

print ("The factorial of 23 is : ",end="")
print (fact)

 Selena Blane Posts: 2 Nickname: sharlotta Registered: Feb, 2019
Re: Can you write a factorial function? Posted: Feb 13, 2019 4:37 AM
function factorial(x) {
executions++;
if (x > 1) {
if (executions % 20 === 0) {
return (function() {
var y = x;
setTimeout(function(y) { return y*factorial(y-1); }, 1);
});
} else {
return x*factorial(x-1);
}
} else {
executions = 0;
return 1;
}
}

 Robert Thompson Posts: 2 Nickname: robert123 Registered: Mar, 2019
Re: Can you write a factorial function? Posted: Mar 19, 2019 5:24 AM
Thanks a lot for this wonderful post, really enjoyed it a lot! By the way, it surely helped me to finish my college assignment in time. Hate to write essays however I used a lot of useful information here <a href="https://handmadewriting.com/blog/guides/cause-and-effect-essay-outline/"& gt;Handmade Writing</a>.They are providing reliable services on any kind of assignment assistance. Highly recommend!

 Flat View: This topic has 15 replies on 2 pages [ 1  2 | » ]
 Previous Topic Next Topic