Skip to content

Instantly share code, notes, and snippets.

@dev10110
Created September 5, 2020 13:44
Show Gist options
  • Save dev10110/79581a1edb0399c3f2b9578577dd73ad to your computer and use it in GitHub Desktop.
Save dev10110/79581a1edb0399c3f2b9578577dd73ad to your computer and use it in GitHub Desktop.
Fibonacci number
fibStore = {}
def fibWrapper(num, mode):
# num : number to compute
# mode : 'r' for return or 'p' for print
if not (mode == 'r' or mode == 'p'):
raise ValueError("mode must be 'r' or 'p'")
value = fib(num)
if mode=='r':
return value
if mode == 'p':
print(value)
def fib(n):
# computes the nth fibonacci number, recursively
if n in fibStore:
return fibStore[n]
if n == 0:
fibStore[n] = 0
return 0
if n == 1 or n==2:
fibStore[n] = 1
return 1
value = fib(n-1) + fib(n-2)
fibStore[n] = value
return value
def square(x):
return x**2
def main():
num = input("Enter a number: ")
num = int(num)
mode = input("Enter mode: ")
if mode == 'p':
fibWrapper(num, mode)
else:
output = fibWrapper(num, mode)
print("output for main: ", output)
if __name__ == '__main__':
try:
main()
except ValueError as e:
print(e)
print("Try again:")
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment