A more pythonic way of writting

Gerard flanagan grflanagan at gmail.com
Fri Dec 5 10:16:09 EST 2008


eric wrote:
> Hi,
> 
> I've got this two pieces of code that works together, and fine
> 
> def testit():
>     for vals in [[i&mask==mask for mask in [1<<j for j in range(6)] ]
> for i in range(1<<6)]:
>         print vals, '->',  flag(*vals)
> 
> def flag(IGNORECASE=False, LOCALE=False, MULTILINE=False,
> DOTALL=False, UNICODE=False, VERBOSE=False):
>     vals = [IGNORECASE, LOCALE, MULTILINE, DOTALL, UNICODE, VERBOSE]
>     filtered = map( lambda m:m[1],filter( lambda m: m[0], zip(vals,
> 'iLmsux')))
>     return '?'+''.join( filtered  )
> 
> testit()
> 
> but I'm not proud of the way it is written. I dont find it very
> pythonic.
> I have to multiplex (using zip) bool and value, filter using only the
> bool, and demultiplex later using map
> 
> the first simply parses all the possible combination of 6 boolean
> (can't hardly be made simpler)
> 
> the second function, should simply return a string based on the
> boolean value
>     i,       L,       m,      s,      u,     x,
>     True, False, False, True, True, False
> =  ?isu
> 
> that's should take only one line, shouldn't it?
> 
> any idea ?
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

#after Paul Rubin (c.l.py)
def hypercube(ndims):
     if ndims == 0:
         yield ()
         return
     for h in 1, 0:
         for y in hypercube(ndims-1):
             yield (h,)+y

#after Mark Tolonen
for item in hypercube(6):
     print ''.join(c for c,v in zip('iLmsux', item) if v)





More information about the Python-list mailing list