Skip to content Skip to sidebar Skip to footer

Invert Edge Values In Python Boolean List

I have a list of booleans like l = [False, False, False, True, True, True, False, False, True, False, False] and want to invert every edge value that is False like [True, True, Tr

Solution 1:

Possibly there's some clever one-line solution for this, but until someone comes up with it, here's a way to do it with old fashioned iteration:

seq = [False, False, False, True, True, True, False, False, True, False, False]

for i in range(len(seq)):
    if seq[i]:
        break
    seq[i] = True

for i in range(len(seq)-1, -1, -1):
    if seq[i]:
        break
    seq[i] = True

print(seq)

Result:

[True, True, True, True, True, True, False, False, True, True, True]

Solution 2:

You can use a couple of generator expressions and then NumPy for vectorised slicing.

The idea is to calculate the first index from the beginning and end of the list separately where a value is True. Then use efficient NumPy slicing to update the relevant elements.

L = [False, False, False, True, True, True, False, False, True, False, False]

idx1 = next(i for i, j in enumerate(L) if j)
idx2 = next(i for i, j in enumerate(L[::-1]) if j)

print(idx1, idx2)  # 3 2

import numpy as np

A = np.array(L)
A[:idx1] = True
A[len(A)-idx2:] = True

print(A)

array([ True,  True,  True,  True,  True,  True, False, False,  True,
        True,  True], dtype=bool)

Solution 3:

I suggest you the following simple code:

myList = [False, False, False, True, True, True, False, False, True, False, False]

tempList = myList[:]

# Iterate from the beginning (and invert) until the element differs from the first one
for i,v in enumerate(tempList):
    if v == tempList[0]: myList[i] = not v
    else:                break

# Iterate from the end (and invert) until the element differs from the last one
for i,v in reversed(list(enumerate(tempList))):
    if v == tempList[-1]: myList[i] = not v
    else:                 break

print(myList)
# [True, True, True, True, True, True, False, False, True, True, True]

Solution 4:

Based on the logic of the other answers, here is a solution using numpy.where.

import numpy as np

l = [False, False, False, True, True, True, False, False, True, False, False]

l = np.array(l)
ind = np.where(l)[0]
first, last = ind[0], ind[-1]

l[:first] = True
l[last + 1:] = True

print(l)

This was inspired by the answer from NPE in https://stackoverflow.com/a/9537766/2611995.


Post a Comment for "Invert Edge Values In Python Boolean List"