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 (eg 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)
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())
.
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.