Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Disappointed at Python

Name: Anonymous 2011-11-09 19:55

Fibonacci number calculation

fibonacci.py:

def f(n):
    if n <= 1:
        return 1
    return f(n-1) + f(n-2)

print(f(30))


fibonacci.rb:

def f(n)
  if n <= 1
    return 1
  end
  return f(n-1) + f(n-2)
end

puts f(30)



$ python --version
Python 3.2.2
$ time python fibonacci.py
1346269

real    0m1.340s
user    0m1.043s
sys    0m0.035s
$ ruby1.8 --version
ruby 1.8.6 (2009-06-08 patchlevel 369) [universal-darwin9.0]
$ time ruby1.8 fibonacci.rb
1346269

real    0m1.539s
user    0m1.492s
sys    0m0.008s
$ ruby --version
ruby 1.9.2p290 (2011-07-09 revision 32553) [i386-darwin9.8.0]
$ time ruby fibonacci.rb
1346269

real    0m0.306s
user    0m0.296s
sys    0m0.007s


What the fuck going on, Guido?  I am switching to ruby.

Name: Anonymous 2011-11-10 6:33

What's going on is that Ruby detects that the function is pure while Python does not, you can mend it yourself but I don't know if such behavior is advisable.

def pure (func):
    cache = {}
    def wrapper (*args):
        if args not in cache:
            cache[args] = func (*args)
        return cache[args]
    return wrapper

@pure
def fib (n):
    return 1 if n <= 1 else fib (n-1) + fib (n-2)

# Timing I/O is stupid
print fib (30)


[~/Python/trash] time python fib.py
1346269

real    0m0.167s
user    0m0.133s
sys    0m0.034s


I don't have Ruby installed so I can't test whether it still is faster on my machine. I also don't have Python3k installed on my machine so I had to run this using "CPython version 2.7".

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List