【问题标题】:How to create a list of all possible lists satisfying a certain condition?如何创建满足特定条件的所有可能列表的列表?
【发布时间】:2017-09-27 05:47:21
【问题描述】:

我目前正在尝试解决欧拉问题 18 (https://projecteuler.net/problem=18),使用“蛮力”方法检查所有可能的路径。到目前为止,我一直在尝试更小的“模型”三角形。 我正在使用列表推导来创建一个列表列表,其中内部列表将包含该行的索引,例如:

lst = [[a,b,c,d] for a in [0] for b in [0,1] for c in [0,1,2] for d in 
[0,1,2,3] if b == a or b == a + 1 if c == b or c == b + 1 if d == c or d == 
c + 1]

这给了我想要的列表列表,即:

[[0,0,0,0],[0,0,0,1],[0,0,1,1],[0,0,1,2],[0,1,1,1],[0,1,1,2],[0,1,2,2],
[0,1,2,3]]

注意:if 条件确保它只移动到三角形下一行中的相邻数字,所以

lst[i][j] = lst[i][j-1] or lst[i][j] = lst[i][j]-1

在我达到这一点之后,我打算对每个内部列表,我会采用与这些索引相关的数字(所以 [0,0,0,0] 将是 3,7,2,8)并对它们求和,这样就可以得到所有可能的和,然后取其中的最大值。

问题是,如果我将其放大到大三角形,我的列表理解中将有 15 个 'for's 和 'if's。似乎必须有一个更简单的方法!我对 Python 还很陌生,所以希望有一些我可以利用的明显功能,我到目前为止还没有意识到!

【问题讨论】:

  • 您可能想查看dynamic programming 算法以提高计算效率。
  • 我对动态编程进行了一些研究,但我想先尝试使用蛮力解决它。

标签: python list list-comprehension


【解决方案1】:

多么有趣的问题!这是一个简单的蛮力方法,注意使用 itertools 生成所有组合,然后排除连续行索引差异超过一个的所有情况。

import itertools
import numpy as np

# Here is the input triangle
tri = np.array([[3],[7,4],[2,4,6],[8,5,9,3]])
indices = np.array([range(len(i)) for i in tri])

# Generate all the possible combinations
indexCombs = list(itertools.product(*indices))

# Generate the difference between indices in successive rows for each combination
diffCombs = [np.array(i[1:]) - np.array(i[:-1]) for i in indexCombs]

# The only combinations that are valid are when successive row indices differ by 1 or 0
validCombs = [indexCombs[i] for i in range(len(indexCombs)) if np.all(diffCombs[i]**2<=1)]

# Now get the actual values from the triangle for each row combination
valueCombs = [[tri[i][j[i]] for i in range(len(tri))] for j in validCombs]

# Find the sum for each combination
sums = np.sum(valueCombs, axis=1)

# Print the information pertaining to the largest sum
print 'Highest sum: {0}'.format(sums.max())
print 'Combination: {0}'.format(valueCombs[sums.argmax()])
print 'Row indices: {0}'.format(indexCombs[sums.argmax()])

输出是:

最高和:23

组合:[3, 7, 4, 9]

行索引:(0, 0, 1, 0)

不幸的是,这在计算上是非常密集的,因此它不适用于大三角形 - 但肯定有一些概念和工具可以扩展以尝试使其工作!

【讨论】:

  • 谢谢!我肯定会查找 itertools 和 numpy - 我相信它们会派上用场。是的,我的主要问题是将它放大到更大的三角形,因为有很多可能性,它只需要很长时间才能运行!
猜你喜欢
  • 2011-11-16
  • 1970-01-01
  • 2011-11-02
  • 1970-01-01
  • 2020-07-28
  • 2020-06-27
  • 1970-01-01
  • 2019-08-19
  • 1970-01-01
相关资源
最近更新 更多