I have a list containing only True
and False
values. I am looking for a pattern when the elements of the list changes from True
to False
or vise versa more than 3 times.
Example (T is used for True
and F for False
for abbreviation):
List = [T, T, T, F, F, F, T, F, T, F, T, T, T, T]
What I want to detect is: [F, T, F, T, F, T]
and its starting index in the original list.
Please note that the pattern is not fixed. It may be [F, T, F, T, F, T]
or [T, F, T, F, T]
.
If you have any idea to accomplish this task efficiently, please let me know.
If fact, I need this detection to be done in real-time. I mean, the List
is being made by getting data from another source (timestamp is 0.5 second). And I need to detect the above mentioned pattern in the List
. In you are aware how to solve this problem (either real time or not), please let me know.
Well, you could make each list into a string:
newlist=['T' if x is True else 'F' for x in mylist]
newstring=''.join(newlist)
Then find the position of the match to 'FTFTFT' as described in the accepted answer to this question.
The problem is analogous to finding the subarray of maximum length whose sum is 0 and can be approached in a similar manner:
T = True
F = False
List = [T, T, T, F, F, F, T, F, T, F, T, T, T, T]
def max_toggle_subarray(arr):
start = 0
max_len = 0
for indexI, i in enumerate(arr):
length = 0
for indexJ, j in enumerate(arr[indexI:-1]):
curr = j
length += 1
predict = False if curr else True # Toggle and predict next
if predict == arr[indexI + indexJ + 1]:
if length >= max_len:
max_len = length
if indexJ == 0: start = max(start, indexI + indexJ) # We dont update start index on every iteration
end = indexI + indexJ + 1
else:
break
return start, end
# test array
print("Length of the longest subarray is starting at % d until % d" % max_toggle_subarray(List))
It might be possible to reduce time complexity to O(n) with a approach similar to - find the Largest Sum Contiguous Subarray
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.