Читать книгу Algorithms For Dummies - John Paul Mueller, John Mueller Paul, Luca Massaron - Страница 89
Distinguishing permutations
ОглавлениеWhen you receive raw data, it appears in a specific order. The order can represent just about anything, such as the log of a data input device that monitors something like a production line. Perhaps the data is a series of numbers representing the number of products made at any particular moment in time. The reason that you receive the data in a particular order is important, but that order might not lend itself to obtaining the output you need from an algorithm. Creating a data permutation, a reordering of the data so that it presents a different view, might help to achieve a desired result.
You can view permutations in a number of ways. One method of viewing a permutation is as a random presentation of the sequence order. In this case, you can use the numpy
random.permutation()
function, as shown here:
a = np.array([1,2,3])print(np.random.permutation(a))
What you see is a randomized version of the original data, such as [2 1 3]. Each time you run this code, you receive a different random ordering of the data sequence, which comes in handy with algorithms that require you to randomize the dataset to obtain the desired results. For example, sampling is an essential part of data analytics, and the technique shown is an efficient way to perform this task.
Another way to view the issue is the need to obtain all the permutations for a dataset so that you can try each one in turn. To perform this task, you need to import the itertools
package. The following code shows a technique you can use to obtain a list of all the permutations of a particular vector:
from itertools import permutations a = np.array([1,2,3]) for p in permutations(a): print(p)
The output you see looks like this:
(1, 2, 3)(1, 3, 2)(2, 1, 3)(2, 3, 1)(3, 1, 2)(3, 2, 1)
If you want to use the list comprehension (https://www.w3schools.com/python/python_lists_comprehension.asp
) approach, which is a shorter method of performing repetitive tasks, you can use [print(p) for p in permutations(a)]
instead. You can read more about itertools
at https://docs.python.org/3/library/itertools.html
.