How to Do a Permutation in Python
Permutations are used in probability and statistics to determine the number of ways a list of items can be arranged. Python does not include any integrated permutation functions, but the calculation can be accomplished nonetheless via the "itertools module". Included in this module is a "permutations" function that can calculate and list the number of permutations given a "set" of values and a permutation length of "r".
Instructions
-
-
1
Import the "itertools" module:
import itertools
-
2
Assign all values in the set to a variable. Suppose that you need to determine the number of ways 2 members from a sorority of 5 students could be elected into positions as Vice President and President. Assuming their names are Angela, Cindy, Jan, Marsha and Beyonce, you would type the following command:
permutation_set_variable = ['Angela', 'Cindy', 'Jan', 'Marsha', 'Beyonce']
-
-
3
Call the "permutations" function in the following form:
itertools.permutations(set, r)
-
4
Replace "set" with the variable containing the values and "r" with the length required. Given the example, you would type the following:
itertools.permutations(permutation_set_variable, 2)
-
1