The Artima Developer Community
Sponsored Link

Python Answers Forum
Can you write a factorial function?

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

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   
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
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 6: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 7: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: 1153
Nickname: matt
Registered: Feb, 2002

Re: Look at me, mom!! Recursively!! Posted: Oct 18, 2004 1: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 2: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 8: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 12: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 11:05 AM
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 11:05 AM
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 18, 2009 10:02 PM
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 10:06 AM
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???

frederick 99

Posts: 1
Nickname: frederick9
Registered: Jan, 2017

Re: Can you write a factorial function? Posted: Jan 14, 2017 9:50 AM
Reply to this message Reply
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).

Link to the article: https://gist.github.com/fmeyer/289467#file-evolution-of-a-python-programmer-py-L65

Vijay Khatri

Posts: 2
Nickname: vijay1994
Registered: Dec, 2018

Re: Can you write a factorial function? Posted: Dec 12, 2018 2:05 AM
Reply to this message Reply
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
Reply to this message Reply
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;
}
}

http://madridmeencanta.org/where-can-i-get-help-with-my-homework

Robert Thompson

Posts: 2
Nickname: robert123
Registered: Mar, 2019

Re: Can you write a factorial function? Posted: Mar 19, 2019 5:24 AM
Reply to this message Reply
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 | » ]
Topic: writing string variable to file Previous Topic   Next Topic Topic: writing a number variable to a file

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use