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









up vote
0
down vote

favorite












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?



 import random
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!



I've tried while rather than if in the for loop, but it did not work.










share|improve this question





















  • When you detect an invalid pairing - you simply break from the loop and go on with the program; the second call to pairing() is unreachable (and wouldn't do anything, anyway, since you throw the return value away).
    – jasonharper
    Nov 9 at 19:56










  • When I set pairs=pairing(names) at 3rd last line, won't that capture the return value from the for loop?
    – machump
    Nov 9 at 19:59










  • Oh, I didn't even notice that line. What that does is make all your previous work meaningless, because you generated entirely new pairs and didn't check them.
    – jasonharper
    Nov 9 at 20:00














up vote
0
down vote

favorite












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?



 import random
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!



I've tried while rather than if in the for loop, but it did not work.










share|improve this question





















  • When you detect an invalid pairing - you simply break from the loop and go on with the program; the second call to pairing() is unreachable (and wouldn't do anything, anyway, since you throw the return value away).
    – jasonharper
    Nov 9 at 19:56










  • When I set pairs=pairing(names) at 3rd last line, won't that capture the return value from the for loop?
    – machump
    Nov 9 at 19:59










  • Oh, I didn't even notice that line. What that does is make all your previous work meaningless, because you generated entirely new pairs and didn't check them.
    – jasonharper
    Nov 9 at 20:00












up vote
0
down vote

favorite









up vote
0
down vote

favorite











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?



 import random
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!



I've tried while rather than if in the for loop, but it did not work.










share|improve this question













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?



 import random
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!



I've tried while rather than if in the for loop, but it did not work.







python-3.x for-loop random matching shuffle






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 9 at 19:46









machump

309112




309112











  • When you detect an invalid pairing - you simply break from the loop and go on with the program; the second call to pairing() is unreachable (and wouldn't do anything, anyway, since you throw the return value away).
    – jasonharper
    Nov 9 at 19:56










  • When I set pairs=pairing(names) at 3rd last line, won't that capture the return value from the for loop?
    – machump
    Nov 9 at 19:59










  • Oh, I didn't even notice that line. What that does is make all your previous work meaningless, because you generated entirely new pairs and didn't check them.
    – jasonharper
    Nov 9 at 20:00
















  • When you detect an invalid pairing - you simply break from the loop and go on with the program; the second call to pairing() is unreachable (and wouldn't do anything, anyway, since you throw the return value away).
    – jasonharper
    Nov 9 at 19:56










  • When I set pairs=pairing(names) at 3rd last line, won't that capture the return value from the for loop?
    – machump
    Nov 9 at 19:59










  • Oh, I didn't even notice that line. What that does is make all your previous work meaningless, because you generated entirely new pairs and didn't check them.
    – jasonharper
    Nov 9 at 20:00















When you detect an invalid pairing - you simply break from the loop and go on with the program; the second call to pairing() is unreachable (and wouldn't do anything, anyway, since you throw the return value away).
– jasonharper
Nov 9 at 19:56




When you detect an invalid pairing - you simply break from the loop and go on with the program; the second call to pairing() is unreachable (and wouldn't do anything, anyway, since you throw the return value away).
– jasonharper
Nov 9 at 19:56












When I set pairs=pairing(names) at 3rd last line, won't that capture the return value from the for loop?
– machump
Nov 9 at 19:59




When I set pairs=pairing(names) at 3rd last line, won't that capture the return value from the for loop?
– machump
Nov 9 at 19:59












Oh, I didn't even notice that line. What that does is make all your previous work meaningless, because you generated entirely new pairs and didn't check them.
– jasonharper
Nov 9 at 20:00




Oh, I didn't even notice that line. What that does is make all your previous work meaningless, because you generated entirely new pairs and didn't check them.
– jasonharper
Nov 9 at 20:00












1 Answer
1






active

oldest

votes

















up vote
0
down vote



accepted










from itertools import combinations
import pandas as pd
import random

dict='your dictionary'

#create function to pair names together
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]))
for matchup in pairs:
if dict[matchup[0]]==dict[matchup[1]]: #if someone's gym matches their opponent's gym in dictionary, re-run this function
return pairing(x)
return pairs

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


The trick is to return pairing(x) inside the custom function. This will return new pairings if any elements in the tuple share the same value in the dictionary. If inside the if statement, you go pairing(x) then return pair, it'll return the original tuple list which contains duplicates.






share|improve this answer




















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53232361%2fpython-if-condition-for-a-variable-true-execute-function-assigning-new-variabl%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote



    accepted










    from itertools import combinations
    import pandas as pd
    import random

    dict='your dictionary'

    #create function to pair names together
    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]))
    for matchup in pairs:
    if dict[matchup[0]]==dict[matchup[1]]: #if someone's gym matches their opponent's gym in dictionary, re-run this function
    return pairing(x)
    return pairs

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


    The trick is to return pairing(x) inside the custom function. This will return new pairings if any elements in the tuple share the same value in the dictionary. If inside the if statement, you go pairing(x) then return pair, it'll return the original tuple list which contains duplicates.






    share|improve this answer
























      up vote
      0
      down vote



      accepted










      from itertools import combinations
      import pandas as pd
      import random

      dict='your dictionary'

      #create function to pair names together
      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]))
      for matchup in pairs:
      if dict[matchup[0]]==dict[matchup[1]]: #if someone's gym matches their opponent's gym in dictionary, re-run this function
      return pairing(x)
      return pairs

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


      The trick is to return pairing(x) inside the custom function. This will return new pairings if any elements in the tuple share the same value in the dictionary. If inside the if statement, you go pairing(x) then return pair, it'll return the original tuple list which contains duplicates.






      share|improve this answer






















        up vote
        0
        down vote



        accepted







        up vote
        0
        down vote



        accepted






        from itertools import combinations
        import pandas as pd
        import random

        dict='your dictionary'

        #create function to pair names together
        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]))
        for matchup in pairs:
        if dict[matchup[0]]==dict[matchup[1]]: #if someone's gym matches their opponent's gym in dictionary, re-run this function
        return pairing(x)
        return pairs

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


        The trick is to return pairing(x) inside the custom function. This will return new pairings if any elements in the tuple share the same value in the dictionary. If inside the if statement, you go pairing(x) then return pair, it'll return the original tuple list which contains duplicates.






        share|improve this answer












        from itertools import combinations
        import pandas as pd
        import random

        dict='your dictionary'

        #create function to pair names together
        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]))
        for matchup in pairs:
        if dict[matchup[0]]==dict[matchup[1]]: #if someone's gym matches their opponent's gym in dictionary, re-run this function
        return pairing(x)
        return pairs

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


        The trick is to return pairing(x) inside the custom function. This will return new pairings if any elements in the tuple share the same value in the dictionary. If inside the if statement, you go pairing(x) then return pair, it'll return the original tuple list which contains duplicates.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 10 at 0:50









        machump

        309112




        309112



























             

            draft saved


            draft discarded















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53232361%2fpython-if-condition-for-a-variable-true-execute-function-assigning-new-variabl%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Darth Vader #20

            How to how show current date and time by default on contact form 7 in WordPress without taking input from user in datetimepicker

            Ondo