0

I got an error in the following function which says that 'NoneType' object is not iterable. The print(max()) function works just fine when I put it outside the loop so why doesn't it work here?

def minSetSize(self, arr: List[int]) -> int:
        target=len(arr)/2
        sum=0
        res=[]
        hash={x:arr.count(x) for x in arr}
        freq=list(hash.values())
        while (sum<target):
            sum+=max(freq) #error thrown here
            res.append(max(freq))
            freq=freq.remove(max(freq))
        return len(res)
CorvusRex
  • 79
  • 9
  • Does this answer your question? [Why does newList = list.remove(x) return None?](https://stackoverflow.com/questions/34101007/why-does-newlist-list-removex-return-none) – kaya3 Mar 04 '20 at 11:17

2 Answers2

0

freq is a list before the loop, then on the first iteration of the loop you call

        while (sum<target):
            sum+=max(freq) #error thrown here
            res.append(max(freq))
            freq=freq.remove(max(freq))

The remove method of a list always returns None. So you essentially store this None as the value for freq. so now you have changed freq from a list to None. So on the next iteration you get the error.

Just call freq.remove(max(freq)) on its own dont try to allocate the result to freq

        while (sum<target):
            sum+=max(freq) #error thrown here
            res.append(max(freq))
            freq.remove(max(freq))
Chris Doyle
  • 10,703
  • 2
  • 23
  • 42
0

Please check out this. You had an error in freq=freq.remove(max(freq)) No need to assign back to the same freq variable. Because id of that list objects remains the same until scripts run.

def minSetSize(arr) -> int:
    target = len(arr) / 2
    sum = 0
    res = []
    hash_dict = {x: arr.count(x) for x in arr}
    freq = list(hash_dict.values())
    while sum < target:
        sum += max(freq)
        res.append(max(freq))
        freq.remove(max(freq)) # error was here  here
    return len(res)

print(minSetSize([1,2,5,7,3, 53]))
krishna
  • 1,029
  • 6
  • 12