Mo' Money- Making An "algorithm" To Solve Two Variable Algebra Problems
Solution 1:
Using numpy for the system:
x+y=160
10x+50y=1760
import numpy as np
a = np.array([[1, 1], [10, 50]])
b = np.array([160, 1760])
x = np.linalg.solve(a, b)
print(x)
Outputs:
[156. 4.]
Solution 2:
There are a total of two variables, the number of tens and the number of fifties. So you could do nested for-loops. A really blunt way of doing this would be:
for fifties in range(161):
for tens in range(161-fifties):
if (fifties+tens == 160) and (50*fifties + 10*tens == 1760):
break
We can improve that a bit by noting that each time we increase the number of fifties, we decrease the possible number of tens:
for fifties in range(161):
for tens in range(161-fifties):
if (fifties+tens == 160) and (50*fifties + 10*tens == 1760:
break
It can be improved even further by noting that although there are a total of two variables, we have the constraint that they add up to 160. Thus, we can use this constraint to get one given the other:
for fifties in range(161):
tens =160 - fifties
if50*fifties + 10*tens == 1760:
break
Solution 3:
You can take a dynamic programming approach to this for a general solution:
Set up some edge conditions where there is no answer:
- If the length of notes it less than 1
- You have one note but the total is not divisible by the denomination there's no answer.
The take a note off and see if it works by recursively calling the function with the remaining notes and adjusted bill-count/total.
defcountNotes(notes, total, bills):
iflen(notes) < 1:
returniflen(notes) == 1:
return [bills] if bills * notes[0] == total elseNonefor count inrange(bills+1):
amount = notes[0] * count
rest = countNotes(notes[1:], total - amount, bills - count)
if rest:
return [count, *rest]
countNotes([50, 10], 1760, 160)
#[4, 156]
countNotes([100, 20, 5], 173, 2)
# None -- not possible
countNotes([100, 20, 5, 2], 1255, 61)
#[1, 57, 3, 0]
This will return the counts as a list in the same order as the notes passed in. If you're dealing with large lists and totals if could be improved by memoizing it.
Solution 4:
d = {'x': 10, 'y': 50} #create dictionary to hold bill values
total_value = 1760
num_bills = 160
y = (total_value - num_bills *d['x']) / (d['y']-d['x']) #isolating y
x = num_bills - y # isolating x with y value knownprint("the number of ten dollar bills is: " + str(x))
print("the number of fifty dollar bills is: " + str(y))
Post a Comment for "Mo' Money- Making An "algorithm" To Solve Two Variable Algebra Problems"