A challenge from the Mensa Puzzle Calendar

Chris Myers chris.myers at prov.ingenta.com
Fri Oct 4 13:15:17 EDT 2002


Thanks, all for your response to my challenge!
I'm sufficiently humbled by looking at the quality of code I've read.

Some of what I saw was pretty complex for my eyes (I'm still looking
over some of it), but IMHO (as OP, judge, and jury for the contest), I
choose Raymond Hettinger's entry, based on elegance, innovation and
brevity:

for a in range(700,800):
    for b in range(100):
        digits = list('%d%d%d' % (a, b, a*b))
        digits.sort()
        if digits == list('0123456789'):
            print '%5d\n%5d\n-----\n%5d' % (a, b, a*b)

Which can be easily generalized by changing the first line to 

for a in range(1000):

and the 3rd line to 

        digits = list('%.3d%.2d%.5d' % (a, b, a*b))

in order to catch those solutions with operands and results beginning
with '0'.

So, my generalized sol'n of Raymond's answer is:

for a in range(1000):
    for b in range(100):
        digits = list('%.3d%.2d%.5d' % (a, b, a*b))
        digits.sort()
        if digits == list('0123456789'):
            print '\n%5.3d\n%5.2d\n-----\n%5.5d' % (a, b, a*b)


This generalized solution takes less than 4 seconds to run on my
computer!


My solution, below, took almost 4 MINUTES!!  (Again, sufficiently
humbled am I)

def list_less(short_list):
    l = range(10)
    for i in short_list:
        l.remove(i)
    return l

for a in list_less([]):
  for b in list_less([a]):
    for c in list_less([a,b]):
      for d in list_less([a,b,c]):
        for e in list_less([a,b,c,d]):
          for f in list_less([a,b,c,d,e]):
            for g in list_less([a,b,c,d,e,f]):
              for h in list_less([a,b,c,d,e,f,g]):
                for i in list_less([a,b,c,d,e,f,g,h]):
                  for j in list_less([a,b,c,d,e,f,g,h,i]):
                      if (100*a + 10*b + c) * (10*d + e) == \
                         10000*f + 1000*g + 100*h + 10*i + j:
                          (A,B,C,D,E,F,G,H,I,J) =
(a,b,c,d,e,f,g,h,i,j)
                          print "\n  %d%d%d\nX 
%d%d\n-----\n%d%d%d%d%d\n" \
                                %(A,B,C,D,E,F,G,H,I,J)


I originally thought this was a pretty solution -- not so much
anymore.

Again, thanks, all for accepting my challenge.
Please, post more puzzles of this sort -- anyone.

Cheers,
Chris

PS: Actual solutions to the generalized version of the puzzle:

138 * 42 = 05796
157 * 28 = 04396
159 * 48 = 07632
186 * 39 = 07254
198 * 27 = 05346
297 * 18 = 05346
297 * 54 = 16038
345 * 78 = 26910
367 * 52 = 19084
396 * 45 = 17820
402 * 39 = 15678
483 * 12 = 05796
495 * 36 = 17820
594 * 27 = 16038
715 * 46 = 32890
927 * 63 = 58401

I'm a number theory buff, so I noticed some fascinating things:
  two of the sol'ns use one of the same operands - 297
  THREE of the sol'ns generated the same product!!
 
How cool is that?!
:-)



More information about the Python-list mailing list