【发布时间】:2022-01-20 16:28:00
【问题描述】:
给定一个字母列表,例如 L=['a','b','c','d','e','f'] 和一个元组列表,例如 T=[(' a','b'),('a','c'),('b','c')].
现在我想从 L 的列表中创建最大数量的未包含在 T 中的元组。这需要在没有重复的情况下完成,即 (a,b) 将与 (b,a) 相同。此外,每个字母只能与另一个字母匹配。
我的想法是:
#create a List of all possible tuples first:
all_tuples = [(x,y) for x in L for y in L if x!=y]
#now remove duplicates
unique_tuples = list(set([tuple(sorted(elem)) for elem in all_tuples]))
#Now, create a new set that matches each letter only once with another letter
visited=set()
output = []
for letter1, letter2 in unique tuples:
if ((letter1, letter2) or (letter2, letter1)) in T:
continue
if not letter1 in visited and not letter2 in visited:
visited.add(letter1)
visited.add(letter2)
output.append((letter1,letter2))
print(output)
然而,这并不总是给出可能的元组的最大数量,这取决于 T 是什么。例如,假设我们提取可能的 unique_tuples=[('a','b'),('a','d'),('b','c')]。
如果我们先将 ('a','b') 附加到我们的输出中,我们将无法再附加 ('b','c'),因为 'b' 已经匹配。但是,如果我们先附加 ('a','d'),我们也可以在之后得到 ('b','c') 并获得最大数量的两个元组。
如何解决这个问题?
【问题讨论】:
-
我在遵循这个例子时遇到了麻烦——你不能有 ('b', 'c') 因为它已经在 T 中,对吧?鉴于 T 重复使用字母,“与另一个字母匹配”如何工作?
-
对不起,我的写作令人困惑。我的意思是从集合 [('a','b'),('a','d'),('b','c')] 中最多可以提取两个元组,使得每个字母都匹配最多一次。但是,如果先选择 ('a','b'),则无法选择其他元组。
-
而集合 T 是一个给定的集合,不需要满足字母只能匹配一次的规则。该规则仅适用于输出。