vendredi 9 novembre 2018

Python- If condition for a variable True, execute function assigning new variable until False

I've not ever encountered this type of situation in a Python for loop before.

I have a dictionary of Names (key) and Regions (value). I want to match up each Name with two other names. The matched name cannot be themselves and reversing the elements is not a valid match (1,2) = (2,1). I do not want people from the same Region to be matched together though (unless it becomes impossible).

dict = {
    "Tom":"Canada",
    "Jerry":"USA",
    "Peter":"USA",
    "Pan":"Canada",
    "Edgar":"France"
    }

desired possible output: [('Tom','Jerry'),('Tom','Peter'),('Jerry','Pan'),('Pan','Peter'),('Edgar','Peter'),('Edgar','Jerry')]

Everyone appears twice, but Jerry and Peter appears more in order for Edgar to have 2 matches with Names from a different region (Jerry and Peter should be chosen randomly here) Count: Tom: 2, Jerry: 3, Peter: 3, Pan: 2, Edgar: 2

My approach is to convert the names into a list, shuffle them, then create tuple pairs using zip in a custom function. After the function is complete. I use a a for to check for pairings from the same region, if a same pairing region exists, then re-run the custom function. For some reason, when I print the results, I still see pairings between the same regions. What am I missing here?

    names=list(dict.keys())
    def pairing(x):
        random.shuffle(x)
        #each person is tupled twice, once with the neighbor on each side
        pairs = list(zip(x, x[1:]+x[:1]))
        return pairs

    pairs=pairing(names) #assigns variable from function to 'pairs'

    for matchup in pairs:
        if dict[matchup[0]]==dict[matchup[1]]:    
            break
            pairing(names)

    pairs=pairing(names)
    for matchup in pairs:
        print(matchup[0] ,dict[matchup[0]] , matchup[1] , dict[matchup[1]])

Just looking at it, something is clearly broken in the for loop, please help!




Aucun commentaire:

Enregistrer un commentaire