Your code appears to be correct, but I have a few comments.
First, using the typing
, re
, and collections
modules is perhaps somewhat overkill for what you are trying to achieve. For small programs, it's best to make use of the built-in functions, and methods of build-in types, rather than to import modules, if possible. In particular, the string methods can be useful, and I've found the max
, map
, all
, and any
functions to be handy.
Second, while it wasn't specified what the function should do given an empty string, it would be prudent to handle this case. Currently, your code will throw an error; I think it would make sense to return the letter 'a'
.
Third, parts of your code are a bit difficult to read. In particular, this expression
(sorted(letters[frecuencies.index(max(frecuencies))])[0])
required some concentration to understand. I'm not sure how this could be improved. I think the problem is that by this point I've lost track of what the data-structures look like.
That's it for comments. To finish, here is an approach to the problem that I think would be considered quite Pythonic:
def most_frequent_letter(text):
"""Return the first letter of the alphabet that occurs jointly most
often in the given string. Case is ignored."""
alphabet = 'abcdefghijklmnopqrstuvwxyz'
return max(alphabet, key=text.lower().count)
The max
function will return the first maximal element in the list, where the value being maximised is the result of applying the function key
. So in this case, it will return the alphabetically first letter with the (joint) highest count in the lowercased text.
You could import the latin alphabet from the string
module, if you'd rather not type it out:
from string import ascii_lowercase
I would work on:
- becoming more familiar with the built-in methods and functions;
- writing code with the human reader in mind: try to keep the state of variables simple and self-evident. Ideally a line of code should be somewhat comprehensible in isolation without having to use working memory to mentally build up the state of the variables from the previous lines of the program.