Introduction to Programming using Python 1st Edition

Published by Pearson
ISBN 10: 0132747189
ISBN 13: 978-0-13274-718-9

Chapter 15 - Recursion - Programming Exercises - Page 523: 15.2

Answer

code

Work Step by Step

# 15.2 (Fibonacci numbers) Rewrite the fib function in Listing 15.2 using iterations. # (Hint: To compute fib(n) without recursion, you need to obtain fib(n - 2) # and fib(n - 1) first.) Let f0 and f1 denote the two previous Fibonacci numbers. # The current Fibonacci number would then be f0 + f1. The algorithm can be # described as follows: # f0 = 0 # For fibs(0) # f1 = 1 # For fib(1) # for i in range(2, n + 1): # currentFib = f0 + f1 # f0 = f1 # f1 = currentFib # # After the loop, currentFib is fib(n) # Write a test program that prompts the user to enter an index and displays its # Fibonacci number. n = eval(input("Enter a number: ")) f0 = 0 f1 = 1 fib = 0 for i in range(2, n + 1): fib = f0 + f1 f0 = f1 f1 = fib print("The Fibonacci of", n, "is", fib)
Update this answer!

You can help us out by revising, improving and updating this answer.

Update this answer

After you claim an answer you’ll have 24 hours to send in a draft. An editor will review the submission and either publish your submission or provide feedback.