In: Computer Science
In Python,
Given a list of numbers, return a list where all adjacent ==
elements have been reduced to a single element, so
[1,2,2,3,3,2,2,4] returns [1,2,3,2,4]. You may create a new list or
modify the passed in list (set function does not work in this
case).
list1 = [1,2,2,3,3,2,2,4]
print list1
list2 = []
for i in range(len(list1)):
if i != len(list1)-1 and list1[i] != list1[i+1]:
list2.append(list1[i])
if i == len(list1)-1:
if list1[i] != list1[i-1]:
list2.append(list1[i])
print list2
Output:
sh-4.3$ python main.py
[1, 2, 2, 3, 3, 2, 2, 4]
[1, 2, 3, 2, 4]