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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • KyleButler
    New Member
    • Sep 2010
    • 2

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

    Here is my current code:
    Code:
    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?
    Last edited by bvdet; Sep 9 '10, 03:03 AM. Reason: Add code tags, add indentation
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    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:
    Code:
    results = [0,1]
    # start the loop
        results.append(sum(results[-2:]))

    Comment

    • KyleButler
      New Member
      • Sep 2010
      • 2

      #3
      Can you put it in simpler terms? I know i need to put something before the for loop.

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        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:
        Code:
        def fib(arg):
            # code here
            return answer
        
        if '__name__' == '__main__':
            def main():
                x = raw_input("Ask for input")
                print fib(x)
        
            main()

        Comment

        Working...