I have to solve the Travelling Salesman Problem using a genetic algorithm that I will have to write for homework.
The problem consists of 52 cities. Therefore, the search space is 52!
. I need to randomly sample (say) 1000 permutations of range(1, 53)
as individuals for the initial population of my genetic algorithm.
In order to do this, I tried:
>>> random.sample(itertools.permutations(range(1, 53)), 1000)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/random.py", line 314, in sample
n = len(population)
TypeError: object of type 'itertools.permutations' has no len()
So I tried
>>> random.sample(list(itertools.permutations(range(1, 53))), 1000)
However, given that 52!
is VERY large, the list
operation is maxing out the memory and swap space on my computer. I can't just pick the first 1000 permutations generated by itertools.permutations
because it's very deterministic and that would bias my genetic algorithm.
Is there a better way to achieve this sampling?
The idea is to generate each permutation from the previous permutation by choosing a pair of elements to interchange, without disturbing the other n-2 elements. Following is the illustration of generating all the permutations of n given numbers. Example:
If the elements can repeat in the permutation, the formula is: In both formulas "!" denotes the factorial operation: multiplying the sequence of integers from 1 up to that number. For example, a factorial of 4 is 4! = 4 x 3 x 2 x 1 = 24. In some cases, repetition of the same element is allowed in the permutation.
Like the Combinations Calculator the Permutations Calculator finds the number of subsets that can be taken from a larger set. However, the order of the subset matters. The Permutations Calculator finds the number of subsets that can be created including subsets of the same items in different orders.
No good permutation exists. Position of 2 is 1 and position of 1 is 2. Recommended: Please try your approach on {IDE} first, before moving on to the solution. Approach: Consider permutation p such that pi = i. Actually, p is a sequence of numbers from 1 to N and ppi = i .
You don't need to permute at all. Call random.sample(range(52), 52)
1000 times.
P.S.: You really should use zero-based indexing (range(52)
as opposed to range(1, 53)
) in all your work. Things generally work out better that way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With