简体   繁体   中英

Finding the largest list of tuples with distinct elements

Given a list of tuples, I want to find the max amount of tuples in the list where all the elements are distinct.

For example using the list:

[('nat', 'ges'), ('wisD', 'ges'), ('wisD', 'ak'), ('dutl', 'fatl')]

I need to return the list

[('nat', 'ges'), ('wisD', 'ak'), ('dutl', 'fatl')]

Because this list has the most amount of tuples from the original list while still having all elements be distinct.

I can't really figure out how to tackle this problem, so any help would be appreciated.

Here's one way to do it, by parsing through the tuple items and setting a flag if an item is duplicate/unique

test_list = [('nat', 'ges'), ('wisD', 'ges'), ('wisD', 'ak'), ('dutl', 'fatl')]
result = [] 
temp = set()
matched_items = set()
for inner in test_list:
    flag = True
    for ele in inner:
        if ele in temp and ele in matched_items:
            flag = False
        else:
            temp.add(ele)
    if flag:
        matched_items.update(inner)      
        result.append(inner)

    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM