3 import sys, os, re, fractions
4 from fractions import Fraction
8 header_re = re.compile(r'^(\d+) into (\d+).*:.* ([\d/]+)')
9 dissect_re = re.compile(r'\s+(\d+)\s+x\s+\((([\d/]+ \+ )*[\d/]+)\)')
13 def find_min_frag(dissection):
15 for side in dissection:
16 for count, pieces in side:
19 if ret is None or ret > piece:
21 assert ret is not None
24 def verify(n, m, dissection):
25 collections = [{}, {}]
27 for count, pieces in dissection[0]:
28 assert sum(pieces) == n
31 collections[0].setdefault(piece, 0)
32 collections[0][piece] += count
35 for count, pieces in dissection[1]:
36 assert sum(pieces) == m
39 collections[1].setdefault(piece, 0)
40 collections[1][piece] += count
42 assert collections[0] == collections[1]
47 # Look for appropriate file(s).
48 for filename, nature in [("data/main.%d.%d" % (n,m), "e"),
49 ("data/partition.%d.%d" % (n,m), "p"),
50 ("data/manual.%d.%d" % (n,m), "m")]:
51 if os.path.exists(filename):
52 with open(filename) as f:
54 match = header_re.match(header)
55 assert match is not None
56 assert int(match.group(1)) == n
57 assert int(match.group(2)) == m
58 this_best = Fraction(match.group(3))
60 # Now read the actual dissection.
62 for line in f.readlines():
63 match = dissect_re.match(line)
65 count = int(match.group(1))
66 pieces = map(Fraction, match.group(2).split(" + "))
69 dissection[0].append((count, pieces))
71 dissection[1].append((count, pieces))
73 assert False, "wrong length"
74 verify(n, m, dissection)
75 assert find_min_frag(dissection) == this_best
76 dissections[(n,m)] = dissection
82 bound, bound_type = bounds.upper_bound(n, m)
87 elif best_nature == 'e':
90 elif best_nature == 'p':
95 show_bound = " – %s"
96 sys.stdout.write("<td class=\"%s\">" % tdclass)
97 sys.stdout.write(str(best))
99 sys.stdout.write(show_bound % str(bound))
100 sys.stdout.write("</td>\n")
103 limit = 18 # FIXME: configurable
104 sys.stdout.write("""\
107 <title>Known bounds for stick-dissecting problem</title>
108 <style type="text/css">
110 border: 1px solid black;
111 border-collapse: collapse;
114 background-color: #00ff00;
117 background-color: #aaff00;
120 background-color: #ffff00;
123 background-color: #ff8888;
130 sys.stdout.write("<tr>\n")
131 sys.stdout.write("<th>n \\ m</th>\n")
132 for m in range(2,limit-1):
133 sys.stdout.write("<th>%d</th>\n" % m)
134 sys.stdout.write("</tr>\n")
135 for n in range(2,limit):
136 sys.stdout.write("<tr>\n")
137 sys.stdout.write("<th>%d</th>\n" % n)
140 sys.stdout.write("</tr>\n")
141 sys.stdout.write("</table>\n")
142 sys.stdout.write("</body></html>\n")
144 if __name__ == "__main__":