Search code examples
pythonpython-3.xappendgreedy

Greedy Algorithms and append function - how to create a new array?


Okay, so I have an array coin and I want to create a new array which is the same length as array, but with the amount of coins from the array 'coins' needed for input m.

coin = [200,100,50,20,10,5,2,1]

So far, I have the following. What should be in for loop for me to return what I want?

def coinSplitGD2(m):

    coin = [200,100,50,20,10,5,2,1]

    if m==0:
        return 0
    for i in range(len(coin)):
        if coin...

So if m is 143, it will return [0, 1, 0, 2, 0, 0, 1, 1] meaning no 200-coins, one 100-coin, no 50-coins, two 20-coins, no 10-coins, no 5-coins, one 2-coin and one 1-coin


Solution

  • coin = [200,100,50,20,10,5,2,1]
    def coinSplitGD2(m):
        a = []
        for c in coin:
            a.append(m // c)
            m %= c
        return a
    

    so that:

    coinSplitGD2(143)
    

    returns:

    [0, 1, 0, 2, 0, 0, 1, 1]