5 ms·
Actually that's not 'highly proficient'. This is: def read_words(words_file): return [word for line in open(words_file, 'r') for word in line.split
by yohanatan 13y ago
Actually that's not 'highly proficient'. This is:
def read_words(words_file):
return [word for line in open(words_file, 'r') for word in line.split()]
len(set(read_words('test.txt')))
- pwang 13y agolen(set(open("test.txt").read().split()))
- wyager 13y agoOh, I like this one. Not quite what OP asked, but very clean.
- deleted 13y ago[deleted]
- mbq 13y agoR version for comparison (; length(unique(scan('test.txt',character(),sep=" ")))
- eeshanC 13y agoVery clean. 1 small change to make it count of frequencies- table(scan('test.txt',character(),sep=" "))
- bnolsen 13y agosmashing tons of crap together isn't necessarily "highly proficient". In some cases it makes things harder to read and/or harder to maintain and many times certainly harder to edit.
- eeshanC 13y agoTrue that. But there is also another side to this story, where such nested calls translates naturally to what we are thinking, i.e. length(unique(text)) comes from the thought "How many(length()) unique (unique()) words are there in this text(text)?"
- agumonkey 13y agoDon't know when set comprehensions and resource handlers were introduced so that might not run everywhere def read_words(words_file): with open(words_file, 'r') as f: return {word for line in f for word in line.split()}
- jessaustin 13y agoGP asked for counts, not uniques.
- deleted 13y ago[deleted]
- yohanatan 13y agoOops, you're right. words = open("test.txt").read().split() [(k, len(list(g))) for k, g in groupby(words, lambda x: x)]
- leephillips 13y agoDoesn't that require an "import itertools"?
- yohanatan 13y agoYup. Sorry.
- yohanatan 13y agoOops, should have been this: words = open("test.txt").read().split() [(k, len(list(g))) for k, g in groupby(words, lambda x: x)]
- hnriot 13y agoexcept that's wrong, all you're doing is counting the number of unique words, and you didn't even consider Foo and foo as the same in your example. Part of proficiency is understanding the problem.