The Artima Developer Community
Sponsored Link

Python Answers Forum
Can you write a factorial function?

11 replies on 1 page. Most recent reply: Feb 27, 2014 10:23 AM by Nohtyp Edoc

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
    Next Topic
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
Reply to this message Reply
Advertisement
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
Reply to this message Reply

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
Reply to this message Reply

def factorial(n,acumulator=1):
if n:
return acumulator
else:
return factorial(n-1,acumulator*n)

Matt Gerrans

Posts: 1152
Nickname: matt
Registered: Feb, 2002

Re: Look at me, mom!! Recursively!! Posted: Oct 18, 2004 4:34 PM
Reply to this message Reply
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
Reply to this message Reply
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
Reply to this message Reply
> 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".

Sorry about that, guys...

Greg Jorgensen

Posts: 65
Nickname: gregjor
Registered: Feb, 2004

Re: Can you write a factorial function? Posted: Oct 21, 2004 3:21 AM
Reply to this message Reply
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
Reply to this message Reply
#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
Reply to this message Reply
#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)
i = 1 #Thanks Adam
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
Reply to this message Reply

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
Reply to this message Reply
@acidburn

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

Nohtyp Edoc

Posts: 1
Nickname: missac
Registered: Feb, 2014

Re: Can you write a factorial function? Posted: Feb 27, 2014 10:23 AM
Reply to this message Reply
Without using recursion
http://www.programiz.com/python-programming/examples/factorial

Using Recursion:
http://www.programiz.com/python-programming/examples/factorial-recursion

Flat View: This topic has 11 replies on 1 page
    Next Topic Topic: How to convert details from a saved text file into a list of files


Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2014 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us