-1
i/p 1:
test_list = [1, 1, 3, 4, 4, 4, 5,6, 6, 7, 8, 8, 6]
o/p 
[3, 5, 7, 6]

Exp: Since (1 1), (4 4 4) (6 6) (8 8) are in consecutive occurrence so resultant list has no addition of 6 but for last occurrence where 8, 6 are not in multiple consecutive occurrence so 6 is valid in last iteration

i/p 2:
test_list = [1, 1, 3, 4, 4, 4, 5,4,6, 6, 7, 8, 8, 6]
o/p
[3, 5,4, 7, 6]
** like wise for 2nd input  4,4,4 is not valid but 5,4 is valid

Any suggestion for the expected o/p? (I am looking for bit elaborated algorithm)

  • 1
    Does this code work? Do you have any problems with it? 'Is my code good' is off-topic for SO. If you're looking for open-ended feedback, the correct approach would be deleting the question from here and posting on codereview.stackoverflow.com – JeffUK Jun 15 '21 at 12:42
  • @JeffUK You probably mean https://codereview.stackexchange.com. –  Jun 15 '21 at 12:47

2 Answers2

2

You can use itertools.groupby to group adjacent identical values, then only keep values that have group length of 1.

>>> from itertools import groupby
>>> test_list = [1, 1, 3, 4, 4, 4, 5,6, 6, 7, 8, 8, 6]
>>> [k for k, g in groupby(test_list) if len(list(g)) == 1]
[3, 5, 7, 6]
>>> test_list = [1, 1, 3, 4, 4, 4, 5,4,6, 6, 7, 8, 8, 6]
>>> [k for k, g in groupby(test_list) if len(list(g)) == 1]
[3, 5, 4, 7, 6]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0

First of all, you need to know that increasing i in your for loop does not change the value of i. You can check it by runin this code:

for i in range(5):
    print(i)
    i = 2

This code will print 0 1 2 3 4 not 0 2 2 2 2 as you might think.

Going back to your question. I would use groupby from itertools, but since you specified you don't want to use it, I would do something like this:

if test_list[0] != test_list[1]:  # <-- check if first element should belong to result
    res_list.append(test_list[0])  

for i in range(len(test_list[1:-1])):  # Here we use input list, but without first and last element.
    if test_list[i+1] == test_list[i+2] or test_list[i+1] == test_list[i]:
        continue
    else:
        res_list.append(test_list[i+1])

if test_list[-2] != test_list[-1]:  # <-- check if last element should belong to result
    res_list.append(test_list[-1])
Relandom
  • 1,029
  • 2
  • 9
  • 16