Here is my Python code for finding the permutation index of a given digits and a target number. And by permutation index I mean, for example, given digits
[1, 2, 3, 4]. find the index of
3124, meaning the position of
3124 in all permutations. This code finds that. However I have suspicions about it efficiency and implementation. Please review my code.
def perm_ind(numbers, target, length): """ Finding the position of a single permutation in all permutations. Using the mathematic formula. """ ranks = sorted(numbers) # For keeping the index even after some numbers are placed and removed. ind = 0 for step in reversed(xrange(length)): num = (target / 10 ** step) # These two lines are used to get target %= 10 ** step # the left-most digit in each iteration times = ranks.index(num) # Find the rank of the currect digit. ind += factorial(length - 1) * times # Add to result ranks.remove(num) # Remove the used(Placed) number length -= 1 # Decrease length return ind # Example usages print perm_ind([1, 2, 3], 123, 3) print perm_ind([1, 2, 3], 132, 3) print perm_ind([1, 2, 3], 213, 3)