Author | Message |
---|---|
LuisFisher
Posts: 12
|
Posted 00:49 Sep 01, 2018 |
word_list = list("aaaaabbbbcccdde") # I don't think it is possible for the dictionary to refer to itself. # Therefore you must first create a dictionary of { key : 0 } pairs freq = {key : 0 for key in word_list} # and then using a function to wrap the expression def increment(key, dictionary): # so that you can call it and mutate the original dictionary {increment(key, freq) for key in word_list} # this will return {None} but will also mutate the original dictionary # value of freq should now be {'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0} |
rabbott
Posts: 1649
|
Posted 16:57 Sep 01, 2018 |
Right. The point is that the comprehension can't generate the dictionary. All you can do is use the comprehension to call a function that performs a side-effect that increments the dictionary. That's essentially what this solution did. You can get away with not initializing the dictionary. You can generate a list of the partial dictionaries.
{'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1} Last edited by rabbott at
17:17 Sep 01, 2018.
|
LuisFisher
Posts: 12
|
Posted 17:04 Sep 01, 2018 |
O(n) efficiency probably not as good as a normal loop |
rabbott
Posts: 1649
|
Posted 19:42 Sep 01, 2018 |
Not sure why you say that. How can you beat O(n)? |
LuisFisher
Posts: 12
|
Posted 03:37 Sep 02, 2018 |
What I mean is that its O(n) with 2 iterations as apposed to one with a single loop |
rabbott
Posts: 1649
|
Posted 09:40 Sep 02, 2018 |
OK. If you don't initialize the dictionary, there is only one traversal of the word list. |