Fibonaci sequence

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • shing
    New Member
    • Mar 2007
    • 58

    Fibonaci sequence

    I've always thought it would be great to have a program that automatically shows large sequences of the Fibonacci sequence...so far i have
    Code:
    a, b = 0, 1
    while b < 1000:
    print b
    	a, b = b, a+b
    I want the program to show: "Sequence 1: 1". Sequence 2: "1", Sequence 3: "2", Sequence 4: "3", etc etc...

    Does anybody know how I can do this? Also, I want the program to ask "What sequence do you wish to know?"

    And then if i type, "61", it will show the 61th sequence of the Fibo. Series.

    Thanks.
  • elcron
    New Member
    • Sep 2007
    • 43

    #2
    Originally posted by shing
    I've always thought it would be great to have a program that automatically shows large sequences of the Fibonacci sequence...so far i have
    Code:
    a, b = 0, 1
    while b < 1000:
    print b
    	a, b = b, a+b
    I want the program to show: "Sequence 1: 1". Sequence 2: "1", Sequence 3: "2", Sequence 4: "3", etc etc...

    Does anybody know how I can do this? Also, I want the program to ask "What sequence do you wish to know?"

    And then if i type, "61", it will show the 61th sequence of the Fibo. Series.

    Thanks.
    you could store it in a list and use the index
    [code=python]
    >>> def fib(maxNum=1000 ):
    a, b = 0, 1
    li = [b]
    while b < 1000:
    a, b = b, a+b
    li.append(b)
    return li

    >>> fibNums = fib()
    >>> fibNums
    [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597]
    >>> for i in range(len(fibNu ms)):
    print "Sequence %s: %s"%(i+1, fibNums[i])
    Sequence 1: 1
    Sequence 2: 1
    Sequence 3: 2
    Sequence 4: 3
    Sequence 5: 5
    Sequence 6: 8
    Sequence 7: 13
    Sequence 8: 21
    Sequence 9: 34
    Sequence 10: 55
    Sequence 11: 89
    Sequence 12: 144
    Sequence 13: 233
    Sequence 14: 377
    Sequence 15: 610
    Sequence 16: 987
    Sequence 17: 1597
    >>> def printSeq():
    seqID = False
    while not seqID:
    seqID = raw_input("What sequence do you want? ")
    if not seqID in [str(i) for i in range(1, len(fibNums) + 1)]: # +1 because range goes to max - 1
    print "Must be a number in the range of 1-%s"%len(fibNums )
    seqID = False
    else:
    seqID = int(seqID)
    print "Sequence %s: %s"%(seqID, fibNums[seqID-1])
    >>> printSeq()
    What sequence do you want? elcron
    Must be a number in the range of 1-17
    What sequence do you want? 0
    Must be a number in the range of 1-17
    What sequence do you want? 18
    Must be a number in the range of 1-17
    What sequence do you want? 17
    Sequence 17: 1597
    [/code]

    Comment

    Working...