To calculate permutations in Python, you can use the itertools.permutations() function.
This function returns all possible permutations of a given iterable, such as a list, dictionary, tuple, or string.
Example 1: Generating Permutations of a List
Visual Representation
import itertools
new_list = [21, 18, 19]
perm = itertools.permutations(new_list)
for i in list(perm):
print(i)
Output
(21, 18, 19)
(21, 19, 18)
(18, 21, 19)
(18, 19, 21)
(19, 21, 18)
(19, 18, 21)
Example 2: Generating Permutations of a Tuple
Visual Representation
import itertools
sample_tuple = (21, 19)
perm = itertools.permutations(sample_tuple)
for item in perm:
print(item)
Output
(21, 19)
(19, 21)
Example 3: Generating Permutations of a Dictionary
The permutations() function does not produce permutations of the dictionary itself, but rather of the dictionary’s keys (by default).
However, you can also produce permutations of the dictionary’s values using the dictionary.values() method.
import itertools
sample_dict = { 1: 19, 2: 21, 3: 18}
# Calculating permutations of the dictionary's keys
permutations = itertools.permutations(sample_dict, 3) # Choosing 3 keys for each permutation
# Printing the permutations
for perm in permutations:
print(perm)
Output
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
Apka number kya hai?