简体   繁体   中英

Find the most common letter in a word; alphabetically

program input is a string. From this string I would want the most common letter. In the case that there are multiple letters with the same frequency, I would return the one that comes first in the latin alphabet

code:

def most_Wanted(text="Hello Oman"):
    lst = [x for x in text.replace(" ","").lower() if x.isalpha]
    count = {}
    for letter in lst:
        if letter in count:
            count[letter] += 1
        else:
            count[letter] = 1
    count = list(count.items())
    sorted(count, key=lambda x: (-x[1],x[0]))
    print(count[0][0])

expected:

l #though o and l appear 3 times, l is before o in the latin alphabet

output:

h #there seems to be an error in the sorting as the first pair of tuples in the list always seems to be the first letter of the text?

Any suggestions to spruce up the code would be fine, though I would prefer not using modules at the moment so I can learn the core python. Thank you:)

The main issue is that sorted returns a new list, it is not in-place.

You should either reassign its return value, or use .sort() :

count = sorted(count, key=lambda x: (-x[1],x[0]))

or

count.sort(key=lambda x: (-x[1],x[0]))


There is also an issue in the line

lst = [x for x in text.replace(" ","").lower() if x.isalpha]

if x.isalpha is always going to return True since it is only referencing the function instead of actually calling it. It should be changed to

lst = [x for x in text.replace(" ","").lower() if x.isalpha()]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM