In Python, I cannot find a solution as to how to determine whether there is always a 0 following a 1 somewhere in a list of numbers, to form a pair 10. It doesn't have to be direct follower.
For clarity, I mean "list" as in (sort of) binary number, to be specific,
1100 #pass
1001 #fail
1010 #pass
0101 #fail11110000 #pass
11100001 #fail11100100 #pass
There must be always an equal number of 1es before 0es.
Thanks in advance.
Keep a temp variable, initialized at 0
. Increment it for each 1
, decrement it otherwise.
It should never be negative, and to make sure there are as many 1
as 0
, it should be equal to 0
at the end.
def check(bits):temp = 0for bit in bits:if temp < 0:return Falseif int(bit) == 1:temp += 1else:temp -= 1return temp == 0
As an example:
>>> check('1100')
True
>>> check('110001')
False
>>> check('1')
False
>>> check('10')
True
>>> check('1010')
True
>>> check('123')
False