simultaneous assignment

Grant Edwards grante at visi.com
Tue May 2 15:05:23 EDT 2006


On 2006-05-02, John Salerno <johnjsal at NOSPAMgmail.com> wrote:

> Yeah, after trying some crazy things, I just wrote it this way:
>
> def truth_test(seq):
>      truth = 0
>      for item in seq:
>          if item:
>              truth += 1
>      if truth == 1:
>          return True
>      else:
>          return False
>
> Not sure I like having to keep a counter though, but the other stuff I 
> did was really convoluted, like checking to see if the first item was 
> True, and if it was, popping it from the list and iterating over the 
> rest of the items (needless to say, the in-place change wasn't helpful).

Python knows how to count.  :)

def countFalse(seq):
    return len([v for v in seq if not v])

def countTrue(seq):
    return len([v for v in seq if v])

def truth_test(seq):
    return countTrue(seq) == 1

-- 
Grant Edwards                   grante             Yow!  I FORGOT to do the
                                  at               DISHES!!
                               visi.com            



More information about the Python-list mailing list