Obtaining a TypeError in the following code (for Leetcode 46. Permutations) but can't see the issue

Viewed 29

I'm seeing the following error message in my solution to this Leetcode problem:

TypeError: object of type `NoneType' has no len()
    for j in range(len(elt)+1)
class Solution:

    def permute(self, nums: List[int]) -> List[List[int]]:
        
        ans = [[]]
    
        for i in range(len(nums)):
            temp = []
        
            for elt in ans:
                for j in range(len(elt)+1):
                    local = elt.copy()
                    t = local.insert(j, nums[i])
                    temp.append(t)
        
            ans = temp.copy()
    
        return ans
1 Answers

In the first iteration of you're loop, t = local.append(j,nums[i]) is None because insert does not have a return type. This is because .insert() is a mutating-method . By invoking temp.append(t) (with t = None), temp becomes the None type aswell. Since you're invoking ans = temp.copy(). ans is from type None now aswell hence you copied the None type.

When reaching the for loop (for elt in ans), elt becomes None. Therefore calling range(len(elt)+1) will crash, since the None type does not have a len() function.

You see that the element which became None is cascading until a Point where the program crashes. To handle such problems, iterate through the code step by step with a debugger and try to understand whats happening.

Related