I am trying to do this problem:
https://leetcode.com/problems/maximum-swap/description/
My method is basically "Check if the first digit in your number is the largest digit. If it is not, then swap it with the largest digit. If it is, then set aside the first digit in a list (called beginning), then do the same procedure on the new number (the one with the first digit chopped off)."
To do this I wrote a recursive function called swapper which I call elsewhere. I feed into it a list of the digits. It works correctly if
def swapper(digits, beginning):
print 'running: digits, beginning: ', digits, beginning
if len(digits) > 0: #If there is anything left in the number, continue checking if the first digit is the largest)
if digits.index(max(digits)) == 0:
beginning.append(digits[0])
print 'iterating: digits, beginning = ', digits[1:], beginning
swapper(digits[1:], beginning) #recursively run the function with a smaller digit list
else:
digits[digits.index(max(digits))], digits[0] = digits[0],
max(digits)
return beginning + digits
else: #If there is nothing left in the number, return the beginning list
#which is just all the digits at this point
print 'returning beginning'
print 'beginning: ', beginning
return beginning
#pseudocode here: digits = digits(digits of the number)
results = swapper(digits, [])
print 'results: ', results
It works if it never hits that commented "else" inside swapper, but if it does, it doesn't seem to return anything. Using the example number 9973, the stdout is:
running: digits, beginning: [9, 9, 7, 3] []
iterating: digits, beginning = [9, 7, 3] [9]
running: digits, beginning: [9, 7, 3] [9]
iterating: digits, beginning = [7, 3] [9, 9]
running: digits, beginning: [7, 3] [9, 9]
iterating: digits, beginning = [3] [9, 9, 7]
running: digits, beginning: [3] [9, 9, 7]
iterating: digits, beginning = [] [9, 9, 7, 3]
running: digits, beginning: [] [9, 9, 7, 3]
returning beginning
beginning: [9, 9, 7, 3]
results: None
It looks like it correctly partitions the digits into the beginning list. It then properly prints "beginning: ", beginning. The list exists and it's [9,9,7,3] like I expect. It's then supposed to return that. But when I print results outside the function it's just None. Why?
It returns properly via the other return statement (the one that says "return beginning + digits").