0

Context: I'm learning python and I'm trying to make permutations without using itertools. I have a list with 3 football teams and I'd like to make all possible matches between them (so with 3 teams from the team list, we would have 6 possible matches, 4 teams would be 12 matches, etc).

I was trying to do something like this:

team = ["FCP", "SCP", "SLB"]

def allMatches(lst):
    teams = []
    for index in range(0,len(lst)-1):
        for element in lst:
            if teams[index][0] != teams[index][1]: #I was trying to make it so that tuples that have the same team are excluded - ('FCP','FCP') would not be appended for example, but I'm calling teams when it has 0 items appended so this won't do nothing
                teams.append(tuple((element,team[index-1])))
    return teams

allMatches(team)

Desired output would be something like this:

[('FCP','SCP'), ('FCP','SLB'), ('SCP','FCP'), ...]

Thank you in advance

  • Is it not enough for you to write the six possible matches directly? `[(team[0], team[1]), (team[0], team[2]), ...]` – Jose Manuel de Frutos Nov 16 '21 at 22:08
  • In the future, please try to search for solutions first. In your case, it is as easy as putting `python combinations` [into a search engine](https://duckduckgo.com/?q=python+combinations). – Karl Knechtel Nov 16 '21 at 22:19
  • @KarlKnechtel Thank you, most of the solutions I've found used itertools and I was trying to look for something as "vanilla" as possible. –  Nov 16 '21 at 22:20
  • There are all kinds of previous duplicates of that question, too, plus more guidance on the rest of the Internet. Try `python combinations without itertools`. – Karl Knechtel Nov 16 '21 at 22:22
  • Will do, thank you for your help! –  Nov 16 '21 at 22:23

2 Answers2

3

This would fix your code:

team = ["FCP", "SCP", "SLB"]
def allMatches(lst):
    teams = []
    for element_list1 in lst:
        for element_list2 in lst:
            if element_list1 != element_list2:
                teams.append(tuple((element_list1, element_list2)))
    return teams

allMatches(team)

It would be even nicer with a list comprehension:

team = ["FCP", "SCP", "SLB"]
def allMatches(lst):
    return [(el1, el2) for el1 in lst for el2 in lst if el1!=el2]
    

allMatches(team)
intedgar
  • 631
  • 1
  • 11
0

You can try this :

team = ["FCP", "SCP", "SLB"]
teams = []

for index in range(len(team)) :
    for index_2 in range(len(team)) :
        if index != index_2 :
            teams.append(tuple((team[index], team[index_2])))

print(teams)

#[('FCP', 'SCP'),('FCP', 'SLB'),('SCP', 'FCP'),('SCP', 'SLB'),('SLB', 'FCP'),('SLB', 'SCP')]
gustavolq
  • 408
  • 3
  • 10