Skip to content

Instantly share code, notes, and snippets.

@bandit145
Last active August 22, 2021 00:44
Show Gist options
  • Save bandit145/61e521ce0880ed0c4db9b1340caba2b1 to your computer and use it in GitHub Desktop.
Save bandit145/61e521ce0880ed0c4db9b1340caba2b1 to your computer and use it in GitHub Desktop.
recursion exercise
name = 'Dakota'
# data_struct = {
# 'data1': {
# 'data2': {}
# }
# }
def iterative_reverse(name):
reverse_name = ''
num_char = len(name)
while num_char > 0:
print(name[num_char - 1])
reverse_name += name[num_char -1]
num_char -= 1
return reverse_name
#beacause the stack is list in first out we can use this to reverse items (as an example) without loops
def recursive_reverse(name):
print('not at base case')
# this is our exit case or are "base case" as we call it in recursion land.
# as we can see here we check if we are at our last character and just return it starting the return up the stack.
if len(name) == 1:
print('base case')
return name[0]
# this calls itself which means this function will not return until the new one does all the way down
# (which since the last in functions return first will result in the characters coming back in reverse order)
return recursive_reverse(name[1:]) + name[0] # this is our current character which gets append to the return value we are waiting for
#(which is putting our current char beind it's next one on the way back up the stack)
print(iterative_reverse(name))
print(recursive_reverse(name))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment