How to write the Fibonacci Sequence?

前端 未结 30 2385
醉酒成梦
醉酒成梦 2020-11-22 00:32

I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1

30条回答
  •  梦毁少年i
    2020-11-22 01:20

    based on classic fibonacci sequence and just for the sake of the one-liners

    if you just need the number of the index, you can use the reduce (even if reduce it's not best suited for this it can be a good exercise)

    def fibonacci(index):
        return reduce(lambda r,v: r.append(r[-1]+r[-2]) or (r.pop(0) and 0) or r , xrange(index), [0, 1])[1]
    

    and to get the complete array just remove the or (r.pop(0) and 0)

    reduce(lambda r,v: r.append(r[-1]+r[-2]) or r , xrange(last_index), [0, 1])
    

提交回复
热议问题