From 44753a1537cb1f506b3bead25b9e594ef65019a5 Mon Sep 17 00:00:00 2001 From: Kiril Bangachev <51961981+KirilBangachev@users.noreply.github.com> Date: Fri, 13 Sep 2019 00:00:15 -0400 Subject: [PATCH 1/2] Add Kth lexicographic permutation Function that computes the kth lexicographic permtation of 0,1,2,...,n-1 in O(n^2) time --- maths/kth_lexicographic_permutation.py | 44 ++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 maths/kth_lexicographic_permutation.py diff --git a/maths/kth_lexicographic_permutation.py b/maths/kth_lexicographic_permutation.py new file mode 100644 index 000000000000..bfa41e31ea18 --- /dev/null +++ b/maths/kth_lexicographic_permutation.py @@ -0,0 +1,44 @@ +def kthPermutation(k, n): + """ + Finds k'th lexicographic permutation (in increasing order) of + 0,1,2,...n-1 in O(n^2) time. + + Examples: + First permutation is always 0,1,2,...n + >>> kthPermutation(0,5) + [0, 1, 2, 3, 4] + + The order of permutation of 0,1,2,3 is [0,1,2,3], [0,1,3,2], [0,2,1,3], + [0,2,3,1], [0,3,1,2], [0,3,2,1], [1,0,2,3], [1,0,3,2], [1,2,0,3], + [1,2,3,0], [1,3,0,2] + >>> kthPermutation(10,4) + [1, 3, 0, 2] + """ + # Factorails from 1! to (n-1)! + factorials = [1] + for i in range(2, n): + factorials.append(factorials[-1] * i) + assert ( + 0 <= k and k < factorials[-1] * n + ), "k out of bounds" + + permutation = [] + elements = list(range(n)) + + # Find permutation + while factorials: + factorial = factorials.pop() + number = k // factorial + permutation.append(elements[number]) + elements.remove(elements[number]) + k = k % factorial + permutation.append(elements[0]) + + return permutation + + +if __name__ == "__main__": + import doctest + + doctest.testmod() + From 7ad45a46e02edda86a45969de8768f26ef44b306 Mon Sep 17 00:00:00 2001 From: Kiril Bangachev <51961981+KirilBangachev@users.noreply.github.com> Date: Fri, 13 Sep 2019 07:05:39 -0400 Subject: [PATCH 2/2] Update kth_lexicographic_permutation.py Addressed requested changes --- maths/kth_lexicographic_permutation.py | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/maths/kth_lexicographic_permutation.py b/maths/kth_lexicographic_permutation.py index bfa41e31ea18..1820be7274e3 100644 --- a/maths/kth_lexicographic_permutation.py +++ b/maths/kth_lexicographic_permutation.py @@ -18,9 +18,7 @@ def kthPermutation(k, n): factorials = [1] for i in range(2, n): factorials.append(factorials[-1] * i) - assert ( - 0 <= k and k < factorials[-1] * n - ), "k out of bounds" + assert 0 <= k < factorials[-1] * n, "k out of bounds" permutation = [] elements = list(range(n)) @@ -28,10 +26,9 @@ def kthPermutation(k, n): # Find permutation while factorials: factorial = factorials.pop() - number = k // factorial + number, k = divmod(k, factorial) permutation.append(elements[number]) elements.remove(elements[number]) - k = k % factorial permutation.append(elements[0]) return permutation @@ -41,4 +38,3 @@ def kthPermutation(k, n): import doctest doctest.testmod() -