473,242 Members | 1,472 Online

# Fibonaci sequence

58
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
Expand|Select|Wrap|Line Numbers
1. a, b = 0, 1
2. while b < 1000:
3. print b
4.     a, b = b, a+b
5.
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.
Dec 23 '07 #1
1 1357
elcron
43
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
Expand|Select|Wrap|Line Numbers
1. a, b = 0, 1
2. while b < 1000:
3. print b
4.     a, b = b, a+b
5.
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
Expand|Select|Wrap|Line Numbers
1. >>> def fib(maxNum=1000):
2.     a, b = 0, 1
3.     li = [b]
4.     while b < 1000:
5.         a, b = b, a+b
6.         li.append(b)
7.     return li
8.
9. >>> fibNums = fib()
10. >>> fibNums
11. [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597]
12. >>> for i in range(len(fibNums)):
13.     print "Sequence %s: %s"%(i+1, fibNums[i])
14. Sequence 1: 1
15. Sequence 2: 1
16. Sequence 3: 2
17. Sequence 4: 3
18. Sequence 5: 5
19. Sequence 6: 8
20. Sequence 7: 13
21. Sequence 8: 21
22. Sequence 9: 34
23. Sequence 10: 55
24. Sequence 11: 89
25. Sequence 12: 144
26. Sequence 13: 233
27. Sequence 14: 377
28. Sequence 15: 610
29. Sequence 16: 987
30. Sequence 17: 1597
31. >>> def printSeq():
32.     seqID = False
33.     while not seqID:
34.         seqID = raw_input("What sequence do you want? ")
35.         if not seqID in [str(i) for i in range(1, len(fibNums) + 1)]: # +1 because range goes to max - 1
36.             print "Must be a number in the range of 1-%s"%len(fibNums)
37.             seqID = False
38.         else:
39.             seqID = int(seqID)
40.     print "Sequence %s: %s"%(seqID, fibNums[seqID-1])
41. >>> printSeq()
42. What sequence do you want? elcron
43. Must be a number in the range of 1-17
44. What sequence do you want? 0
45. Must be a number in the range of 1-17
46. What sequence do you want? 18
47. Must be a number in the range of 1-17
48. What sequence do you want? 17
49. Sequence 17: 1597
50.
Dec 23 '07 #2