Advertisement
asweigart

factorialEmulateRecursion.py

Jan 13th, 2022
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. callStack = [] # The explicit call stack, which holds "frame objects".
  2. callStack.append({'instrPtr': 'start', 'number': 5}) # "Call" the "factorial() function"
  3. returnValue = None
  4.  
  5. while len(callStack) > 0:
  6. # The body of the "factorial() function":
  7.  
  8. number = callStack[-1]['number'] # Set number parameter.
  9. instrPtr = callStack[-1]['instrPtr']
  10.  
  11. if instrPtr == 'start':
  12. if number == 1:
  13. # BASE CASE
  14. returnValue = 1
  15. callStack.pop() # "Return" from "function call".
  16. continue
  17. else:
  18. # RECURSIVE CASE
  19. callStack[-1]['instrPtr'] = 'after recursive call'
  20. # "Call" the "factorial() function":
  21. callStack.append({'instrPtr': 'start', 'number': number - 1})
  22. continue
  23. elif instrPtr == 'after recursive call':
  24. returnValue = number * returnValue
  25. callStack.pop() # "Return from function call".
  26. continue
  27.  
  28. print(returnValue)
  29.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement