#!/usr/bin/python
## first way ##
import fib_module
print fib_module.calc_fib(n)
## second way ##
f= open ("fib.txt",'r') # import and read from a text file
# don't think single and double quotes make a difference in python.
i = f.readlines()
# at this point, could just use: i(5)
# but how to do it (in a longer way) by using a while loop?
# use a colon at the beginning of a function definition (no curly brackets as in other languages)
while counter < n :
fib_we_want = L[counter].strip() # to take off the newlines
counter += 1 #same as counter = counter + 1 (counter++ does not work in python)
print fib_we_want
## third way: use a list ##
L = [] # don't have to allocate memory or anything.
# L[0] = 1 you cannot do this, as you would in matlab.
L.append(1)
L.append(2)
# let's use a for loop!
for i in range(1,n+1): # range chops off the last guy
next_num = L[-1] + L[-2] #trick to get the last and the second to last entry from the list.
L.append(next_num)
print L[n-1]
## fourth way ... using recursion: ##
def recfib(n):
# 1. stop condition
if n == 1:
return 1
if n == 2:
return 2
# 2. self reference
return_num = recfib(next_num-1) + recfib(next_num-2)
# 3. operate and return answer
return return_num
## fifth way is speedy! ##
# why the fourth way was a classical BAD EXAMPLE of recursion:
# think: how many times will you call the function with the number 7 ?
# 10 will call 9 and 8. 9 will then call 8 and 7, and 8 will call 7 and 6.
# so you are calculating the same value over and over !
steve_dict = {}
def recfib_hash(n,steve_dict):
# 1. stop condition
if n == 1:
return 1
if n == 2:
return 2
# another stop condition
if steve_dict.has_key(next_num): # has_key method asks if
return steve_dict[next_num]
# 2. self reference
return_num = recfib_hash(next_num-1,steve_dict) + recfib_hash(next_num-2,steve_dict)
# function doesn't have the power to change the global variable, we should pass it along
# 2a. store this value in the dictionary
steve_dict[next_num] = return_num
# 3. operate and return answer
return return_num
print recfib_hash[n,{}]