1

Write a program that prints the Fibonacci Sequence from the 5th till the 15th element of the sequence. How should i start from the 5th one, which is '3'? here is my code

def fibonacci_nums(n):
    if n <= 0:
        return [0]
    sequence = [0, 1]
    while len(sequence) <= n:
        next_value = sequence[len(sequence) - 1] + sequence[len(sequence) - 2]
        sequence.append(next_value)
      

return sequence

print("First 15 Fibonacci numbers:")
print(fibonacci_nums(15))
Xiddoc
  • 3,369
  • 3
  • 11
  • 37
Jellyfish
  • 25
  • 5
  • How about choosing a different start sequence? `sequence = [2, 3]` – Ashok Arora Sep 28 '21 at 11:48
  • The 5th element of the Fibonacci sequence is not `3`, and especially not `'3'`. – Klaus D. Sep 28 '21 at 11:49
  • ohh thats it need to be -> return sequence[4:] – Jellyfish Sep 28 '21 at 11:58
  • @KlausD. That depends on whether you consider `fib(0)=0` or `fib(0)=1` this is not a straight forward assumption by a long shot, and if you have a particularly strong opinion on that it probably belongs here: https://stackoverflow.com/questions/1451170/in-the-fibonacci-sequence-is-fib0-0-or-1/29337929 – j__carlson Sep 28 '21 at 12:13
  • @j__carlson While you can modify it and theorize about the Fibonacci sequence, I think it would never have made it into any math book if this example for natural growth start with 0 rabbit pairs. – Klaus D. Sep 28 '21 at 12:27
  • *"ohh thats it need to be -> `return sequence[4:]` "*: and it should be indented properly. I vote to close as typo. – trincot Sep 29 '21 at 06:05

3 Answers3

1
def fibonacci_nums(n):
  if n <= 0:
    return [0]
  sequence = [0, 1]
  while len(sequence) <= n:
    next_value = sequence[len(sequence) - 1] + sequence[len(sequence) - 2]
    sequence.append(next_value)
  return sequence[4:]
print("Fibonacci numbers from 5th to 15th number:")
print(fibonacci_nums(14))
Jellyfish
  • 25
  • 5
1

Is this what you need:

def fibonacci_nums(n):
  if n <= 0:
    return [0]
  sequence = [0, 1]
  while len(sequence) <= n:
    next_value = sequence[len(sequence) - 1] + sequence[len(sequence) - 2]
    sequence.append(next_value)
  return sequence
print("First 15 Fibonacci numbers:")
print(fibonacci_nums(15)[4:])    # Print elements from 4th index

Output:

First 15 Fibonacci numbers:
[3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
Bhagyesh Dudhediya
  • 1,800
  • 1
  • 13
  • 16
1

Try this:

def fibonacci_nums(n, k):
    fib=[0,1]
    for f in range(k-1):
        fib.append(fib[f]+fib[f+1])
    return fib[n-1:k]

fibonacci_nums(5, 15)

Output:

[3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
j__carlson
  • 1,346
  • 3
  • 12
  • 20