tags:

views:

84

answers:

4

Here's what I got:

# D. Given a list of numbers, return a list where
# all adjacent == elements have been reduced to a single element,
# so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or
# modify the passed in list.
def remove_adjacent(nums):
  for number in nums:
    numberHolder = number

  # +++your code here+++
  return

I'm kind of stuck here. What can I do?

A: 

Compare the current number with the previous number. If it's not the same then append it to a new list. Then save it so that the next loop can use it.

Ignacio Vazquez-Abrams
+4  A: 
>>> import itertools
>>> [i[0] for i in itertools.groupby([1,2,2,3,3,3,2,2])]
[1, 2, 3, 2]

Or:

>>> def f(l):
...     r = []
...     last = None
...     for i in l:
...         if i != last:
...             r.append(i)
...             last = i
...     return r        
... 
>>> f([1,2,2,3,3,3,4,4,2,2])
[1, 2, 3, 4, 2]
Max Shawabkeh
A: 

try this:

def remove_adjacent(nums):
  removed_list = []
  numberHolder = None
  for number in nums:
    if number != numberHolder:
       removed_list.append(number)
       numberHolder = number
  return removed_list
systempuntoout
A: 

This is another solution based on filter(). It's not just for adyacent and equal elements but for equal elements:

def remove_repeated_items(collection):
   uniques = []
   def not_already_added(item):
      if item in uniques:
         return False
      else:
         uniques.append(item)
         return True
   return filter(not_already_added, collection)

And then:

repeated = [1,2,2,3,3]
print remove_repeated_items(repeated)
jaimeirurzun