0

My code is like a mix of recursive and iterative and I'm returning the list coins[] when my B reached 0. But I'm always getting None, although my list coins is for this example [5, 1, 1, 1].

Maybe someone know what the problem is, because I'm very new to programming.

coins = []


def greedy_coin_change(M, B):
    current_max = 0
    if B == 0:
        return coins

    for value in M:
        if value <= B:
            if value > current_max:
                current_max = value
    B = B - current_max
    coins.append(current_max)
    if B != 0:
        greedy_coin_change(M, B)
    if B == 0:
        return coins

print(greedy_coin_change([10, 5, 1], 8))

I got the solution, from a comment below. Just change it like that:

def greedy_coin_change(M, B):
.........
    if B != 0:
        return greedy_coin_change(M, B)
......
bad_coder
  • 11,289
  • 20
  • 44
  • 72
  • Is coins defined outside of the function on purpose? – DownloadPizza Apr 26 '21 at 15:58
  • it is defined outside because i dont want it to be resetted everytime when im going into my function. also dont wanna change the params because it is written like that from my school. –  Apr 26 '21 at 15:59
  • Also why not just `print(coins)` after calling your function? – quamrana Apr 26 '21 at 16:00
  • 1
    @newprogrammer22 well, you should know that using global variables like that is bad practice – juanpa.arrivillaga Apr 26 '21 at 16:00
  • The question is closed, but the answer is to add a return to greedy_coin_change(M, B). Also, I'll echo the responses saying not to use a global variable like that because the scope can get changed if you make a local variable of the same. – Andrew Holmgren Apr 26 '21 at 16:01
  • 1
    @AndrewHolmgren also, using mutable global state is a classic anti-pattern because it easily leads to "spaghetti code" – juanpa.arrivillaga Apr 26 '21 at 16:06

0 Answers0