Code for finding cycles in a bipartite graph with a TWIST in Python

46 views Asked by At

I am struggling to find a working code to find cycles in a bipartite graph where each row represents a list of one persons preferences, all contained in one large list. A list represents ones preference. The twist here is that we only look at the top choice of all people first in the first iteration. When a cycle is found the players in the cycle are removed. In the second iteration everyone points at their top choice of the ramaining people, so if, for example, person 2's top choice was person 1, but person 1 was present in a cycle, we should look at the second, third, fourth or whatever preference of the second person. The code should finish when no cycles can be found anymore and should list the cycles found.

I have coded the following:

def find_and_remove_cycles(preferences_dict):
    def find_match(preferences_dict, person):
        for choice in preferences_dict[person]:
            if choice not in matched:
                matched.add(choice)
                return choice
        return None

    cycles = []
    while True:
        matched = set()
        cycle = None
        for person in preferences_dict:
            if person not in matched:
                while True:
                    choice = find_match(preferences_dict, person)
                    if choice is None:
                        break
                    if choice in matched:
                        cycle = [person, choice]
                        break
                    matched.add(person)
        if not cycle:
            break
        cycles.append(cycle)
        for person in cycle:
            del preferences_dict[person]

    return cycles

# Example preferences as a dictionary
preferences_dict = {
    1: [2, 3, 4],
    2: [3, 1, 4],
    3: [2, 1, 4],
    4: [1, 2, 3]
}

cycles = find_and_remove_cycles(preferences_dict)
print("Cycles found:", cycles)

The output gives the cycles [1,2] and [3,4], however the cycles should have been [2,3] and [1,4].

Can someone help me, as I have been stuck 2 days now...

Note: I have used dictionaries here as others have suggested on StackOverflow, but lists in list is what I prefer.

Thanks!

0

There are 0 answers