python - 在不创建列表的情况下以不同的顺序迭代 itertools.product

标签 python algorithm dynamic-programming combinatorics python-itertools

我有一个覆盖巨大搜索空间的iterable。我的计划不是让脚本终止,而是在一定时间后将其终止。

现在我需要这个空间的笛卡尔积并在那里搜索。 itertools.product 生成此订单:

>>> list(itertools.product(range(3), repeat=2))
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

虽然我想按对角线顺序搜索,类似于:

[(0, 0), (0, 1), (1, 0), (0, 2), (1, 1), (2, 0), (1, 2), (2, 1), (2, 2)]

sorted 使用一些返回元组元素总和的关键函数是我的常规方法,但是为了排序需要检查所有数据,这在我的情况下是不可行的。有办法做到这一点吗?

这个问题与this one非常相似,但答案中仍使用 sorted 。此外,我无法快速了解如何将 ordered_combinations 调整为 ordered_product

最佳答案

这个问题等同于询问如何使用给定的总和为总和的连续递增值创建所有 n 元组:

                  (0, 0),               sum == 0
              (0, 1), (1, 0),           sum == 1
        (0, 2), (1, 1), (2, 0),         sum == 2
             (1, 2), (2, 1),            sum == 3
                  (2, 2)                sum == 4

对于任何给定的行(具有给定的目标总和),子问题等同于动态规划问题 Number of ways to make change for amount NNumber of ways to add up to a sum S with N numbers .

另请参阅 Combinatorial Algorithms 中的评论唐纳德·高德纳 (Donald Knuth)。

关于python - 在不创建列表的情况下以不同的顺序迭代 itertools.product,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39917557/

相关文章:

algorithm - 用于存储预先计算的最大值的高效数据结构

algorithm - 使用递归在二叉树中根和节点之间的距离

python - 我如何提示用户键入正确的输入并重复使用该输入以进行循环?

python - IPython 7.0.1 中的多行编辑中断

python - Python 列表中的分层搜索

java - 如何将此二维 DP(动态程序)解决方案优化为一维?

python - Needleman-Wunsch 算法动态规划实现中的回溯

Windows 与 Linux 上的 Python 目录结构

c++ - 对一组数字进行排列,然后将它们变成一个 int

algorithm - 坚持 DFS/BFS 任务(USACO 银牌)