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.
a == 0
, then I set a separate variable b = 0
. a == 1
, then I set b = 1
.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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With