In my program, when a user inputs a word, it needs to be checked for letters that are the same.
For example, in string = "hello"
, hello has 2 'l's. How can i check for this in a python program?
In my program, when a user inputs a word, it needs to be checked for letters that are the same.
For example, in string = "hello"
, hello has 2 'l's. How can i check for this in a python program?
Use a Counter
object to count characters, returning those that have counts over 1.
from collections import Counter
def get_duplicates(string):
c = Counter(string)
return [(k, v) for k, v in c.items() if v > 1]
In [482]: get_duplicates('hello')
Out[482]: [('l', 2)]
In [483]: get_duplicates('helloooo')
Out[483]: [('l', 2), ('o', 4)]
You can accomplish this with
d = defaultdict(int)
def get_dupl(some_string):
# iterate over characters is some_string
for item in some_string:
d[item] += 1
# select all characters with count > 1
return dict(filter(lambda x: x[1]>1, d.items()))
print(get_dupl('hellooooo'))
which yields
{'l': 2, 'o': 5}