-2
  1. My denomination "5" is not showing up and how do you reverse the dict easily. i dont want extra 5 line of code.lol
  2. Can you guys help me out with it?
  3. the code is working so far.

  4. here is my code with a test case

    def change(target, coins):
        result = dict()
        i= len(coins) -1
        while i> 0:
            coin = coins[i]
            numOfThisCoin= target // coin
            result[coin] = numOfThisCoin
            target -= coin * numOfThisCoin
            i-= 1
        return result
    
    print(change(185, (5, 10, 25, 100, 200)))
    

i am getting output

    {200: 0, 100: 1, 25: 3, 10: 1}

but want it like

    {5: 0, 10: 1, 25: 3, 100: 1, 200: 0}
  • Dicts aren't supposed to be ordered. However, there's a `collections.OrderedDict`. – Jus Mar 07 '18 at 04:29

2 Answers2

0

Here is the corrected code for your problem:

from collections import OrderedDict

def change(target, coins):
    result = dict()
    i= len(coins) -1
    while i>= 0:
        coin = coins[i]
        numOfThisCoin= target // coin
        result[coin] = numOfThisCoin
        target -= coin * numOfThisCoin
        i-= 1
    res = OrderedDict(sorted(result.items()))
    return res

print(change(185, (5, 10, 25, 100, 200)))

If you (not only 25 you can access any coin denomination)

print(res[25])

Output will be

3

in this case. dict- it does not keep the elements in order. You have to use OrderedDict for sorting the elements in the order you want. For more info follow the below link:

http://docs.python.org/library/collections.html#collections.OrderedDict

Nishant Gupta
  • 3,533
  • 1
  • 11
  • 18
0
def change(target, coins):
    result = dict()
    i= len(coins) -1
    while i>= 0:
        coin = coins[i]
        numOfThisCoin= target // coin
        result[coin] = numOfThisCoin
        target -= coin * numOfThisCoin
        i-= 1
    return dict(sorted(result.items()))

print(change(185, (5, 10, 25, 100, 200)))
Rohit Chopra
  • 567
  • 1
  • 8
  • 24