Created
August 26, 2009 14:53
-
-
Save xwmx/175552 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def fib(n): | |
if n == 0 or n == 1: | |
return n | |
else: | |
return fib(n-1) + fib(n-2) | |
for i in range(36): | |
print "n=%d => %d" % (i, fib(i)) | |
# Python 2.5.4 | |
# $ time python fib.py | |
# real 0m25.760s | |
# user 0m25.103s | |
# sys 0m0.178 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def fib(n) | |
if n == 0 || n == 1 | |
n | |
else | |
fib(n-1) + fib(n-2) | |
end | |
end | |
36.times do |i| | |
puts "n=#{i} => #{fib(i)}" | |
end | |
# ruby 1.9.1 | |
# $ time ruby fib.rb | |
# real 0m10.230s | |
# user 0m9.953s | |
# sys 0m0.080s |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def fib(n): | |
a, b = 0, 1 | |
i = 0 | |
while i < n: | |
yield (i, a) | |
a, b = b, a + b | |
i += 1 | |
for i, f in fib(36): | |
print "n=%d => %d" % (i, f) | |
# Python 2.5.4 | |
# $ time python fib2.py | |
# real 0m0.029s | |
# user 0m0.012s | |
# sys 0m0.013s |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fib = lambda do |n,b| | |
i,k=0,1 | |
n.times do |p| | |
b[p, i] | |
i,k=k,i+k | |
end | |
end | |
fib[36, proc {|i, f| puts "n=%d => %d" % [i, f] }] | |
# ruby 1.9.1 | |
# $ time ruby fib2.rb | |
# real 0m0.019s | |
# user 0m0.011s | |
# sys 0m0.008s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment