Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unordered version of itertools.permutations

Tags:

python

The following program constructs a URL from a list using the itertools.permutations.

def url_construct_function():
    for i in range(1, len(samplelist)):
        for item in list(permutations(samplelist, i)):
  1. Suppose there are 3 items presented in the sample list: a,b,c
  2. itertools.permutations provides a good description around various possible ordered combinations
    • a
    • b
    • c
    • a,b
    • a,c
    • b,a
    • b,c
    • c,a
    • c,b

I want to make the program understand that a,b and b,a are the same.

like image 976
Rams Avatar asked Mar 27 '16 19:03

Rams


People also ask

How do you find permutations without Itertools?

A. To create combinations without using itertools, iterate the list one by one and fix the first element of the list and make combinations with the remaining list. Similarly, iterate with all the list elements one by one by recursion of the remaining list.

How does Itertools permutations work?

The permutation tuples are emitted in lexicographic order according to the order of the input iterable. So, if the input iterable is sorted, the output tuples will be produced in sorted order. Elements are treated as unique based on their position, not on their value.

What does Permute mean in Python?

A permutation, also called an “arrangement number” or “order”, is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. Examples: Input : str = 'ABC' Output : ABC ACB BAC BCA CAB CBA.

What does permutations return in Python?

permutations() This tool returns successive length permutations of elements in an iterable. If is not specified or is None , then defaults to the length of the iterable, and all possible full length permutations are generated. Permutations are printed in a lexicographic sorted order.


1 Answers

itertools.combinations works like itertools.permutations and does what you are looking for (and what the name suggests)

from itertools import combinations
...
    for item in list(combinations(samplelist, i)):
    ...
a
b
c
a, b
a, c
b, c

as in combinations, unlike permutations, order doesn't matter. All neatly covered in the docs.

like image 119
user2390182 Avatar answered Sep 21 '22 20:09

user2390182