Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Matrix sol. I <3 Fractions. solution in Clear category for How Much Gold by Lasica
from fractions import Fraction
METALS = {'gold':0, 'tin':1, 'iron':2, 'copper':3}
def checkio(alloys):
"""
Find proportion of gold - we actually are given 4 linear equations with
proportions of metal X/weight of the bar. Those equations are
3 given by "alloys" and one, that alltogether proportion is equal 1
I will keep the coefficients of the variables in matrix...
And solve it with Gaussian elimination
"""
#initialisation of matrix
matrix = [[Fraction(0) for i in range(5)] for j in range(3)] # 5 columns 3+1 rows
matrix.append([Fraction(1) for i in range(5)]) # last equation - all alloys alltogether = 1
#translates alloys for coefficients in matrix
for num, dictpair in enumerate(alloys.items()):
for metal_name in dictpair[0].split('-'):
matrix[num][METALS[metal_name]] = Fraction(1)
matrix[num][-1] = dictpair[1]
# returns sum of 2 rows starting from column fromcol, where second one is multiplied by mult
addrows = lambda row1, row2, mult=1, fromcol=0: [x+mult*row2[n] for n,x in enumerate(row1[fromcol:], fromcol)]
# returns index of first row which has non-zero value on column "column". Looks for rows from row with index rowrange
findrowindex = lambda column, rowrange: [x for x in range(rowrange,len(matrix)) if matrix[x][column]][0]
#Gaussian elimination
for n, row in enumerate(matrix,0):
if not row[n]:
to_swap_ind = findrowindex(n,n+1)
matrix[n], matrix[to_swap_ind] = matrix[to_swap_ind], matrix[n]
row = matrix[n]
for j in matrix[:n]+matrix[n+1:]:
if j[n]:
j[n:] = addrows(j, row, -j[n]/row[n], n)
return Fraction(1, matrix[0][0])*matrix[0][4]
April 26, 2014
Comments: