Search code examples
pythonpermutationpython-itertools

how to edit a permutation


every number is a port. and the permutation gives me all possible routes but my starting port is always number 1,so out of all combinations i want the ones that start with 1.

this is all i got so far

from itertools import permutations

routes = permutations([1 , 2, 3 ,4 , 5])
for i in list(routes):
      print(i)

is there a way to enable me to pick those specific combinations?


Solution

  • You could simply add a 1 to the beginning of the permutations of 2,3,4,5. For example,

    from itertools import permutations
    
    routes = permutations([2, 3 ,4 , 5])
    for i in routes:
          print([1,*i])
    

    If you really want to generate every permutation and filter down to those starting with 1, you could do the following.

    from itertools import permutations
    
    routes = permutations([1,2, 3 ,4 , 5])
    for i in routes:
        if i[0] == 1:
            print(i)