A cleaner / shorter way to solve this problem?

This exercise is taken from the Google Python Class :

D. Given a list of numbers, return a list where all adjacent elements == were reduced to one element, so [1, 2, 2, 3] returns [1, 2, 3]. You can create a new list or modify a past list.

Here is my solution:

def remove_adjacent(nums):
  if not nums:
    return nums

  list = [nums[0]]

  for num in nums[1:]:
    if num != list[-1]:
        list.append(num)

  return list

But it looks more like a C program than a Python script, and I feel it can be made much more elegant.

EDIT

So, [1, 2, 2, 3]must give [1, 2, 3]and [1, 2, 3, 3, 2]must give[1, 2, 3, 2]

+3
source share
7 answers

In itertools , which works here:

import itertools
[key for key,seq in itertools.groupby([1,1,1,2,2,3,4,4])]

You can also write a generator:

def remove_adjacent(items):
    # iterate the items
    it = iter(items)
    # get the first one
    last = next(it)
    # yield it in any case
    yield last
    for current in it:
        # if the next item is different yield it
        if current != last:
            yield current
            last = current
        # else: its a duplicate, do nothing with it

print list(remove_adjacent([1,1,1,2,2,3,4,4]))
+9

itertools .

import itertools

def remove_adjacent(lst):
  i = iter(lst)
  yield next(i)
  for x, y in itertools.izip(lst, i):
    if x != y:
      yield y


L = [1, 2, 2, 3]

print list(remove_adjacent(L))
+3

, . , . [1:].

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

b = [ i for i,j in zip(a,a[1:] + [None]) if not i == j ]
+3

, - +[None], ...

>>> mylist=[1,2,2,3,3,3,3,4,5,5,5]
>>> [x for x, y in zip(mylist, mylist[1:]+[None]) if x != y]
[1, 2, 3, 4, 5]

, , itertools.groupby(), THC4K, .

+2
>>> def collapse( data ):
...  return list(sorted(set(data)))
... 
>>> collapse([1,2,2,3])
[1, 2, 3]

:

>>> def remove_adjacent( data ):
...     last = None
...     for datum in data:
...         if datum != last:
...             last = datum
...             yield datum
...             
>>> list( remove_adjacent( [1,2,2,3,2] ) )
[1, 2, 3, 2]
+1

; , . Python 3 functools.

def remove_adjacent(nums):
  def maybe_append(l, x):
    return l + ([] if len(l) and l[-1] == x else [x])
  return reduce(maybe_append, nums, [])
0
source

Source: https://habr.com/ru/post/1774567/


All Articles