[Tutor] Is there a better way to do this?

Jeff Shannon jeff at ccvcorp.com
Thu Jul 22 23:40:54 CEST 2004

Hee-Seng Kye wrote:
> I'm trying to write a program that computes six-digit numbers, in which 
> the left digit is always smaller than its following digit (i.e., it's 
> always ascending).  The output of the program starts with "0 1 2 3 4 5" 
> and ends on "6 7 8 9 A B."  The best I could do was to have many 
> embedded 'for' statements:
> c = 1
> for p0 in range(0, 7):
>   for p1 in range(1, 12):
>     for p2 in range(2, 12):
>       for p3 in range(3, 12):
>         for p4 in range(4, 12):
>           for p5 in range(5, 12):
>             if p0 < p1 < p2 < p3 < p4 < p5:
>               print repr(c).rjust(3), "\t",
>               print "%X %X %X %X %X %X" % (p0, p1, p2, p3, p4, p5)
>               c += 1
> print "...Done"

I don't have the time / spare brain cycles to write real sample code, 
but if I were doing something like this, I'd look closely at the 
possibility of using a recursion instead of multiply-nested for loops. 
  You might be able to craft a recursive generator that would iterate 
over its sub-generator and then itself.  I don't know whether this 
would be likely to run *faster*, but it would be a lot more flexible 
than manually writing out N levels of for-loops...

def my_generator(depth, min, max):
     for n in range(min, max):
         for result in my_generator(depth-1, n, max):
             yield (n,) + result

for results in my_generator(depth, min, max):
     format = " ".join(["%X"] * depth)
     print format % results

The generator there won't actually work -- it needs to do 
bounds-checking on depth before entering the loop, and of course I 
haven't tested *any* of this -- but this may give you a starting point.

Jeff Shannon
Credit International

More information about the Tutor mailing list