'lines repeat in List python
I need your help with the next problem, i need that a python recieve an string "EEEEDDSGES" and the output would by the sum of charactes that repeat in line, E 4 D 2 S 1 G 1 E 1 S 1
my code is the next,
diccionario = {}
contador = 0
for palabra in cadena:
if palabra.upper() in diccionario:
diccionario[palabra.upper()] += 1
else:
diccionario[palabra.upper()] = 1
for palabra in diccionario:
frecuencia = diccionario[palabra]
print(palabra, end=" ")
print(frecuencia) ```
the output is ,
S,S,d,f,s
S 1
S 2
d 3
f 4
s 5
Solution 1:[1]
Try itertools.groupby:
from itertools import groupby
s = "EEEEDDSGES"
for v, g in groupby(s):
print(v, sum(1 for _ in g))
Prints:
E 4
D 2
S 1
G 1
E 1
S 1
Solution 2:[2]
I'm sorry I don't understand what this language is, but I guess I understand what you are trying to do. I have changed the variable names for my comprehension.
s="EEEEDDSGES"
letters={}
for i in s:
i=i.upper()
try:
letters[i]+=1
except(KeyError):
letters.update({i:1})
for i in letters: print(f"{i}: {letters[i]}", end=" ")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andrej Kesely |
| Solution 2 | TheRavenSpectre |
