I am trying to solve this problem:
Consider a simple number compression algorithm that works as follows:
111155522500 -> [('1', 4), ('5', 3), ('2', 2), ('5', 1), ('O', 2)]
The algorithm goes from left to right through each digit and returns a list of two-element tuples. Each tuple consists of a digit and the number of repetitions of a given digit until the next, different digit in the number is encountered.
Implement a function called compress () that compresses number as described above.
Examples:
[IN]: compress(lll)
[OUT]: [('l', 3)]
[IN]: conpress(1000000)
[OUT]: [('1', 1), ('O', 6)]
[IN]: conpress(10005000)
[OUT]: [('1', 1), ('O', 3), ('5', 1), ('O', 3)]
My code:
#para funcionar, é e necessário acrescentar um caracter que não existe ao final da string!
def compress(elemento):
elemento = str(elemento)
elemento = elemento +"§"# the code only works if I add some char not in the string
saida = []
#cont = 0
contagem = []
for index,ele in enumerate(elemento):
ele = str(ele)
#print(f"contagem: {contagem}")
if len(contagem) == 0 or ele in contagem:
contagem.append(ele)
if ele not in contagem :
saida.append((elemento[index-1],len(contagem)) )
contagem = []
contagem.append(ele)
return saida
compress('1000500011')
OUT:
[('1', 1), ('0', 3), ('5', 1), ('0', 3), ('1', 2)]
The problem: The code only works if I add some char not in the string as "§" Could someone help to solve this problem using the itertools built-in module and the groupby and without this modules?