In order to solve this problem, we need to calculate the following proportion
(a1) gold-tin
(a2) gold-copper
(a3) gold-iron
Once we got (a1), (a2), and (a3), we can calculate the proportion of gold applying the following equation:
gold = ( (a1)+(a2)+(a3) - 1 ) / 2
Therefore we can divide this question into three sub-questions (a1) (a2) (a3).
Firstly, we can categorize the given proportion into two classes.
(b1) proportion consists of "gold"
Ex. gold-tin proportion
(b2) proportion doesn't consist of "gold"
Ex. copper-iron proportion
If the given proportion belongs to (b1), we just return it
However, when it belongs to (b2), we return (1 - given_proportion)
And following is the source code
from fractions import Fraction
METALS = ('gold', 'tin', 'iron', 'copper')
def get_proportion(ele1, ele2, ele3, ele4, alloys):
#print(ele1+','+ele2+','+ele3+','+ele4)
if ele1+'-'+ele2 in alloys:
return alloys[ele1+'-'+ele2]
elif ele2+'-'+ele1 in alloys:
return alloys[ele2+'-'+ele1]
elif ele3+'-'+ele4 in alloys:
return 1 - alloys[ele3+'-'+ele4]
elif ele4+'-'+ele3 in alloys:
return 1 - alloys[ele4+'-'+ele3]
else:
assert(0)
def checkio(alloys):
#step 1. find proportion of gold-tin, gold-iron, and gold-copper
gold_tin = get_proportion('gold', 'tin', 'iron', 'copper', alloys)
gold_iron = get_proportion('gold', 'iron', 'tin', 'copper', alloys)
gold_copper = get_proportion('gold', 'copper', 'tin', 'iron', alloys)
#step 2.
return Fraction(gold_tin + gold_iron + gold_copper - 1, 2)
沒有留言:
張貼留言