-1

Say I have a list

[0, 1, 1, 3, 4, 5, 5, 1, 1, 1]

And output I would want for this list would be:

[0, 1, 3, 4, 5, 1]

My first thought was to do by sorting but I still want elements to remain as they are with the example of the ones above and in the same order. How would I do this?

I would prefer pseudocode, hints, or python please!

Jisoo Kim
  • 1
  • 2

4 Answers4

1

Lucky for you, this exact behavior is provided as a recipe in official Python docs at: https://docs.python.org/3/library/itertools.html

Example usage:

list(unique_justseen([0, 1, 1, 3, 4, 5, 5, 1, 1, 1]))
# => [0, 1, 3, 4, 5, 1]
Kache
  • 15,647
  • 12
  • 51
  • 79
0

When you don't want to use itertools:

lst = [0, 0, 1, 1, 3, 4, 5, 5, 1, 1, 1]

res = lst[0:1]
for item in lst:
    if res[-1] != item:
        res.append(item)

print(res) #=> [0, 1, 3, 4, 5, 1]
iGian
  • 11,023
  • 3
  • 21
  • 36
0

Use a generator and keep track of the previous value:

def unique_just_seen(iterable):
    previous = object()  # ensures the first value in the iterable is yielded
    for item in iterable:
        if item != previous:
            yield item
            previous = item

print(list(unique_just_seen([0, 1, 1, 3, 4, 5, 5, 1, 1, 1]))) # [0, 1, 3, 4, 5, 1]
Stuart
  • 9,597
  • 1
  • 21
  • 30
0

You could use zip fo compare items with their predecessor:

a = [0, 1, 1, 3, 4, 5, 5, 1, 1, 1]

b = a[:1] + [n for p,n in zip(a,a[1:]) if n!=p]

print(b)
[0, 1, 3, 4, 5, 1]
Alain T.
  • 40,517
  • 4
  • 31
  • 51