Skip to content

Instantly share code, notes, and snippets.

@milkey-mouse
Last active March 10, 2017 00:52
Show Gist options
  • Save milkey-mouse/23318ccf36893c3a3847 to your computer and use it in GitHub Desktop.
Save milkey-mouse/23318ccf36893c3a3847 to your computer and use it in GitHub Desktop.
it does what it says on the tin
form_consts = {
"ice": {
"temp": 0.0,
"c": 2.06,
"water": 334.0
},
"water": {
"temp": 100.0,
"c": 4.184,
"ice": -334.0,
"steam": 2260.0
},
"steam": {
"c": 1.87,
"water": -2260.0
}
}
def parse_sentence(sentence):
#print("Parsing sentence...")
idx = 0
while not sentence[idx].isdigit():
idx += 1
#print("Found first number at " + str(idx))
prefix = sentence[:idx].strip().lower()
sentence = sentence[idx:]
#print("Prefix: " + prefix)
#print("Sentence: " + sentence)
if prefix.startswith("calculate the amount of heat"):
#print("Detected conversion problem.")
return parse_part(sentence)
else:
#print("I dunno.")
return parse_part(sentence)
def parse_part(sent):
sent = [i.strip() for i in sent.split("to")]
mass = [i.strip() for i in sent[0].split("of")]
sent[0] = mass[1]
mass = float(mass[0].replace(" g", ""))
#print("Mass: " + str(mass))
if sent[-1].endswith("."):
sent[-1] = sent[-1][:-1]
#print(sent)
forms = []
for form in sent:
stripped = form.replace(" °C", "").replace("°C", "").replace("C", "").replace("liquid water", "water")
parts = stripped.split(" at ")
parts[1] = float(parts[1])
parts[0] = parts[0].lower()
parts = tuple(parts)
forms.append(parts)
if forms[0][1] < forms[1][1]:
return get_conversions(forms, mass)
else:
return get_conversions(forms, -mass)
def get_conversions(parts, mass):
convpoints = {}
highest = None
for name, form in form_consts.items():
if "temp" in form:
convpoints[float(form["temp"])] = name
else:
highest = name
#print("Conversion points: " + str(list(convpoints.keys())))
appconvs = {}
temps = []
for part in parts:
temps.append(part[1])
#print("Temps: " + str(temps))
for temp, name in convpoints.items():
if float(temp) <= max(temps) and float(temp) >= min(temps):
appconvs[temp] = name
convlist = list(appconvs.keys())
#print("Applicable points: " + str(convlist))
convs = []
for part in parts:
convs.append((part[1], part[0]))
lastform = appconvs[sorted(appconvs.keys())[0]]
lasttemp = None
#print("Starting form: " + lastform)
for k, v in appconvs.items():
convs.append((k, v))
convs.sort()
tempgrade = []
total = 0
for k in sorted(convpoints.keys()):
tempgrade.append(convpoints[k])
tempgrade.append(highest)
lasttemp = None
for iidx, jidx, i, j in zip(range(0,len(convs)),range(1,len(convs)+1),convs,convs[1:]):
ival = tempgrade.index(i[1])
jval = tempgrade.index(j[1])
if ival > jval:
convs[iidx] = j
convs[jidx] = i
for key, val in convs:
if val != lastform:
print(lastform + " => " + val + " " + str(form_consts[lastform][val]*mass) + "J")
total += form_consts[lastform][val]*mass
if lasttemp != None:
print(str(lasttemp) + " => " + str(key) + " " + str((key-lasttemp)*mass*form_consts[val]["c"])+ "J")
total += (lasttemp-key)*mass*form_consts[val]["c"]
lasttemp = key
lastform = val
return total
while True:
try:
print("Total: " + str(parse_sentence(input(">>"))) + " joules")
#print(parse_sentence("Calculate the amount of heat needed to convert 96.0 g of ice at -27 °C to steam at 100.0 °C."))
#print("Total: " + parse_sentence("Calculate the amount of heat needed to convert 96.0 g of steam at 100.0 °C to ice at -27 °C.") + " joules")
#print("Total: " + parse_sentence("Calculate the amount of heat needed to convert 96.0 g of steam at 100.0 °C to ice at -27 °C.") + " joules")
break
except KeyboardInterrupt:
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment