簡體   English   中英

從一組2元組生成3元組

[英]Generating 3-tuples from a set of 2-tuples

在先前的問題中:

從2元組列表中生成3元組的最大數量

我從@AChampion得到了一個答案,如果2元組的數目可被3整除,這似乎有效。但是,例如,如果我們有10個2元組,則解決方案將失敗。 在摸索了一段時間之后,我覺得不可能找到一個完美的解決方案:

(1,2)(1,3),(1,4),(2,3),(2,4),(3,4)

因此,我對尋找一種最小化剩余元組數量的解決方案感興趣。 在上面的示例中,結果可能是:

(1,2,3)           # derived from (1,2), (1,3), (2,3)
(1,4),(2,4),(3,4) # remainder tuples 

從3個2元組生成3元組的規則是:

(a,b), (b,c), (c,a) -> (a, b, c)

即2元組是一個長度為3的循環。3元組中元素的順序並不重要,即:

(a,b,c) == (c,a,b)

我實際上對我們有數字n的情況感興趣:

for x in range(1,n+1):
    for y in range(1,n+1):
        if x!=y:
            a.append((x,y))

# a = [ (1,2),...,(1,n), (2,1),(2,3),...,(2,n),...(n,1),...,(n,n-1) ]

從a中,最小化生成3個元組時剩余的2個元組的數量。 每個2元組只能使用一次。

我花了好幾個小時來解決這個問題,但是對於一般情況,我似乎無法提出一個優雅的解決方案(嗯,我也沒有找到一個丑陋的解決方案:-)。 有什么想法嗎?

為此,您需要創建用於替換的組合數量。 然后遍歷您的數據以獲取包含以上任意組合的3個項目並替換它們。 我已經完成了幾個步驟。

from itertools import combinations

# create replacements elements
number_combinations_raw = list(combinations(range(1, 5), 3))

# create proper number combinations
number_combinations = []
for item in number_combinations_raw:
    if (item[0] + 1 == item[1]) and (item[1] + 1 == item[2]):
        number_combinations.append(item)

# create test data
data = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4)]

# reduce data
reduce_data = []
for number_set in number_combinations:
    count = 0
    merged_data = []
    for item in data:
        if (number_set[0] in item and number_set[1] in item) or (number_set[1] in item and number_set[2] in item) \
            or (number_set[0] in item and number_set[2] in item):
            merged_data.append(item)
            count += 1
    if count == 3:
        reduce_data.append((number_set, merged_data))

# delete merged elements from data list and add replacement
for item in data:
    for reduce_item in reduce_data:
        for element in reduce_item[1]:
            if element in data:
                data.remove(element)

        data = [reduce_item[0]] + data

# remove duplicated replaced elements
final_list = list(dict.fromkeys(data))

輸出:

[(1, 2, 3), (1, 4), (2, 4)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM