Home > Enterprise >  Python List: locating starting and ending position of perticular value
Python List: locating starting and ending position of perticular value

Time:12-20

In my process, I am getting 1 or 0 as a result which I am storing in the List. For ex:

Input Data: 
TestRun = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 ......]
Result = [0,0,0,0,1,1,1,0,0,0,1,1,1,.................]

Now, during this endless process, I would like to store the starting and ending positions of 1 or 0.

Expected Output Result: 
StartingPosZero = [1, 8,...]
EndingPosZero = [4, 10, .....]
StartingPosOne = [5, 11,.....]
EndingPosOne= [7, 13,....]

Is it possible that someone can help me to solve this problem without using any standard functions?

CodePudding user response:

Not sure what the purpose of this code is meant to be for, since in Python indexing starts from 0. This code definitely is repetitive, but at least it does the job. Regardless,

result = [0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1]
StartingPosZero, EndingPosZero, StartingPosOne, EndingPosOne = [], [], [], []

startingBit = result[0]
StartingPosOne.append(1) if startingBit == 0 else StartingPosZero.append(1)

for i in range(len(result)-1):
    currentBit = result[i]
    nextBit = result[i 1]
    if currentBit != nextBit:
        if currentBit != 0:
            EndingPosZero.append(i 1)
            StartingPosOne.append(i 2)
        else:
            EndingPosOne.append(i 1)
            StartingPosZero.append(i 2)

endingBit = result[-1]
EndingPosOne.append(len(result)) if startingBit != 0 else EndingPosZero.append(len(result))

print(StartingPosZero)
print(EndingPosZero)
print(StartingPosOne) 
print(EndingPosOne)

CodePudding user response:

With list comprehension:

TestRun = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
Result = [0,0,0,0,1,1,1,0,0,0,1,1,1]

Result.insert(0,99)
Result.insert(len(Result),99)

StartingPosZeros=[ x 1 for x in range(len(Result)-1) if Result[x 1] != Result[x] if Result[x 1]==0]
EndingPosZeros=[ x for x in range(len(Result)-1) if Result[x 1] != Result[x] if Result[x]==0]    
StartPosOnes=[ x 1 for x in range(len(Result)-1) if Result[x 1] != Result[x] if Result[x 1]==1]    
EndingPosOnes=[ x for x in range(len(Result)-1) if Result[x 1] != Result[x] if Result[x]==1]

print(StartingPosZeros)
print(EndingPosZeros)
print(StartingPosOnes) 
print(EndingPosOnes)

output:

[1, 8]
[4, 10]
[5, 11]
[7, 13]
  • Related