0

I'm trying to create a "most wanted letter" program which takes a string as input and output should be the most repeated letter in that string. Currently, I can't figure out how to create a dictionary (e.g. dict.items():[("a", 2), ("b", 5)...]).

def checkio(text: str) -> str:

    input_text = text
    lowercase_input = str.lower(input_text)
    x = list('')
    for i in lowercase_input:
        x.append(i)
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149

2 Answers2

2

You may use collections.Counter to do it directly.
Consider the following example.

from collections import Counter

s = "example"
c = Counter(s)
# Counter({'e': 2, 'x': 1, 'a': 1, 'm': 1, 'p': 1, 'l': 1})

You can also get the most common letter with

c.most_common(1) #[('e', 2)]

Note also that in case the input is a sentence you may want to avoid whitespace and in this case you can do something like s = str.join("",s.split()).

abc
  • 11,579
  • 2
  • 26
  • 51
  • Great thank you, is it also possible to do this without importing counter? I'm doing some online Python game and it prohibits me from importing counter. – Patrick Wyss Sep 09 '18 at 15:23
  • in this case just create a dict and for each letter you check if it exists as a key. If so you increase the counter, otherwise you add the key with value 1. – abc Sep 09 '18 at 15:25
0

Without any imports, you can use a regular dictionary.

def checkio(text: str) -> str:
    lowercase_input = text.lower()
    x = {}
    for i in lowercase_input:
        x[i] = x.get(i, 0) + 1
    return max(x.items(), key=lambda x: x[1])

key, value = checkio('asdafsasaaaa')  # ('a', 7)

Explanation

dict.get has an optional second parameter, which we set to 0. This means if the key does not exist in the dictionary x.get(i, 0) will return 0. max has an optional key parameter which accepts an anonymous (lambda) function. Since dict.items() returns an iterable of (key, value) pairs, we can calculate the maximum by looking at the value component (1st index).

Performance

This is inefficient versus Counter + most_common as shown by @abc. Specifically, most_common uses heapq to reduce time complexity. See also Python collections.Counter: most_common complexity.

jpp
  • 159,742
  • 34
  • 281
  • 339