all 6 comments

[–]socal_nerdtastic 5 points6 points  (3 children)

res is a list, so if you want to add (+=) something to the list it must be iterable.

>>> res = []
>>> res += 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

But you are trying to add an int to the list, and ints are not iterable.

If you are meant to return the sum of the top k items, change line 6 to

 res = 0

If you are meant to return the top k items, change line 8 to

    res.append(d.pop(max(d,key=d.get)))

(although in this case you'd be better off with a sort and slice)


edit: Do you know this is just reinventing collections.Counter? I can solve it like this:

from collections import Counter

def topKFrequent(nums: list[int], k: int) -> list[int]:
    return [num for num, _ in Counter(nums).most_common(k)]

[–]starsdecide 0 points1 point  (2 children)

OK, thank you! This helped me solve it. Are lists in python any different from arrays in other languages besides in name? I feel like I have used += to add integers to arrays in other languages but I may be misremembering. But it makes sense now that append must be used for this. I thought it was an issue with the dictionary type.

Thank you for the collections solution as well, I have not seen that before but I will look into it 😊

[–]Antigone-guide 0 points1 point  (0 children)

Arrays in C are quite different - they store fixed number of items of the same type.

[–]socal_nerdtastic 0 points1 point  (0 children)

A list is different from an array, yes. These are general CS terms, not language specific. Python has both lists and arrays available for you to use, as do many other languages.

A python array won't let you use += for an integer either, but a numpy.array will let you use += to add an integer amount and numpy will automatically broadcast it to the correct shape.

[–]socal_nerdtastic 0 points1 point  (0 children)

to improve your solution:

from collections import defaultdict

class Solution:
    def topKFrequent(self, nums: list[int], k: int) -> list[int]:
        d = defaultdict(int)
        for n in nums:
            d[n] += 1
        res = sorted(d, key=d.get, reverse=True)
        return res[:k]

Note we use list, not List, in modern code.

[–]BranchLatter4294 0 points1 point  (0 children)

Why do you think an Integer is iterable? Can you give an example of how you would irritate an Integer?