简体   繁体   中英

How to find all possible combinations with ignore cases

I'm currently trying to figure out how to find all possible combinations with certain ignore cases attached to it.

I'll try my best to explain here.

dct = {
'1': "4 7 3",
'2': "6 3 4",
'3': "8 10 11",
'4': "11 9 3",
'5': "11 8 4",
'6': "1 3 11",
'7': "10 9 10",
'8': "11 8 6",
'9': "1 1 2",
'10': "11 6 8",
'11': "2 8 9" }

the values in this dict are the numbers where the key cant go. So key "1" can never be found with values 4, 7 and 3 Now lets say that key "1" gets value 2 added to its list of possible combis. Now key "1" cant have Values 6 3 and 4, as they aren't available in combination with value 2.

Think of it as a giant overly complex intersection with traffic lights. where every number represents a set of traffic lights. If a specific set of lights that sent cars ahead were to be activated, any traffic light which makes the cars turn onto the same road and most likely cause an impact will stay deactivated.

I've been tearing my hair out for the last 3 hours or so trying to figure it out, any help would be greatly appreciated!

You can use the following recursive generator to generate all possible combinations of all lengths. If you want the maximum possible length, you can compute max(..., key=len) .

from typing import Set


dct = {int(k): {int(x) for x in v.split()} for k, v in dct.items()}


def combinations(nodes: Set[int], banned: Set[int]):
    candidates = dct.keys() - nodes - banned
    candidates = {
        c for c in candidates
        if not nodes.intersection(dct[c])
    }
    if not candidates:
        yield nodes
    else:
        candidates = {  # eliminate duplicates
            c for c in candidates
            if not nodes or c > max(nodes)
        }
        for c in candidates:
            yield from combinations(nodes | {c}, banned | dct[c])


from pprint import pprint

pprint(list(combinations(set(), set())))

Output is:

[{8, 1, 2},
 {1, 2, 10, 5},
 {1, 11},
 {2, 5, 7},
 {8, 2, 7},
 {9, 3, 5},
 {3, 5, 7},
 {10, 4},
 {4, 6, 7},
 {8, 4, 7},
 {9, 10, 5},
 {9, 5, 6},
 {5, 6, 7},
 {11, 7},
 {8, 9}]

To compute longest possible combination (might not be unique):

pprint(max(combinations(set(), set()), key=len))

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