Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Two solutions solution in Clear category for Group Equal consecutive by Goodester
"""
This solution contains two different solutions. Both solutions use itertools's groupby function.
"""
from itertools import groupby
from random import randint # randint is used to make both solutions called randomly.
def group_equal(els):
if randint(0, 1):
return group_equal_with_i(els)
return group_equal_with_g(els)
# ****** first solution ******
def group_equal_with_i(els):
unique_els = [i for i, g in groupby(els)]
index_in_els = 0
for i, current_element in enumerate(unique_els):
el_count = identical_consecutives(els, index_in_els)
unique_els[i] = [current_element] * el_count
index_in_els += el_count
return unique_els
def identical_consecutives(l, index=0):
el = l[index]
combo = 1
if index + 1 == len(l):
return 1
for second_el in l[index + 1:]:
if second_el == el:
combo += 1
else:
break
el = second_el
return combo
# ****** second solution ******
def group_equal_with_g(els):
return [list(g) for i, g in groupby(els)]
July 22, 2019
Comments: