Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Two slightly different solutions solution in Clear category for Compress List by lucas.stonedrake
from typing import Iterable
#1st solution
def compress(items: list) -> Iterable:
result = [] # empty list
for i in range(len(items)):
if i == len(items) - 1: result += [items[i]] # always add the last entry
elif items[i] == items[i + 1]: continue #skip if the next entry is equal
else: result += [items[i]] # if neither above, add the entry
return result
# 2nd solution
def compress(items: list) -> Iterable:
result = [] # empty list
items += ['end'] #add a string as final entry
for i in range(len(items) - 1):
if items[i] == items[i + 1]: continue #skip if the next entry is equal
result += [items[i]] # if not, add the entry
return result
if __name__ == '__main__':
print("Example:")
print(list(compress([
5, 5, 5,
4, 5, 6,
6, 5, 5,
7, 8, 0,
0])))
# These "asserts" are used for self-checking and not for an auto-testing
assert list(compress([
5, 5, 5,
4, 5, 6,
6, 5, 5,
7, 8, 0,
0])) == [5, 4, 5, 6, 5, 7, 8, 0]
assert list(compress([1, 1, 1, 1, 2, 2, 2, 1, 1, 1])) == [1, 2, 1]
assert list(compress([7, 7])) == [7]
assert list(compress([])) == []
assert list(compress([1, 2, 3, 4])) == [1, 2, 3, 4]
assert list(compress([9, 9, 9, 9, 9, 9, 9])) == [9]
print("Coding complete? Click 'Check' to earn cool rewards!")
Oct. 29, 2020