部分次序中的最大元素

时间:2018-03-07 15:34:44

标签: python

我正在寻找Python代码以按部分顺序查找最大元素。

还有另外两篇文章解决了这个问题,

但他们只有模糊的描述,没有代码。也有一些年过去了,因为这些被问到了。

编辑:更具体地说,他们都建议建立一个DAG。我自己的想法是使用一些循环,添加和删除列表。但是,我想知道是否有一些简短的“pythonic”方式,对此进行编码。

更确切地说,我有一个条目列表0,1;所有相同的长度。这些数组是GF(2)上某些矩阵的图像空间,只有0和1的字段。

xy成为两个数组。 我说x <= y,如果这种不平等是分段的话。

编辑:更确切地说,我的不等式由函数

给出
def leq(x,y):
  return all([x[i] <= y[i] for i in range(len(x))])

示例

输入:

[1 1 0]
[1 0 0]
[1 0 1]

输出:

[1 1 0]
[1 0 1]

编辑我写下了我的想法

import numpy as np

l = [np.array([1, 1, 0]), np.array([1, 0, 0]), np.array([0, 1, 1])]
l.sort(reverse=True, key=np.sum)
maximal = [l[0]]
for e in l:
    i = 0
    replaced = False
    while i < len(maximal):
        if (maximal[i] <= e).all():
            if replaced:
                maximal.remove(maximal[i])
            else:
                maximal[i] = e.copy()
                replaced = True
        if (e <= maximal[i]).all():
            break
        i += 1
    if i == len(maximal) and not replaced:
        maximal.append(e.copy())

如何在Python中很好地计算(更短的代码/更快的运行时)?

1 个答案:

答案 0 :(得分:0)

经过一些测试后,我最终得到了以下代码。问题的上述代码仍有一些错误。

import numpy as np

def maximal_elements(input_list):
  """Given a list of np.array, compute the maximal elements.

  Call:
    maximal = maximal_elements(input_list)
  Input:
    input_list: list of np.array, all need to have the same length.
  Output:
    maximal: list of np.array, which contains the maximal elements of input_list,
      the order used is elementwise "<="      
  """
  l = input_list.copy()
  l.sort(reverse=True, key=np.sum)
  maximal = [l[0]]
  for e in l[1:]:
    i = 0
    replaced = False
    while i < len(maximal):
      if (maximal[i] <= e).all():
        if replaced:
          maximal.pop(i)
          i -= 1
        else:
          maximal[i] = e.copy()
          replaced = True
      if (e <= maximal[i]).all():
        if not (e == maximal[i]).all():
          break
      i += 1
    if i == len(maximal) and not replaced:
      maximal.append(e.copy())
  return maximal

import itertools
import random
random.seed(2)
l = [np.array(e) for e in random.sample(list(itertools.product([0,1], repeat=5)), 9)]
maximal_elements(l)

返回[array([1, 1, 1, 1, 0]), array([1, 0, 1, 1, 1]), array([0, 1, 0, 1, 1])]