Skip to content

Commit bd71716

Browse files
python: add problem 31 and unittest
1 parent a9793e0 commit bd71716

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

‎Python/sln_1_100/solution_31_40.py

+39
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,37 @@
11
# -*- coding: UTF-8 -*-
2+
from typing import List
3+
24

35
class Solution_31_40:
6+
def nextPermutation(self, nums: List[int]) -> None:
7+
"""
8+
31
9+
Do not return anything, modify nums in-place instead.
10+
"""
11+
if len(nums) <= 1:
12+
return
13+
num_len = len(nums)
14+
if nums[num_len - 2] < nums[num_len - 1]:
15+
nums[num_len - 1], nums[num_len - 2] = nums[num_len - 2], nums[num_len - 1]
16+
else:
17+
start_idx = -1
18+
for idx in range(num_len - 1, 0, -1):
19+
if nums[idx - 1] < nums[idx]:
20+
start_idx = idx - 1
21+
break
22+
if start_idx == -1:
23+
for idx in range(0, num_len // 2):
24+
nums[idx], nums[num_len - 1 - idx] = nums[num_len - 1 - idx], nums[idx]
25+
else:
26+
end_idx = num_len - 1
27+
for idx in range(start_idx + 1, num_len):
28+
if nums[start_idx] >= nums[idx]:
29+
end_idx = idx - 1
30+
break
31+
nums[start_idx], nums[end_idx] = nums[end_idx], nums[start_idx]
32+
for idx in range(start_idx + 1, start_idx + 1 + (num_len - 1 - start_idx) // 2):
33+
nums[idx], nums[num_len + start_idx - idx] = nums[num_len + start_idx - idx], nums[idx]
34+
435
def searchInsert(self, nums, target):
536
"""
637
35
@@ -41,3 +72,11 @@ def countAndSay(self, n):
4172
count = 1
4273
curr += str(count) + say
4374
return curr
75+
76+
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
77+
"""
78+
39
79+
:param candidates:
80+
:param target:
81+
:return:
82+
"""

‎Python/sln_1_100/test_solution_31_40.py

+17
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,23 @@ class TestSolution_31_40(TestCase):
88
def setUp(self):
99
self.sln = Solution_31_40()
1010

11+
def test_nextPermutation(self):
12+
nums1 = [1, 1, 5]
13+
self.sln.nextPermutation(nums1)
14+
assert nums1 == [1, 5, 1]
15+
nums2 = [3, 2, 1]
16+
self.sln.nextPermutation(nums2)
17+
assert nums2 == [1, 2, 3]
18+
nums3 = [1, 3, 2]
19+
self.sln.nextPermutation(nums3)
20+
assert nums3 == [2, 1, 3]
21+
num4 = [1, 5, 1]
22+
self.sln.nextPermutation(num4)
23+
assert num4 == [5, 1, 1]
24+
nums5 = [5, 4, 7, 5, 3, 2]
25+
self.sln.nextPermutation(nums5)
26+
assert nums5 == [5, 5, 2, 3, 4, 7]
27+
1128
def test_searchInsert(self):
1229
ret1 = self.sln.searchInsert([1, 3, 5, 6], 5)
1330
self.assertEqual(ret1, 2)

0 commit comments

Comments
 (0)