Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way of counting True and False

This may be a trivial problem, but I want to learn more about other more clever and efficient ways of solving it.

I have a list of items and each item has a property a whose value is binary.

  • If every item in the list has a == 0, then I set a separate variable b = 0.
  • If every item in the list has a == 1, then I set b = 1.
  • If there is a mixture of a == 0 and a == 1 in the list, then I set b = 2.

I can use a set to keep track of the types of a value, such that if there are two items in the set after iterating through the list, then I can set b = 2, whereas if there is only one item in the set I just retrieve the item (either 0 or 1) and use it to set b.

Any better way?

like image 880
ChrisG Avatar asked Oct 07 '13 15:10

ChrisG


1 Answers

One pass through the list, and no extra data structures constructed:

def zot(bs):
    n, s = len(bs), sum(bs)
    return 1 if n == s else 2 if s else 0
like image 72
Tim Peters Avatar answered Oct 20 '22 03:10

Tim Peters