Author | Message |
---|---|
rabbott
Posts: 1649
|
Posted 12:20 Aug 26, 2018 |
Yesterday Luis Fisher said he thought it was possible to generate a word count using a list comprehension. I was skeptical. Luis was right, but as far as I can tell, the only way to do it is to rely on side effects -- which is not good programming style.
When run, the list comprehension generates a list of the As far as the list comprehension is concerned, the job of Last edited by rabbott at
13:09 Aug 26, 2018.
|
jungsoolim
Posts: 38
|
Posted 22:17 Aug 26, 2018 |
Can we put list comprehension in the body of function? def count_word_freq(words): words = ['a', 'ab', 'a', 'ad', 'sdfsf', 'a', 'sdfsf', 'ab'] If so, wouldn't this function be less efficient that the function using a loop? (i.e.) def word_frequencies(mylist): print(word_frequencies(words)) |
rabbott
Posts: 1649
|
Posted 22:51 Aug 26, 2018 |
Definitely less efficient. It's O(n^2) since you have to scan words for each word. Even if you did something like what Jay did, it's still O(n^2).
Assuming dictionary access is O(1), the side-effect version and the for-loop version are both O(n). |