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))
6
  • How about choosing a different start sequence? sequence = [2, 3] Commented Sep 28, 2021 at 11:48
  • The 5th element of the Fibonacci sequence is not 3, and especially not '3'. Commented Sep 28, 2021 at 11:49
  • ohh thats it need to be -> return sequence[4:] Commented Sep 28, 2021 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: stackoverflow.com/questions/1451170/… Commented Sep 28, 2021 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. Commented Sep 28, 2021 at 12:27

3 Answers 3

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))
Sign up to request clarification or add additional context in comments.

Comments

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]

Comments

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.