Created
May 19, 2024 11:19
-
-
Save DuskyElf/e466f768d14f4927467705d853774223 to your computer and use it in GitHub Desktop.
Visual Stack trace of recursive fibonacci function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class HorizontalPrint: | |
| def __init__(self): | |
| self.y = 0 | |
| self.buffer = [""] | |
| def print(self, v: str): | |
| self.buffer[self.y] += v | |
| self.y += 1 | |
| if len(self.buffer) <= self.y: | |
| self.buffer.append("") | |
| def end_block(self): | |
| self.y = 0 | |
| # allignment | |
| max_x = max(map(len, self.buffer)) + 1#padding | |
| self.buffer = list(map(lambda v: v + " "*(max_x - len(v)), self.buffer)) | |
| def flush(self): | |
| for c in self.buffer: | |
| print(c) | |
| class Stack: | |
| def __init__(self, logger: HorizontalPrint): | |
| self.stack = [] | |
| self.logger = logger | |
| def print(self): | |
| self.logger.print("=======") | |
| for value in self.stack: | |
| self.logger.print(f"|{value}") | |
| self.logger.print("=======") | |
| self.logger.end_block() | |
| def push(self, value: str): | |
| self.stack.append(value) | |
| self.print() | |
| def pop(self): | |
| self.stack.pop() | |
| self.print() | |
| def fib(n: int, stack: Stack): | |
| stack.push(f"fib({n})") | |
| if n == 0: result = 0 | |
| elif n == 1: result = 1 | |
| else: result = fib(n - 1, stack) + fib(n - 2, stack) | |
| stack.pop() | |
| return result | |
| hp = HorizontalPrint() | |
| fib(5, Stack(hp)) | |
| hp.flush() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment