-1

textbook prompt: BETTERCHANGE is not a correct algorithm. Suppose we were changing 40 cents into coins with denominations of c1 = 25, c2 = 20, c3 = 10, c4 = 5, and c5 = 1. BETTERCHANGE would incorrectly return 1 quarter, 1 dime, and 1 nickel, instead of 2 twenty-cent pieces.

def BETTERCHANGE(M,c,d):
    r = float(M);
    result = [];
    for k in range(1,d+1):
        i = r/c[k-1]
        r = r - c[k-1]*i;
        i = int(i);
        result.append(i);
    return result;
M = 40
c = [25,20,10,5,1]
d = 5

print(BETTERCHANGE(M,c,d))

gives [1, 0, 0, 0, 0]

when I am trying to get the return value of [1,0,1,1,0], like the one of the text above. Could you please advice me how to fix the code to get such anaswer?

riven
  • 27
  • 4

1 Answers1

1

You can do everything using integer arithmetic, rather than converting M to float.

Use // for integer division, which will round down. Then use % to get the remainder after the division.

There's no need to use d, you can just iterate over all the elements of c.

def BETTERCHANGE(M,c,d):
    result = [];
    for coin in c:
        i = M // coin
        M = M % coin
        result.append(i);
    return result;

M = 40
c = [25,20,10,5,1]
d = 5

print(BETTERCHANGE(M,c,d))
Barmar
  • 741,623
  • 53
  • 500
  • 612