1

i need to Write a function that takes a list of any size as an argument, and returns a list where all adjacent, equal elements have been reduced to a single element. For example [1, 2, 2, 3] would return as [1, 2, 3].

this needs to be done in python

yes this is class work

i'm not really sure on what to do for some of this.

def func1(x):

    list1 = x
    for i in x:
        for n in list1:
            if i == n:
               list2 = i
               print(list2)
    return;
a = [1,2,2,3]
func1(a)
John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • `[x for x, g in itertools.groupby(a)]` - but that’s likely not the kind of solution you are supposed to give. Tell us what specific problems you have, and we may be able to help you. But like this, your question is too unspecific. – poke Dec 08 '14 at 00:36
  • Duplicate of [Remove adjacent duplicate elements from a list](http://stackoverflow.com/q/3460161/2823755) – wwii Dec 08 '14 at 05:10

2 Answers2

3

Easy way

>>> from itertools import groupby
>>> a = [1,2,2,3]
>>> [k for k, v in groupby(a)]
[1, 2, 3]

If you had to do it by hand, just keep track of the last element you've seen and check it with each element you iterate over

def func1(x):
    result = []
    last = None
    for i in x:
        if i != last:
            result.append(i)
        last = i

    return result

a = [1,2,2,3]
print func1(a)

Caveat: if your list can contain Nones, then make last = object() (a completely unique object) instead of last = None since None could be the first element of the list and therefore get skipped.

jamylak
  • 128,818
  • 30
  • 231
  • 230
0

you can do in more pythonic using :

sorted(set(x))

ie:

a = [1,2,3,2,3]
a = sorted(set(a)
print(a)
nishparadox
  • 750
  • 6
  • 13