Question 6: A Python solution
import os
import re
import robobrowser
import math
start_url = 'http://hackoff.apps.mclean.net.nz/spreadsheet/question-001'
cell_data = {}
def save_response(ua):
try:
os.rename('response.html', 'response-prev.html')
except FileNotFoundError:
pass
finally:
with open('response.html', 'w') as out:
out.write("<!-- {} -->\n{}".format(ua.url, ua.response.text))
def extract_data(ua):
cell_data.clear()
rows = ua.find_all('tr')[1:]
r = 1
for row in rows:
c = 0
for cell in row.find_all('td'):
key = "{0}{1}".format(chr(ord('A') + c), r)
cell_data[key] = cell.text
c+=1
r+=1
def cell_value(match):
return cell_data[match.group(0)]
def solve(formula):
formula = re.sub(r'\b([A-Z]\d+)\b', cell_value, formula)
print(" Substituted: " + formula)
return eval(formula)
def SQRT(val):
return math.sqrt(val)
def MAX(*args):
return sorted(args)[-1]
os.system("rm -rf work; mkdir work")
os.chdir("work")
ua = robobrowser.RoboBrowser()
ua.open(start_url)
for i in range(101):
print("\n" + ua.url)
save_response(ua)
form = ua.get_forms()[0]
formula = form['formula'].value
print(" Formula: {}".format(formula))
extract_data(ua)
solution = solve(formula)
print(" Solution: {}".format(solution))
form['solution'].value = "{}".format(int(solution))
ua.submit_form(form)