0

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?

Nogarde
  • 3
  • 2
  • Use a counter, and find all characters which have count over 1? – cs95 Oct 16 '17 at 22:52
  • Welcome to Stack Overflow. What have you already tried yourself to do this? Please review [How much research effort is expected?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users). Stack Overflow is not a coding service. You are expected to research your issue and make a good attempt to write the code yourself before posting. If you get stuck on something specific, come back and include a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and a summary of what you tried, so we can help. – S4NDM4N Oct 17 '17 at 03:39

2 Answers2

1

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)]
cs95
  • 379,657
  • 97
  • 704
  • 746
0

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}
00sdf0
  • 148
  • 1
  • 8