aboutsummaryrefslogtreecommitdiff
path: root/challenge-174/mohammad-anwar/python/ch-2.py
diff options
context:
space:
mode:
authorMohammad S Anwar <mohammad.anwar@yahoo.com>2022-07-21 23:38:45 +0100
committerMohammad S Anwar <mohammad.anwar@yahoo.com>2022-07-21 23:38:45 +0100
commitcff3bfa6eda5aa6f58717e02e7b7c4ee2e0bf853 (patch)
treeaf52067f9f430c60e616a6aa6a7e21c28d3eab66 /challenge-174/mohammad-anwar/python/ch-2.py
parent63e8b874c96aa159a17eeb62a5cec40abb4aecb2 (diff)
downloadperlweeklychallenge-club-cff3bfa6eda5aa6f58717e02e7b7c4ee2e0bf853.tar.gz
perlweeklychallenge-club-cff3bfa6eda5aa6f58717e02e7b7c4ee2e0bf853.tar.bz2
perlweeklychallenge-club-cff3bfa6eda5aa6f58717e02e7b7c4ee2e0bf853.zip
- Added solutions to the task "Permutation Ranking" of week 174.
Diffstat (limited to 'challenge-174/mohammad-anwar/python/ch-2.py')
-rw-r--r--challenge-174/mohammad-anwar/python/ch-2.py53
1 files changed, 53 insertions, 0 deletions
diff --git a/challenge-174/mohammad-anwar/python/ch-2.py b/challenge-174/mohammad-anwar/python/ch-2.py
new file mode 100644
index 0000000000..96b0492d4f
--- /dev/null
+++ b/challenge-174/mohammad-anwar/python/ch-2.py
@@ -0,0 +1,53 @@
+#!/usr/bin/python3
+
+'''
+
+Week 174:
+
+ https://theweeklychallenge.org/blog/perl-weekly-challenge-174
+
+Task #2: Permutation Ranking
+
+ You are given a list of integers with no duplicates, e.g. [0, 1, 2].
+
+ Write two functions, permutation2rank() which will take the list
+ and determine its rank (starting at 0) in the set of possible
+ permutations arranged in lexicographic order, and rank2permutation()
+ which will take the list and a rank number and produce just that
+ permutation.
+
+'''
+
+import unittest
+import itertools
+
+def permutation2rank(array):
+ array.sort()
+ return list(itertools.permutations(array))
+
+def rank2permutation(array, rank):
+ p2r = permutation2rank(array)
+ return p2r[rank]
+
+#
+#
+# Unit test class
+
+class TestPermutationRanking(unittest.TestCase):
+ def test_permutation2rank(self):
+ exp = [ (0, 1, 2),
+ (0, 2, 1),
+ (1, 0, 2),
+ (1, 2, 0),
+ (2, 0, 1),
+ (2, 1, 0),
+ ]
+ got = permutation2rank([1, 0, 2])
+ self.assertEqual(exp, got)
+
+ def test_rank2permutation(self):
+ exp = (0, 2, 1)
+ got = rank2permutation([1, 0, 2], 1)
+ self.assertEqual(exp, got)
+
+unittest.main()