# # Sep 16 homework # chap 3 exercise 16 # Jim Mahoney's example solution. # # Find n'th Fibonnaci number, where n is entered by the user. # # I choose to number the sequence this way. # F[0] = 0 # F[1] = 1 # F[n+2] = F[n] + F[n+1] for n >= 0. # See for example http://en.wikipedia.org/wiki/Fibonacci_number # That gives for the first few these numbers. # n F[n] # -- ---- # 0 0 definition # 1 1 definition # 2 1 = sum of two previous ones = 0 + 1 # 3 2 = 1 + 1 # 4 3 = 1 + 2 # 5 5 = 2 + 3 # 6 8 = 3 + 5 # 7 13 = 5 + 8 # print("-- chap3ex16.py --") print("Find the n'th Fibonnaci number.") def fib(): n = int(input("What is n? ")) F_n = 0 F_n_plus_1 = 1 for i in range(n): F_n_plus_2 = F_n + F_n_plus_1 # Calculate F[n+2] = F[n] + F[n+1] F_n = F_n_plus_1 # Slide up to the next value of n. F_n_plus_1 = F_n_plus_2 ## ## -- implementation remarks -- ## ## Another way to do the last two lines would be with tuples: # (F_n, F_n_plus_1) = (F_n_plus_1, F_n_plus_2) ## ## Or all three lines could be done in at once: # (F_n, F_n_plus_1) = (F_n_plus_1, F_n + F_n_plus_1) ## print("F[", n, "] = ", F_n) fib()