1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
from itertools import combinations # the sixteen numbers used s16 = set(range(1, 17)) # a set for storing any solutions sol = set() # select the first row (which are all single digits) for p in combinations(range(1, 10), 4): # compute the top row as a number nbr = int(''.join(str(x) for x in p)) # now select the second row from the remaining numbers s12 = s16 - set(p) for q in combinations(s12, 4): # check that their product equals the first row number if q[0] * q[1] * q[2] * q[3] == nbr: # check that they are greater than those above if all(x < y for x, y in zip(p, q)): # now set the third row from the remaining numbers s08 = s12 - set(q) for r in combinations(s08, 4): # and check that they are greater than those above if all(x < y for x, y in zip(q, r)): # and repeat this for the fourth row s = tuple(s08 - set(r)) if all(x < y for x, y in zip(r, s)): # store the table for any solutions found sol |= set(((p, q, r, s),)) # print any solutions for t in sol: print() for r in t: print('{0[0]:3d}{0[1]:3d}{0[2]:3d}{0[3]:3d}'.format(r)) |