生成没有itertools和带有跳过元素的组合

时间:2019-05-03 14:05:11

标签: python

我关注itertools的代码,该代码正在生成组合。我需要更新此代码。有一个小的更新,看起来像这样:

def combinations(iterable, r, degrees):
   pool = tuple(iterable)
   n = len(pool)
   if r > n:
      return
   indices = []
   for pair in pairs:
      if degrees[pair[0]] < 2 and degrees[pair[1]] < 2:
          degrees[pair[0]] += 1
          degrees[pair[1]] += 1
          indices.append(pairs.index(pair))

      if len(indices) == r:
          break
   yield tuple(pool[i] for i in indices)
   while True:
      for i in reversed(range(r)):
          if indices[i] != i + n - r:
              break
      else:
          return
      indices[i] += 1
      for j in range(i+1, r):
          indices[j] = indices[j-1] + 1
      yield tuple(pool[i] for i in indices)

使用此功能,我需要在图形中生成所有可能的边。每个边都表示为元组,例如(1, 2)

因此iterable起作用的参数是所有可能边的列表:

[(5, 7), (5, 8), (5, 9), (5, 10), (5, 11), (5, 12), (6, 7), (6, 8), (6, 9), (6, 10), (6, 11), (6, 12), (7, 9), (7, 10), (7, 11), (7, 12), (8, 9), (8, 10), (8, 11), (8, 12), (9, 11), (9, 12), (10, 11), (10, 12)]

r参数是组合的长度,在我的情况下为8。

degrees是一个字典,其中包含每个节点的度数(5,6,7,8,9,10,11,12)。

在现有代码中,首先生成组合((5, 7), (5, 8), (6, 7), (6, 8), (9, 11), (9, 12), (10, 11), (10, 12))

在这种情况下:

for pair in pairs:
  if degrees[pair[0]] < 2 and degrees[pair[1]] < 2:
      degrees[pair[0]] += 1
      degrees[pair[1]] += 1
      indices.append(pairs.index(pair))

  if len(indices) == r:
      break

我正在验证每个节点的程度。 不大于2 。有人可以帮助我更改代码的while部分以生成所有可能的边(我需要像提到的情况一样跳过索引)。

我不能使用itertools,因为它效率很低。我也无法生成所有组合并对其进行过滤。我只需要跳过索引就可以了。

0 个答案:

没有答案
相关问题