Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Detection of change in consecutive list elements isn't working

My goal is to print the value of the elements in the list where the consecutive elements are changed. For instance, if the given input is 1 1 1 3 3 3 2 then the output should be [1,3,3,2], because in the input you can see that the value of 1 is changing to 3, so 1 and 3 should be appended to the list, and also the value of 3 is changing to 2, so 3 and 2 should also be appended to the list.

The required output is [1,3,3,2].
However, my code is returning only [1,3] but not [3,2]. I don’t understand why?

for t in range(int(input())):
    n = int(input())
    a = list(map(int,input().split()))[:n]
    l=[]
    if a.count(a[0])==len(a):
        print("0")
    else:
        for i in a:
            if a[i] != a[i+1]:
                print(i)
                l.extend((a[i],a[i+1]))
        print(l)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Code:

a = [1, 1, 1, 3, 3, 3, 2]
output = []
for i in range(len(a) - 1):
    if a[i] != a[i + 1]:
        output.append(a[i])
        output.append(a[i+1])

print(output)

Output:

[1, 3, 3, 2]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading