views:

63

answers:

1

Hello. I'm having trouble getting my list to return in my code. Instead of returning the list, it keeps returning None, but if I replace the return with print in the elif statement, it prints the list just fine. How can I repair this?

def makeChange2(amount, coinDenomination, listofcoins = None):
#makes a list of coins from an amount given by using a greedy algorithm
    coinDenomination.sort()
    #reverse the list to make the largest position 0 at all times
    coinDenomination.reverse()
    #assigns list
    if listofcoins is None:
        listofcoins = []
    if amount >= coinDenomination[0]:
        listofcoins = listofcoins + [coinDenomination[0]]
        makeChange2((amount - coinDenomination[0]), coinDenomination, listofcoins)
    elif amount == 0:
        return listofcoins
    else:

        makeChange2(amount, coinDenomination[1:], listofcoins)
+4  A: 

You're not returning the value of the recursive calls to makeChange2.

Once control reaches either of those calls to makeChange2 and completes the call, the program continues to the next statement, which is the end of the function; thus, it returns None.

If that concept is still giving you trouble, try running this simple factorial program with and without the return keyword in the return n*factorial(n-1) line:

def factorial(n):
   if n == 0 or n == 1:
       return 1
   return n * factorial(n-1)

print factorial(3)

Manually walking through the code should help elucidate what was wrong in your original program.

Mark Rushakoff
I don't get it still. How is it returning to the end of the function if amount always goes to 0? It shouldn't reach the end of the function. Also, I have walked through this bloody thing for 10 hours. Trust me, I only ask places like this as a last resort. I'm stumped, and I simply do not know what to do. Also, adding return does not work: return makeChange2((amount - coinDenomination[0]), coinDenomination, listofcoins) elif amount == 0: return listofcoins
Nate
Nevermind, I see what you are saying now. I have to return in both if and else statements, or it goes to the end of the list in every call except the last. Thankyou for your help.
Nate