3 ms·
My solution: lines = [line for line in open("bible.txt")] words = [word for line in lines for word in line.split()] counts = {word:0 for word in wo
by wyager 13y ago
My solution:
lines = [line for line in open("bible.txt")]
words = [word for line in lines for word in line.split()]
counts = {word:0 for word in words}
for word in words:
counts[word] += 1
No imports needed. Linear time. A bit inefficient in the dictionary comprehension, but easy to read.
The "lines=" and "words=" can be compressed into one line, but I figure this is a bit easier to read for people who aren't familiar with nested list comprehensions.
- burntsushi 13y ago> A bit inefficient in the dictionary comprehension, but easy to read. If you allow one import to sneak in, I think a `defaultdict` would do nicely. :-)
- ajayjain 13y agoI'm not too familiar with Python, but this is case sensitive unlike benhoyt's examples. Would this be case insensitive? lines = [line for line in open("bible.txt")] words = [word.lower() for line in lines for word in line.split()] counts = {word:0 for word in words} for word in words: counts[word] += 1
- gejjaxxita 13y agoyes!