Last active
August 29, 2015 14:07
-
-
Save evanpeck/435778e8015f3a95985f to your computer and use it in GitHub Desktop.
While teaching recursion in an Introduction to CS class, I wasn't terribly happy with any existing visualizations of recursive methods. I created a very simple command-line vis that traces the calls in sumOfDigits
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
''' | |
ORIGINAL FUNCTION | |
def sumOfDigits(numberString): | |
if len(numberString) < 1: | |
return 0 | |
else: | |
return int(numberString[0]) + sumOfDigits(numberString[1:]) | |
''' | |
def sumOfDigits(numberString, depth=0): | |
''' | |
Calculates the sum of a string of digits. | |
Creates a visual trace of the recursion. | |
Print assumes that you are using Python 3+ | |
Used in CSCI203 at Bucknell University. | |
input: a string of digits - '2345561' | |
output: the sum of the digits (int) | |
''' | |
if depth == 0: | |
print() | |
print('Original Call: sumOfDigits(\'' + numberString + '\')\n') | |
if len(numberString) < 1: | |
return 0 | |
else: | |
simpleStep = int(numberString[0]) | |
rest = numberString[1:] | |
print(' |\t'*depth, simpleStep, '+', 'sumOfDigits(\''+str(rest)+'\')') | |
print('\t'*(depth+1), '|') | |
compute = sumOfDigits(rest, depth+1) | |
answer = simpleStep + compute | |
print(' |\t'*depth, simpleStep, '+', compute, '=', answer) | |
print('\t'*depth) | |
return answer | |
if __name__ == '__main__': | |
# An example of running the function | |
sumOfDigits('184323') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment