I would like to only allow lists where the first n elements are True
and then all of the remaining elements are False
. I want lists like these examples to return True
:
[]
[True]
[False]
[False, False]
[True, False]
[True, False, False]
[True, True, True, False]
And lists like these to return False
:
[False, True]
[True, False, True]
That is, any list that can we written as [True] * n + [False] * m
for n
, m
integers in the interval [0, infty).
I am currently using a function called check_true_then_false
, but I feel like there is probably a neater way of doing this. The code doesn't need to be fast, as this will only be run once (not inside a loop) and the lists will short (single digit lengths).
def check_true_then_false(x):
n_trues = sum(x)
should_be_true = x[:n_trues] # get the first n items
should_be_false = x[n_trues:len(x)] # get the remaining items
# return True only if all of the first n elements are True and the remaining
# elements are all False
return all(should_be_true) and not any(should_be_false)
Testing shows that it produces the correct output:
test_cases = [[True],
[False],
[True, False],
[True, False, False],
[True, True, True, False],
[False, True],
[True, False, True]]
print([check_true_then_false(test_case) for test_case in test_cases])
# expected output: [True, True, True, True, True, False, False]
[]
,[True]
, and[False, False]
acceptable? \$\endgroup\$[True] * n + [False] * m
forn
,m
integers in the interval [0, infty). \$\endgroup\$