Learning Python

Dr. Pastor elpX at adsihqX.com
Fri Aug 11 17:04:12 EDT 2006


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

#
# 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]
         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]
         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]):
             b += 1
             print ' SEND', '  ',a[0],a[1],a[2],a[3]
             print ' MORE', '  ',a[4],a[5],a[6],a[1]
             print ' ----', ' ---------'
             print 'MONEY', '',a[4],a[5],a[2],a[1],a[7]
             print
print "There are ", b, " solutions."
print
...
















----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----



More information about the Python-list mailing list