Home > Software engineering >  program that prints the Fibonacci Sequence from the 5th till the 15th element of the sequence
program that prints the Fibonacci Sequence from the 5th till the 15th element of the sequence

Time:09-29

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))

CodePudding user response:

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))

CodePudding user response:

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]

CodePudding user response:

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]
  • Related