# math_recursion.py # Walker M. White (wmw2) # September 9, 2012 """Functions from second recursion lecture""" def commafy_str(s): """Returns: s, with commas every 3 digits. Example: commafy('5341267') = '5,341,267' Precondition: s a string representing an integer n >= 0""" # You can't always check everything with an assert # However, check what you can assert type(s) == str, `s` + ' is not a string' if len(s) <= 3: return s; # String has more than 3 digits return commafy(s[0,len(s)-3]) + ',' +s[len(s)-3] def commafy(n): """Returns: n as a string, with commas every 3 digits. Example: commafy('5341267') = '5,341,267' Precondition: n is an int with n >= 0""" assert type(n) == int, `n`+' is not an int' # get in the habit assert n >= 0, `n`+' is negative' # get in the habit # return commafy(`n`) if n < 1000: return `n` # n >= 1000 return commafy(n/1000) + ',' + to3(n % 1000) def to3(p): """Returns: p with at least 3 chars Adds leading 0's if necessary Precondition: p is an int""" assert type(p) == int, `p`+' is not an int' # get in the habit if p < 10: return '00' + `p` elif p < 100: return '0' + `p` return `p` # Number of frames used in exp recursive calls count_frames = 0 def exp_slow(b, c): """Returns: b^c. Property: b^c = b * b^(c-1) Precondition: b a number, c >= 0 an int""" # get in the habit of checking what you can assert type(b) == float or type(b) == int, `b`+' is not a number' assert type(c) == int, `c`+' is not an int' assert c >= 0, `c`+' is negative' if c == 0: return 1 # Allows us to write to global variable. EVIL! Do not use! global count_frames # Used to count the number of frames count_frames = count_frames+1; # c > 0 return b * exp_slow(b, c-1) def exp_alt(b, c): """Returns: b^c. Property: b^c = b^(c/2) * b^(c-c/2) Precondition: b a float, c >= 0 an int""" assert type(b) == float or type(b) == int, `b`+' is not a number' assert type(c) == int, `c`+' is not an int' assert c >= 0, `c`+' is negative' if c == 0: return 1 # Allows us to write to global variable. EVIL! Do not use! global count_frames # Used to count the number of frames count_frames = count_frames+1; # c > 0 return exp_alt(b, c/2)*exp_alt(b,c-c/2) def exp_fast(b, c): """Returns: b^c. Property. b^c = b * b^(c-1) Property. b^c = (b*b)^(c/2) for even c Precondition: b a float, c >= 0 an int""" assert type(b) == float or type(b) == int, `b`+' is not a number' assert type(c) == int, `c`+' is not an int' assert c >= 0, `c`+' is negative' if c == 0: return 1 # Allows us to write to global variable. EVIL! Do not use! global count_frames # Used to count the number of frames count_frames = count_frames+1; # c > 0 if c % 2 == 0: return exp_fast(b*b, c/2) return b * exp_fast(b, c-1)