PDA

View Full Version : First stab at python :x


Halide
09-30-2002, 01:00 AM
ok, this is terrible..... please make this code better?

def factorial(a):
for i in range(a - 1, 0, -1):
a *= i
return a

Strike
09-30-2002, 02:26 AM
Recursive version:

def fact(n, acc=1):
if n = 1: return acc
return fact(n-1, n*acc)

Halide
09-30-2002, 02:55 AM
hmm ok ;)

so which one is faster?

inkedmn
09-30-2002, 06:55 AM
well, they look about even to me...

(i added some time.time()'s and pass both functions the number 20):


D:\python\code>python halide.py
took 0 seconds
2432902008176640000

D:\python\code>python strike.py
took 0 seconds
2432902008176640000


:)

Halide
09-30-2002, 09:23 AM
hey...how precise is time.time() :)

Strike
09-30-2002, 10:06 AM
It's not a matter of which one is faster (though I would think that they would be pretty much the same .. I would hope that Python could and would optimize tail-recursion). It's just a different way of doing it - if you think the recursive one reads better, go for it. The only thing I'd change about your version is instead of stepping backwards through the range, I'd just go from 1 to n instead of from n to 1 (doesn't matter which way you go).

Halide
09-30-2002, 11:05 AM
ok, cool

moving on :)

Halide
09-30-2002, 11:08 AM
is my sig correct

inkedmn
09-30-2002, 12:06 PM
sig = []
sig.append("i know php and mysql")
sig.append("i'm learning python!")
for item in sig:
print item


:)

Halide
09-30-2002, 06:22 PM
thanks

inkedmn
09-30-2002, 07:36 PM
no problemo amigo

jemfinch
10-01-2002, 12:46 AM
Python doesn't optimize tail recursion (heck, Python doesn't really optimize anything.) For large numbers, the recursive version would almost certainly be much slower than the iterative version, which is (IMO) probably best written like this:


def factorial(n):
ret = 1
while n > 1:
ret *= n
n -= 1
return ret


You can also obfuscate things a bit, probably getting slightly faster:


def factorial(n):
return reduce(operator.mul, xrange(1, n+1))


Jeremy

Halide
10-01-2002, 01:21 AM
your code looks cool jemfinch,

but what is xrange

and I was thinking about reduce ... or map or whatever... but i'm a newbie

Strike
10-01-2002, 03:14 AM
Halide: xrange() is a Python built in function ... you know where the docs are :)

Halide
10-01-2002, 08:09 AM
;)