Created
January 9, 2014 22:01
-
-
Save cameronp98/8342869 to your computer and use it in GitHub Desktop.
Sorting by letter frequency in Python using defaultdict
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import defaultdict | |
def letter_frequency(text): | |
freq = defaultdict(int) | |
for char in text.replace("\n", ""): | |
freq[char] += 1 | |
return freq | |
def main(): | |
text = "The quick brown fox jumps over the lazy dog" | |
freq = letter_frequency(text.lower()) | |
print(sorted(freq.items(), key=lambda i: i[1], reverse=True)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment