向递归函数传递参数的不同类型
Different types of passing parameters to a recursive function
下面的代码工作得很好。
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
然而,下面的返回错误
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)
我正在尝试理解这背后的逻辑。
我不确定这两种参数传递方式之间的区别。
.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
函数 cur.append(i)
没有 return 任何东西。它仅将 i
附加到 cur
列表。
然后当你用它作为参数调用 perm
时,你基本上调用了 perm(None)
,这是不可迭代的。因此 [i for i in nums if not i in cur]
失败。
下面的代码工作得很好。
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
然而,下面的返回错误
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)
我正在尝试理解这背后的逻辑。
我不确定这两种参数传递方式之间的区别。
.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
函数 cur.append(i)
没有 return 任何东西。它仅将 i
附加到 cur
列表。
然后当你用它作为参数调用 perm
时,你基本上调用了 perm(None)
,这是不可迭代的。因此 [i for i in nums if not i in cur]
失败。