Good job so far, your code appears to be correct. I have a few comments, mostly on style.
First, using the
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
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
Third, parts of your code are a bit difficult to read. In particular, this expression
required some concentration to understand. I'm not sure how this could be improved. I think the problem is that by this point, with the re-jigging and type conversions, 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:
"""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)
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
Good job on producing a correct solution to a tricky problem. I would work on:
- becoming more familiar with the built-in methods and functions;
- taking a step back to consider whether there is a more elegant way to approach the problem rather than ploughing on; and
- 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 involved from the previous lines of the program).