在使用动态编程解决斐波那契数列的程序中,返回值在 Ruby 中无法按预期工作
我是 ruby 新手,所以我可能在这里犯了一个非常新手的错误,但我尝试在谷歌上搜索答案,但无法弄清楚这段代码给出奇怪行为的原因。这段代码非常简单,使用基本的动态编程将中间结果存储到哈希中,以便稍后使用以加快计算速度。
$existingSequence = {0 => 1, 1 => 2}
def fib(n)
if $existingSequence.has_key? n
return $existingSequence.values_at n;
end
if n == 0
return 1;
elsif n == 1
return 2;
end
$existingSequence[n] = fib(n - 1) + fib(n - 2)
return $existingSequence[n];
end
n = fib(2)
puts n
我希望这段代码输出 3,因为这会调用 fib(1) 和 fib(0),分别返回 2 和 1,然后相加为 3。但输出是 1 和 2。
I'm new to ruby so I'm probably making a very newbie mistake here but I tried Googling for an answer and couldn't figure out the reason why this code is giving weird behavior. This code is very simple, and uses basic dynamic programming to store intermediate result to a Hash so it is used later to speed up the computation.
$existingSequence = {0 => 1, 1 => 2}
def fib(n)
if $existingSequence.has_key? n
return $existingSequence.values_at n;
end
if n == 0
return 1;
elsif n == 1
return 2;
end
$existingSequence[n] = fib(n - 1) + fib(n - 2)
return $existingSequence[n];
end
n = fib(2)
puts n
I expect this code to output 3 since that makes a call to fib(1) and fib(0) which returns 2 and 1 respectively, and then added to be 3. But the output is 1 and 2.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Hash.values_at
返回一个数组,因此当代码执行fib(1) + fib(0)
时,它会连接数组[2]
和[1]
在一起,得到答案[2, 1]
。而不是:...您应该这样做:
顺便说一句,斐波那契数列传统上以 0 和 1 开头,而不是 1 和 2。
Hash.values_at
returns an array, so when the code doesfib(1) + fib(0)
, it's concatenating the arrays[2]
and[1]
together, resulting in the answer[2, 1]
. Instead of:...you should do this instead:
BTW, the Fibonacci sequence traditionally starts with 0 and 1, not 1 and 2.
稍微偏离主题,这里有一个有趣的方法,基本上可以做同样的事情,但是使用
Hash
默认值机制来使用Hash
不仅用于缓存,还用于计算注意:我自己没有想出这个,我从 此处。
Slightly off-topic, here's a fun way of doing essentially the same thing, but using the
Hash
default value mechanism to use theHash
not only for caching, but also for computing the values:Note: I didn't come up with this myself, I stole it from here.
fib
的第二行应为:将 $existingSequence替换为
Add
puts $existingSequence
到文件末尾以查看差异。The second line of
fib
should read:instead of
Add
puts $existingSequence
to the end of the file to see the difference.