Search code examples
pythonfor-loopalgebra

How to use nested for-loops to find the x and y of a linear equation


I'm trying to find how many 10 and 50 dollar bills go into $1760 if there are only 160 bills. I figured, with the help of a friend, that using a nested for-loop is the best way to go but I'm having issues with implementation. My idea is to iterate every x one-by-one until 160 and if then the equation != 1760, I increment y by 1 and restart.

These are the equations: 10x + 50y = 1760, x + y = 160

My desired output is: 10(156) + 50(4) = 1760. But so far, all I've been getting is this:

10(1) + 50(0) = 10
10(2) + 50(1) = 70
10(3) + 50(2) = 130
10(4) + 50(3) = 190
10(5) + 50(4) = 250
...
...
...
10(156) + 50(30) = 3060
10(157) + 50(30) = 3070
10(158) + 50(30) = 3080
10(159) + 50(30) = 3090
10(160) + 50(30) = 3100

And for some reason, y stuck at 30 starting when x = 31. I don't know why. Anyways, this is my code:

for i in range(1, 161):
    print("10" + "(" + str(i) + ") + 50" + "(" + str(y) + ")" + " = " + str((10*i)+(50*y)))
    if ((10*i)+(50*y) < 1760):
        y += 1

I don't want the exact answer. I just want to know where I'm going wrong.


Solution

  • Why your y gets 'stuck' at 30:

    Once the sum exceeds 1760, y never gets incremented again as (10*x + 50*y) < 1760 is always False. This happens at x=31 and y=30, which is why your y is 'stuck' at 30.


    Your approach is almost complete but there is a minor bug in the logic:

    Instead of running the 10-bills, x, up to 160 and increment the 50-bills, y, by one only if the amount exceeds the desired sum, you can run the 10-bills up to 160 and directly set the amount of 50-bills in each iteration to be y = 160 - x. This is because you enforce this condition (160 = x + y) so only configurations that fulfill this requirement need to be considered.

    So, you were right in that you only need a single for loop, but you can set y in every iteration directly as 160 = x + y, and then you only need to check if the amount is correct.

    So the Ansatz for this solution looks something like:

    for x in range(0, 161):
        y = 160 - x
        # calculate the sum
        # if the sum is correct, break