The below code worked perfectly fine.
def perm(cur):
avail = [i for i in nums if not i in cur]
if len(avail) == 0:
res.append(cur.copy())
return
for i in avail:
cur.append(i)
perm(cur)
cur.pop()
perm([])
return res
However, the below one returned error
def perm(cur):
avail = [i for i in nums if not i in cur]
if len(avail) == 0:
res.append(cur.copy())
return
for i in avail:
perm(cur.append(i))
cur.pop()
perm([])
return res
TypeError: argument of type 'NoneType' is not iterable
avail = [i for i in nums if not i in cur]
Line 5 in <listcomp> (Solution.py)
avail = [i for i in nums if not i in cur]
Line 5 in perm (Solution.py)
perm(cur.append(i))
Line 12 in perm (Solution.py)
perm([])
Line 15 in permute (Solution.py)
ret = Solution().permute(param_1)
Line 38 in _driver (Solution.py)
_driver()
Line 49 in <module> (Solution.py)
I'm trying to understand the logic behind this.
I'm not sure of the difference between both ways of parameter passing.
CodePudding user response:
.append returns None.
def perm(cur):
avail = [i for i in nums if not i in cur]
if len(avail) == 0:
res.append(cur.copy())
return
for i in avail:
// Here .append(i) does not return anything so the cur you are passing in the perm funcion is None
perm(cur.append(i))
cur.pop()
perm([])
return res
CodePudding user response:
Function cur.append(i) doesn't return anything. It only appends i to cur list.
Then when you call perm with it as an argument, you basically calling perm(None), which is not iterable. Therefore [i for i in nums if not i in cur] fails.
