4 ms·
Shouldn't: def fib(n): if n < 2: return 1 else : return fib(n - 1) + fib(n - 2) Be: ... if n < 2: return n ... ? Or am I be
by amouat 16y ago
Shouldn't:
def fib(n):
if n < 2: return 1
else : return fib(n - 1) + fib(n - 2)
Be:
...
if n < 2: return n
...
?
Or am I being stupid?
EDIT: changed x to n.
- VMG 16y agoworks with both - try it on paper
- amouat 16y agoI did - with 2: fib(2) = fib(2-1) + fib(2-2) fib(2) = fib(1) + fib(0) fib(2) = 1 + 1 (rather than 1 + 0) No?
- amouat 16y agoIt's definitely wrong - just ran it in python to check in case I was missing something!
- deleted 16y ago[deleted]
- jpd 16y agoI don't think it's explicitly wrong; I've seen both fib(0) = 1 and fib(0) = 0 before. Wikipedia shows: By definition, the first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum of the previous two. Some sources omit the initial 0, instead beginning the sequence with two 1s.
- amouat 16y agoI think it's still wrong by that definition. I think it is just saying fib(1) is the first number, not fib(0). fib(2) should never be 2. EDIT: Actually, I think you're right: it's just an index thing (do we start at 1 or 0) - I was confusing the index of 2 with the value of 2.
- VMG 16y agoYou are right, the difference is that the one sequence is " 0 1 1 2 3 5 ... " while the other is " 1 1 2 3 5 ..." - so it is just shifted by one. The interesting properties of the sequence still remain.
- tome 16y agoYou must mean "return n", but I don't have an opinion on "correct" behvior. All that's happening is the index is shifted by 1.
- amouat 16y agoTrue. I'll update above regarding n. However, it's certainly different to the other examples and I would expect fib(2) to be 1 + 0 not 1 + 1. It's a very minor point though - I think I'll stop now ;)