Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit fa0062c

Browse files
python: add problem 60 and unittest
1 parent 9550c34 commit fa0062c

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

Python/sln_1_100/solution_51_60.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,3 +135,27 @@ def generateMatrix(self, n):
135135
direction_index = (direction_index + 1) % 4
136136

137137
return matrix
138+
139+
def getPermutation(self, n, k):
140+
"""
141+
60
142+
:param n:
143+
:param k:
144+
:return:
145+
"""
146+
factorial = 1
147+
for i in range(1, n + 1):
148+
factorial *= i
149+
digits = [str(d) for d in range(1, n + 1)]
150+
perm_digits = []
151+
for index in range(n, 0, -1):
152+
current_digit = (k - 1) // (factorial // index) + 1
153+
if current_digit:
154+
k = (k - 1) % (factorial // index) + 1
155+
factorial //= index
156+
perm_digits.append(digits.pop(current_digit - 1))
157+
else:
158+
perm_digits += digits
159+
break
160+
161+
return ''.join(perm_digits)

Python/sln_1_100/test_solution_51_60.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,10 @@ def test_lengthOfLastWord(self):
2727
def test_generateMatrix(self):
2828
matrix = self.sln.generateMatrix(3)
2929
self.assertEqual(matrix, [[1, 2, 3], [8, 9, 4], [7, 6, 5]])
30+
31+
def test_getPermutation(self):
32+
self.assertEqual(self.sln.getPermutation(3, 3),'213')
33+
self.assertEqual(self.sln.getPermutation(3, 5),'312')
34+
self.assertEqual(self.sln.getPermutation(1, 1),'1')
35+
self.assertEqual(self.sln.getPermutation(2, 2),'21')
36+
self.assertEqual(self.sln.getPermutation(4, 2),'1243')

0 commit comments

Comments
 (0)