Skip to content

Instantly share code, notes, and snippets.

@nmante
Created November 26, 2016 00:53
Show Gist options
  • Save nmante/2c01d7427d360740a97f054a7192b6ab to your computer and use it in GitHub Desktop.
Save nmante/2c01d7427d360740a97f054a7192b6ab to your computer and use it in GitHub Desktop.
Two examples of recursion: the fibonacci sequence, and the towers of hanoi.
#!/usr/bin/env python
"""
Nii Mante
November 23rd, 2016
To execute the fibonacci sequence with 5 numbers, use a command like so
python recursion.py fib -n 5
To execute the hanoi game with 4 disks, use a command like so
python recursion.py hanoi -d 4
"""
import argparse
def create_parser():
parser = argparse.ArgumentParser(description="Execute examples of recursive programs")
subparsers = parser.add_subparsers(help="Sub help")
# Fibonacci Parser
fib_parser = subparsers.add_parser('fib')
fib_parser.add_argument('-n', '--numbers', type=int, help="Amount of numbers to generate for fibonacci sequence", default=5)
fib_parser.set_defaults(func=sequence)
# Hanoi Parser
hanoi_parser = subparsers.add_parser('hanoi')
hanoi_parser.add_argument('-v', '--verbose', action="store_true", help="Set this flag to print each move out. Default behavior is to simply print the last tower")
hanoi_parser.add_argument('-d', '--num_disks', type=int, help="Number of disks to start the Hanoi game with", default=3)
hanoi_parser.set_defaults(func=hanoi)
return parser
def sequence(args):
def fibonacci(n):
if n < 0:
return 0
if n == 0 or n == 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
n = args.numbers
seq = []
for i in range(n):
seq.append(fibonacci(i))
print seq
def hanoi(args):
def move_disk(disk_num, from_tower, to_tower):
print "moving disk: " + str(disk_num) + " from tower: " + str(from_tower) + " to tower: " + str(to_tower)
def solve_hanoi(height, from_tower, to_tower, buffer_tower):
if height > 0:
solve_hanoi(height - 1, from_tower, buffer_tower, to_tower)
move_disk(height, from_tower, to_tower)
solve_hanoi(height - 1, buffer_tower, to_tower, from_tower)
num_disks = args.num_disks
solve_hanoi(num_disks, 0, 2, 1)
def main():
args = create_parser().parse_args()
args.func(args)
"""
# Tower of hanoi
solve_hanoi(3, 0, 2, 1)
# Fibonacci
print sequence(4)
"""
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment