我在优化 python 递归时遇到了问题。所以我想生成由 10 个元素组成的数组/列表中的所有可能性,每个元素都可以填充 0-9 数字。 所以,我决定在这种情况下使用递归,这里是:
routes = []
route = []
def generateRoutes(route, floor):
if floor >= 10:
routes.append(route)
else:
for channel in range(0, 10):
new_route=route.copy()
new_route.append(channel)
generateRoutes(new_route, floor + 1)
generateRoutes(route, 0)
我的代码需要永恒才能完成任务(更不用说占用大量内存)。我的问题是,有没有办法解决/优化我的代码? (除了递归,我也打开了其他方法)
编辑: 添加了有关函数如何调用的详细信息
最佳答案
itertools
模块已经提供了一个非递归的惰性解决方案:
>>> import itertools
>>> routes = itertools.product(range(10), repeat=10)
每个值都是在您遍历 routes
时按需生成的,而不是一次将所有 100 亿个值都存储在内存中。
>>> print(list(itertools.islice(routes, 20)))
[(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 0, 0, 0, 1), (0, 0, 0, 0, 0, 0, 0, 0, 0, 2), (0, 0, 0, 0, 0, 0, 0, 0, 0, 3), (0, 0, 0, 0, 0, 0, 0, 0, 0, 4), (0, 0, 0, 0, 0, 0, 0, 0, 0, 5), (0, 0, 0, 0, 0, 0, 0, 0, 0, 6), (0, 0, 0, 0, 0, 0, 0, 0, 0, 7), (0, 0, 0, 0, 0, 0, 0, 0, 0, 8), (0, 0, 0, 0, 0, 0, 0, 0, 0, 9), (0, 0, 0, 0, 0, 0, 0, 0, 1, 0), (0, 0, 0, 0, 0, 0, 0, 0, 1, 1), (0, 0, 0, 0, 0, 0, 0, 0, 1, 2), (0, 0, 0, 0, 0, 0, 0, 0, 1, 3), (0, 0, 0, 0, 0, 0, 0, 0, 1, 4), (0, 0, 0, 0, 0, 0, 0, 0, 1, 5), (0, 0, 0, 0, 0, 0, 0, 0, 1, 6), (0, 0, 0, 0, 0, 0, 0, 0, 1, 7), (0, 0, 0, 0, 0, 0, 0, 0, 1, 8), (0, 0, 0, 0, 0, 0, 0, 0, 1, 9)]
>>> print(list(itertools.islice(routes, 20)))
[(0, 0, 0, 0, 0, 0, 0, 0, 2, 0), (0, 0, 0, 0, 0, 0, 0, 0, 2, 1), (0, 0, 0, 0, 0, 0, 0, 0, 2, 2), (0, 0, 0, 0, 0, 0, 0, 0, 2, 3), (0, 0, 0, 0, 0, 0, 0, 0, 2, 4), (0, 0, 0, 0, 0, 0, 0, 0, 2, 5), (0, 0, 0, 0, 0, 0, 0, 0, 2, 6), (0, 0, 0, 0, 0, 0, 0, 0, 2, 7), (0, 0, 0, 0, 0, 0, 0, 0, 2, 8), (0, 0, 0, 0, 0, 0, 0, 0, 2, 9), (0, 0, 0, 0, 0, 0, 0, 0, 3, 0), (0, 0, 0, 0, 0, 0, 0, 0, 3, 1), (0, 0, 0, 0, 0, 0, 0, 0, 3, 2), (0, 0, 0, 0, 0, 0, 0, 0, 3, 3), (0, 0, 0, 0, 0, 0, 0, 0, 3, 4), (0, 0, 0, 0, 0, 0, 0, 0, 3, 5), (0, 0, 0, 0, 0, 0, 0, 0, 3, 6), (0, 0, 0, 0, 0, 0, 0, 0, 3, 7), (0, 0, 0, 0, 0, 0, 0, 0, 3, 8), (0, 0, 0, 0, 0, 0, 0, 0, 3, 9)]
关于python - 优化python中的递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55958764/