443,660 Members | 1,102 Online Need help? Post your question and get tips & solutions from a community of 443,660 IT Pros & Developers. It's quick & easy.

# Using an accumulator instead of exponential(**) in python.

 P: 2 Here is my current code: Expand|Select|Wrap|Line Numbers def fibClosed():     n=input("Enter a maximum value of n you'd like to compute")     for i in range (n+1):         x= round((1 / math.sqrt(5)) * ((1+math.sqrt(5))/2) ** i)     print i, int(x) , type(i) It uses an equation to figure out the Fibonacci Sequence. However, I need to use an accumulator instead of the exponential ( ** i) to get the same results. Can someone help me? Sep 9 '10 #1
3 Replies

 Expert Mod 2.5K+ P: 2,851 One way is to initialize a list with the sequence seed values which are 0 and 1. Start a while or for loop and append the sum of the last two elements of the list. Example: Expand|Select|Wrap|Line Numbers results = [0,1] # start the loop     results.append(sum(results[-2:])) Sep 9 '10 #2

 P: 2 Can you put it in simpler terms? I know i need to put something before the for loop. Sep 9 '10 #3

 Expert Mod 2.5K+ P: 2,851 That's about as simple as I know to make it. All you need is a means to limit the number of loop iterations. It can be a for loop over a range (as in the code you posted) or a while loop that exits with a return or break statement upon reaching some limit. The sequence is accumulating in the list, so you need to decide if you want to return the entire list or the last number in the list. Here is one way to organize it: Expand|Select|Wrap|Line Numbers def fib(arg):     # code here     return answer   if '__name__' == '__main__':     def main():         x = raw_input("Ask for input")         print fib(x)       main() Sep 9 '10 #4 