Learning Python

Gabriel Genellina gagsl-py at yahoo.com.ar
Fri Aug 11 20:32:32 EDT 2006


At Friday 11/8/2006 18:04, Dr. Pastor wrote:

>Attempting to learn Python; I constructed the module
>listed below. I would like to make it shorter, faster,
>more "Python like". (Windows XP, Pro.)
>Many thanks for any advice!
>...
>
>#-------------------------------------------------------------------------------
>   # Name:        SendMoreMoney.py
>   # Purpose:     A solution to the SEND+MORE=MONEY puzzle.
>   #
>   # Author:      Dr. Pastor
>   #
>   # Copyright:   (c) Dr. Pastor 2006
>
>#-------------------------------------------------------------------------------
>   #!/usr/bin/env python

This line is not used on Windows, but if you want to include it, must 
be the very first line on the script.


>#
># The solution for the puzzle of
>#        SEND
>#       +MORE
>#       -----
>#       MONEY
>#
>
>def perm(items, n=None):
>      if n is None:
>          n = len(items)
>      for i in range(len(items)):
>          v = items[i:i+1]

I would use v = [items[i]] but that's a matter of taste...

>          if n == 1:
>              yield v
>          else:
>              rest = items[:i] + items[i+1:]
>              for p in perm(rest, n-1):
>                  yield v + p
>
>def comb(items, n=None):
>      if n is None:
>          n = len(items)
>      for i in range(len(items)):
>          v = items[i:i+1]

Same as above.

>          if n == 1:
>              yield v
>          else:
>              rest = items[i+1:]
>              for c in comb(rest, n-1):
>                  yield v + c
>#
>#   S   E   N   D   M   O   R   Y
># ['0','1','2','3','4','5','6','7','8','9']
>#
>print
>print "Selections of 8 items from 10 then the permutation of them."
>print
>b=0
>for s in comb([0,1,2,3,4,5,6,7,8,9],8):
>      for a in perm(s,None):
>          if (a[4]*1000+a[5]*100+a[2]*10+a[1])*10+a[7] == \
>               (a[0]+a[4])*1000+(a[1]+a[5])*100+(a[2]+a[6])*10+(a[3]+a[1]):

Backslash as continuation is a bit problematic (add an empty space 
after it and it's broken...) so it's better to add an open parens; 
continuation is implicit until the last parens is closed:

          if (a[4]*10000+a[5]*1000+a[2]*100+a[1]*10+a[7] ==
               (a[0]+a[4])*1000+(a[1]+a[5])*100+(a[2]+a[6])*10+(a[3]+a[1])):

If speed is not the most important thing, you could assign names to 
the 8 items:

         S, E, N, D, M, O, R, Y = a
         if poly(10, M,O,N,E,Y) == poly(10, S,E,N,D) + poly(10, M,O,R,E):

which is infinitely more legible (and a bit compact, too).
(poly is left as an exercise: def poly(x, *args): )

And a,b,s are too short names...



Gabriel Genellina
Softlab SRL 


	
	
		
__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas




More information about the Python-list mailing list