Russell McCoy
Russell McCoy

Reputation: 25

Nested Loops Question___>

could someone help me out with this question? I'm sure it's simple but I'm new to python.

Question: Create a program where every person meets the other persons = [ “John”, “Marissa”, “Pete”, “Dayton” ]

What I have so far:

persons = ["John", "Marissa", "Pete", "Dayton"]

them = ["Dayton", "Pete", "Marissa", "John"]

for x in persons:
    for y in them:
        print(x, "Meets", y)

This works but I don't want to print the same person meeting themself.

Upvotes: 2

Views: 358

Answers (4)

VMSM
VMSM

Reputation: 15

This code should also work:

persons = ["John", "Marissa", "Pete", "Dayton"]
them = ["Dayton", "Pete", "Marissa", "John"]

for x in range(len(persons)):
    for y in range(len(them)):
        if x != y:
           print(f'{persons[x]} meets {them[y]}')

Output:

John meets Pete

John meets Marissa

Marissa meets Dayton

Marissa meets John

Pete meets Dayton

Pete meets John

Dayton meets Pete

Dayton meets Marissa

Upvotes: 0

jrhode2
jrhode2

Reputation: 161

You can also use combinations() from itertools (docs). This will have each person meeting everyone else exactly once, so you'd have John meets Marissa or Marissa meets John but not both.

from itertools import combinations

persons = ["John", "Marissa", "Pete", "Dayton"]

for person1, person2 in combinations(persons, 2):
    print(person1, "Meets", person2)

Output:

John Meets Marissa
John Meets Pete
John Meets Dayton
Marissa Meets Pete
Marissa Meets Dayton
Pete Meets Dayton

Upvotes: 3

Timofey Chernousov
Timofey Chernousov

Reputation: 1294

In addition to @itsanantk answer, when you want to eliminate same pairs (i.e. treat "John Meets Marissa" and "Marissa Meets John" as a same), you could use following pattern:

persons = ["John", "Marissa", "Pete", "Dayton"]
for i, x in enumerate(persons):
    for y in persons[i+1:]:
        print(x, "Meets", y)

Here, every person meets every person standing after it in the list.

Same effect could be achieved using more concise syntaxes of itertools module:

from itertools import combinations
persons = ["John", "Marissa", "Pete", "Dayton"]
for x, y in combinations(persons,2):
    print(x, "Meets", y)

Upvotes: 0

itsanantk
itsanantk

Reputation: 264

This code should work:

persons = ["John", "Marissa", "Pete", "Dayton"]

them = ["Dayton", "Pete", "Marissa", "John"]

for x in persons:
    for y in them:
        if not x==y:
            print(x, "Meets", y)

Upvotes: 4

Related Questions