Hacker News new | ask | show | jobs
by ginkgo 6139 days ago
Or you could simply make your python code tail-recursive:

  $ time python fib.py 40
  102334155

  real	0m0.013s
  user	0m0.000s
  sys	0m0.010s
3 comments

Then you are testing two different things, and if you use tail recursion even Ruby 1.9 still runs it faster than Python.

  # 400
  $ time ruby fib.rb

  real	0m0.017s
  user	0m0.010s
  sys	0m0.006s
  
  # 400
  $ time python fib.py 

  real	0m0.023s
  user	0m0.011s
  sys	0m0.011s
Of course you can, but that's not going to work when you run out of stack space. The point of my stupid benchmark was to write the equivalent ruby code, and then the equivalent C code, forgetting the fact that there's a much more optimal way to do it (e.g. write it in scheme with tail calls).
> was to write the equivalent ruby code,

that should have stated "equivalent python code"

Python does not do tail call optimization.
Whether it does tail call optimization is a different question than whether you can write the algorithm in a tail-recursive manner, though.
Yes, but without the optimization, how would it help? Am I just being a n00b?
Writing it tail-recursively forces you to switch from the O(2^n) algorithm (which has two recursive calls; you can't put both into tail position) to a more efficient algorithm. You could also write the more-efficient algorithm without tail recursion, of course.
No, you're not being a n00b. It'll help because the stack usage will grow linearly as opposed to quadratically, as in the case of the naive solution. You'll still overflow the stack without the optimization.