By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,660 Members | 1,102 Online
Bytes IT Community
+ Ask a Question
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
  1. def fibClosed():
  2.     n=input("Enter a maximum value of n you'd like to compute")
  3.     for i in range (n+1):
  4.         x= round((1 / math.sqrt(5)) * ((1+math.sqrt(5))/2) ** i)
  5.     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
Share this Question
Share on Google+
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
  1. results = [0,1]
  2. # start the loop
  3.     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
  1. def fib(arg):
  2.     # code here
  3.     return answer
  5. if '__name__' == '__main__':
  6.     def main():
  7.         x = raw_input("Ask for input")
  8.         print fib(x)
  10.     main()
Sep 9 '10 #4

Post your reply

Sign in to post your reply or Sign up for a free account.