-2

I understand there are many, many posts about permutations (unique, variable length, etc.), but I have not been able to use them to solve my particular issue.

Let's say I have a list of metropolitan areas in the United States: ['nyc','sf','atl']

I need to output a permutation of 2 metros without repetition. For example, I've tried:

set(itertools.permutations(['nyc','sf','atl'], 2))

{('atl', 'nyc'),
 ('atl', 'sf'),
 ('nyc', 'atl'),
 ('nyc', 'sf'),
 ('sf', 'atl'),
 ('sf', 'nyc')}

However, notice that NYC and ATL are paired twice: ('nyc', 'atl') and ('atl', 'nyc'). The ideal output would be:

{('nyc', 'nyc'),
 ('nyc', 'sf'),
 ('nyc', 'atl'),
 ('sf', 'sf'),
 ('sf', 'atl'),
 ('atl', 'atl')}
rpanai
  • 12,515
  • 2
  • 42
  • 64
measureallthethings
  • 1,102
  • 10
  • 26
  • 5
    You want combinations, `itertools.combinations`?, for example `combinations('ABCD', 2) --> AB AC AD BC BD CD`. There is also combinations_with_replacement – Dani Mesejo Oct 18 '19 at 15:51
  • @DanielMesejo yes, that will work! specifically, `list(itertools.combinations_with_replacement(['nyc','sf','atl'], 2))` is exactly what i am looking for because it also compares to each other (e.g., i get `('nyc', 'nyc')` in the list. – measureallthethings Oct 18 '19 at 15:56

1 Answers1

2

As mentioned by @Daniel Mesejo comment, use combinations.

>>> import itertools
>>> set(itertools.combinations(['nyc','sf','atl'], 2))
{('nyc', 'atl'), ('sf', 'atl'), ('nyc', 'sf')}
Florian Bernard
  • 2,561
  • 1
  • 9
  • 22