python - 将作为响应返回的静态变量放在递归块中
问题描述
我写了这样一个递归解决方案来合并两个排序列表
res = []
def merge(l1, l2):
"""
:type l1:List
:rtype res: List[int]
"""
#Base
#Case1: Both are empty Case2 and Case3: One of them is empty
if len(l1) * len(l2) == 0:
res = l1 + l2
return res
#Case 4
if len(l1) = 1 and len(l2) = 1:
if l1[0] <= l2[0]:
res.append(l1.pop(0)) #decrement
else:
res.append(l2.pop(0))
return res
#Recur Case
if len(l1) > 1 and len(l2) > 1:
return merge(l1, l2)
我关心的问题是静态变量res
应该在功能模块之外定义。res=[]
在这种情况下,我可能会在其他地方重复使用时忘记复制。模块merge
不是 100% 独立的。
所以我把它放在里面
def merge(l1, l2):
"""
:type l1:List
:rtype res: List[int]
"""
global res
try:
print(res)
except NameError:
res = []
...
解法很繁琐,
怎么能简明扼要地解题呢?
解决方案
您可以将res
作为参数放入函数中。由于它是可变的,它也应该通过引用传递,并且不会占用更多内存(递归本身除外)。
或者您可以将它包装在一个类中并使用 访问它self.res
,但这将提供与在递归中传递变量相同的逻辑,如下所示。
def merge(l1, l2, res=None):
"""
:type l1:List
:rtype res: List[int]
"""
# Default parameter, read more here on why not to initialise as list
# https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments
if res is None:
res = []
#Base
#Case1: Both are empty Case2 and Case3: One of them is empty
if len(l1) * len(l2) == 0:
res = l1 + l2
return res
#Case 4
if len(l1) = 1 and len(l2) = 1:
if l1[0] <= l2[0]:
res.append(l1.pop(0)) #decrement
else:
res.append(l2.pop(0))
return res
#Recur Case
if len(l1) > 1 and len(l2) > 1:
return merge(l1, l2, res)
推荐阅读
- python - 如何在 Raspberry Pi 中更改默认 python 版本
- javascript - 需要用不同的颜色显示每个字符
- python-click - Python单击以重新启动命令并清除所有参数
- jquery - 用于调用 Cloudify Rest API 的 Ajax 代码响应错误“未定义”
- html - 粘性顶部在整个页面中不起作用。只为标题工作
- java - 如何使用 gdal docker 映像创建软件并使用 Java GUI 运行它?
- regex - 用于检测端口号的 Yara 正则表达式不起作用
- amazon-web-services - 什么角色允许 EC2 用户运行 aws ec2 authorize-security-group-egress
- javascript - 如何在 React Navigation 5 中将自定义道具传递给抽屉屏幕?
- javascript - 检查 JavaScript 中是否存在通知