Skip to content

Commit 6eaaf7d

Browse files
committed
Add Fibonacci Seq 2
1 parent 6a55d0e commit 6eaaf7d

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

FibonacciSequence_Solution2.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
#Author: azmathias Stuperuser Ltd.
2+
#Purpose: Determine the nth number in the Fibonacci Sequence
3+
#Notes: Solution2: using recursion
4+
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]
5+
#ToDo: Combine solutions so user can choose which method to use in the same program
6+
#
7+
8+
# get nth term to test
9+
def inputterm(message):
10+
while True:
11+
try:
12+
userinput = int(input(message))
13+
except ValueError:
14+
print("\nPlease input a valid number:")
15+
continue
16+
else:
17+
return userinput
18+
break
19+
20+
def fibonacci2(n):
21+
if n < 0:
22+
print("Invalid input")
23+
elif n == 1:
24+
return 0
25+
elif n == 2:
26+
return 1
27+
else:
28+
return fibonacci2(n-1) + fibonacci2(n-2)
29+
30+
# allow user to test again
31+
def testStatus():
32+
testQ = "\nType q to quit, or hit <Enter> to test another number."
33+
print(testQ)
34+
new_value = 0
35+
while not new_value:
36+
response = input('> ')
37+
if response == '':
38+
print()
39+
elif response == 'q':
40+
new_value = -1
41+
else:
42+
print("\nPlease try again.")
43+
print(testQ)
44+
continue
45+
return new_value
46+
47+
def main():
48+
print("Fibonacci Sequence Term Finder (using recursion) \n")
49+
value = 0
50+
while value != -1:
51+
num = inputterm("Please enter a number for the nth term:")
52+
ret_val = fibonacci2(num)
53+
print("\n{0} is the {1}th number in the Fibonacci Sequence".format(ret_val,num))
54+
value = testStatus()
55+
print("\nThank you for playing!")
56+
57+
if __name__ == '__main__': main()

0 commit comments

Comments
 (0)