[Python] How can I successfully call a recursion method in Python?

Discussão em 'Python' iniciado por Stack, Março 22, 2025.

  1. Stack

    Stack Membro Participativo

    I read and reread about recursion. I've seen so many videos and Stack Overflow posts, but I just don't get it. I've been going round and round for three hours on this recursion solution (BTW, yes, I know it's a greedy/unsafe solution)


    Example: given coins [10, 5, 1] cents, find the minimum number of each coin to total 18 cents. A solution is supposed to return the coin collection [10, 5, 1, 1, 1].
    ​

    I can't get it to move past the first coin, 10 in the collection. What am I missing and why?

    def r_change_money(total, denominations):
    def collect_coins(total, denominations):
    if total == 0:
    return False
    # fd (floor division)
    fd = total // denominations[0]
    addl_coins = [denominations[0]] * fd
    total -= fd * denominations[0]
    denominations.pop(0)
    return addl_coins

    # sort highest denom first
    denominations.sort(reverse=True)
    # holds coin collection
    coins = []
    coins += collect_coins(total, denominations)
    return coins

    # [10, 5, 1, 1, 1]
    print(r_change_money(18, [1, 10, 5]))

    # [6, 1, 1] (although safe answer is [4, 4])
    print(r_change_money(8, [6, 1, 4]))


    At least this solution isn't giving me errors anymore, but I am getting:

    [10]
    [6]

    Continue reading...

Compartilhe esta Página