code
stringlengths 20
13.2k
| label
stringlengths 21
6.26k
|
---|---|
1 # 213
2
3 class Solution:
4 def rob(self, houses):
5 if not houses:
6 return 0
7
8 # last house is not robbed
9 rob_first = self.helper(houses, 0, len(houses) - 2)
10 # first house is not robbed
11 skip_first = self.helper(houses, 1, len(houses) - 1)
12
13 return max(rob_first, skip_first)
14
15 def helper(self, houses, start, end):
16 if end == start:
17 return houses[start]
18
19 curr, prev = 0, 0
20
21 for i in range(start, end + 1):
22 curr, prev = max(curr, houses[i] + prev), curr
23
24 return curr | Clean Code: No Issues Detected
|
1 #82
2
3 from utils.listNode import ListNode
4
5 class Solution:
6 def remove_duplicates(self, head):
7 if not head:
8 return head
9
10 curr, runner = head, head.next
11
12 while runner:
13 if curr.value != runner.value:
14 curr.next = runner
15 curr = curr.next
16
17 runner = runner.next
18
19 curr.next = None
20 return head
21
22 one = ListNode(1)
23 two = ListNode(1)
24 three = ListNode(3)
25 four = ListNode(3)
26 five = ListNode(4)
27 six = ListNode(4)
28 seven = ListNode(5)
29
30 one.next = two
31 two.next = three
32 three.next = four
33 four.next = five
34 five.next = six
35 six.next = seven
36
37 print(one)
38
39 solution = Solution()
40 print(solution.remove_duplicates(one)) | 5 - refactor: too-few-public-methods
|
1 from utils.interval import Interval
2
3 class Solution:
4 def get_right_intervals(self, intervals):
5 intervals = [(intervals[i], i) for i in range(len(intervals))]
6 # In order to do binary search, the array needs to be sorted
7 # We need to sort by the start because the intervals with a bigger start represent the pool of possibilities
8 intervals.sort(key= lambda x: x[0].start)
9 result = [-1 for _ in range(len(intervals))]
10
11 for index, (interval, i) in enumerate(intervals):
12 left, right = index + 1, len(intervals) # right = len(intervals) means that it is possible to get no right interval
13 while left < right:
14 mid = (left + right) // 2
15 midInterval = intervals[mid][0]
16 if midInterval.start < interval.end:
17 left = mid + 1
18 else:
19 right = mid
20 # left is the index of the right interval
21 if left < len(intervals):
22 result[i] = intervals[left][1]
23
24 return result
25
26 solution = Solution()
27 interval1 = Interval(1, 4)
28 interval2 = Interval(2, 3)
29 interval3 = Interval(3, 4)
30 intervals = [interval1, interval3, interval2]
31 print("intervals = {}".format(intervals))
32 print(solution.get_right_intervals(intervals)) | 4 - warning: redefined-outer-name
3 - refactor: too-few-public-methods
|
1 # 849
2
3 class Solution:
4 def max_distance_to_closest(self, seats):
5 if not seats:
6 return 0
7
8 n = len(seats)
9
10 lefts, rights = [n] * n, [n] * n
11
12 for i in range(len(seats)):
13 if seats[i] == 1:
14 lefts[i] = 0
15 elif i > 0:
16 lefts[i] = 1 + lefts[i - 1]
17
18 for i in range(n - 1, -1, -1):
19 if seats[i] == 1:
20 rights[i] = 0
21 elif i < n - 1:
22 rights[i] = 1 + rights[i + 1]
23
24 return max(min(lefts[i], rights[i]) for i in range(n))
25
26 class Solution2:
27 def max_distance_to_closest(self, seats):
28 if not seats:
29 return 0
30
31 n = len(seats)
32 lefts, rights = [n] * n, [n] * n
33
34 for i in range(n):
35 if seats[i] == 1:
36 lefts[i] = 0
37 elif i > 0:
38 lefts[i] = lefts[i - 1] + 1
39
40 for i in range(n - 1, -1, -1):
41 if seats[i] == 1:
42 rights[i] = 0
43 elif i < n - 1:
44 rights[i] = rights[i + 1] + 1
45
46 return max(min(lefts[i], rights[i]) for i in range(n))
47
48
49
50
51 seats = [1,0,0,0,1,0,1]
52 solution = Solution()
53 print(solution.max_distance_to_closest(seats))
54 [0, 1, 2, 1, 0, 1, 0]
| 4 - warning: redefined-outer-name
3 - refactor: too-few-public-methods
27 - warning: redefined-outer-name
26 - refactor: too-few-public-methods
54 - warning: pointless-statement
|
1 from utils.treeNode import TreeNode
2
3 class Solution:
4 def invert(self, node):
5 if not node:
6 return
7
8 self.invert(node.left)
9 self.invert(node.right)
10
11 node.left, node.right = node.right, node.left
12
13
14 node1 = TreeNode(1)
15 node2 = TreeNode(2)
16 node3 = TreeNode(3)
17 node4 = TreeNode(4)
18 node5 = TreeNode(5)
19 node6 = TreeNode(6)
20 node7 = TreeNode(7)
21
22 node1.left = node2
23 node1.right = node3
24
25 node2.left = node4
26 node2.right = node5
27
28 node3.left = node6
29 node6.left = node7
30
31 print(node1)
32
33 print('=================')
34
35 solution = Solution()
36 solution.invert(node1)
37 print(node1)
| 3 - refactor: too-few-public-methods
|
1 from utils.treeNode import TreeNode
2 from utils.treeUtils import generate_tree
3
4 class Solution:
5 def get_zigzag_level_order(self, node):
6 result = []
7 if not node:
8 return result
9 should_reverse = False
10 level_nodes = [node]
11
12 while level_nodes:
13 result.append([])
14 new_level_nodes = []
15
16 for node in level_nodes:
17 result[-1].append(node.value)
18
19 if node.left:
20 new_level_nodes.append(node.left)
21 if node.right:
22 new_level_nodes.append(node.right)
23
24 level_nodes = new_level_nodes
25
26 if should_reverse:
27 result[-1] = result[-1][::-1]
28 should_reverse = not should_reverse
29
30 return result
31
32 root = generate_tree()
33 print(root)
34 solution = Solution()
35 print(solution.get_zigzag_level_order(root)) | 16 - refactor: redefined-argument-from-local
4 - refactor: too-few-public-methods
1 - warning: unused-import
|
1 from utils.listNode import ListNode
2
3 class Solution:
4 # time: O(N)
5 # space: O(1)
6 def partition(self, head, pivot):
7 if not head:
8 return head
9
10 s_head = smaller = ListNode(None)
11 g_head = greater = ListNode(None)
12 node = head
13
14 while node:
15 if node.value < pivot:
16 smaller.next = node
17 smaller = node
18 else:
19 greater.next = node
20 greater = node
21
22 node = node.next
23
24 greater.next = None
25 smaller.next = g_head.next
26
27 return s_head.next
28
29 one = ListNode(1)
30 two = ListNode(4)
31 three = ListNode(3)
32 four = ListNode(2)
33 five = ListNode(5)
34 six = ListNode(2)
35
36 one.next = two
37 two.next = three
38 three.next = four
39 four.next = five
40 five.next = six
41
42 print(one)
43
44 solution = Solution()
45 print(solution.partition(one, 3)) | 3 - refactor: too-few-public-methods
|
1 from utils.listNode import ListNode
2
3 class Solution:
4 def reverse(self, head):
5 rev = None
6
7 while head:
8 rev, rev.next, head = head, rev, head.next
9
10 return rev
11
12 def reverse2(self, head):
13 rev = None
14
15 while head:
16 next = head.next
17 head.next = rev
18 rev = head
19 head = next
20
21 return rev
22
23
24
25
26
27
28
29
30 one = ListNode(1)
31 two = ListNode(2)
32 three = ListNode(3)
33 four = ListNode(4)
34 five = ListNode(5)
35 six = ListNode(6)
36 seven = ListNode(7)
37
38 one.next = two
39 two.next = three
40 three.next = four
41 four.next = five
42 five.next = six
43 six.next = seven
44
45 print(one)
46 solution = Solution()
47 print(solution.reverse2(one))
| 16 - warning: redefined-builtin
|
1 import unittest
2
3 class Solution:
4 def get_longest_common_sequence(self, str1, str2):
5 if not str1 or not str2:
6 return ''
7
8 max_length = float('-inf')
9
10 num_rows, num_cols = len(str2) + 1, len(str1) + 1
11 T = [[0 for _ in range(num_cols)] for _ in range(num_rows)]
12
13 for i in range(1, num_rows):
14 for j in range(1, num_cols):
15 if str2[i - 1] != str1[j - 1]:
16 # if the sequences do not need to be contigious
17 T[i][j] = max(T[i - 1][j], T[i][j - 1])
18 # if the sequence need to be contiguous
19 T[i][j] = 0
20 else:
21 T[i][j] = T[i - 1][j - 1] + 1
22 # to get the max length of the contiguous common sequence
23 max_length = max(max_length, T[i][j])
24
25 result = ''
26 i = num_rows - 1
27 j = num_cols - 1
28
29 while T[i][j]:
30 if T[i][j] == T[i - 1][j]:
31 i -= 1
32 elif T[i][j] == T[i][j - 1]:
33 j -= 1
34 elif T[i][j] == T[i - 1][j - 1] + 1:
35 result += str2[i - 1]
36 i -= 1
37 j -= 1
38 else:
39 raise Exception('Error constructing table')
40
41 return result[::-1]
42
43
44 class Test(unittest.TestCase):
45 def test_longest_common_subsequence(self):
46 solution = Solution()
47 str1 = 'ABCDEFGHIJ'
48 str2 = 'FOOBCDBCDEG'
49 expected = 'BCDEG'
50 actual = solution.get_longest_common_sequence(str1, str2)
51 self.assertEqual(expected, actual)
52 print('Success!')
53
54 def main():
55 test = Test()
56 test.test_longest_common_subsequence()
57
58 if __name__ == '__main__':
59 main() | 4 - warning: bad-indentation
6 - warning: bad-indentation
39 - warning: broad-exception-raised
3 - refactor: too-few-public-methods
|
1 class Solution:
2 def can_jump(self, nums):
3 last = len(nums) - 1
4 for i in range(last - 1, -1, -1):
5 if i + nums[i] >= last:
6 last = i
7
8 return last == 0
9
10 def can_jump2(self, nums):
11 max_reached = 0
12 stack = [0]
13 while stack:
14 index = stack.pop()
15 if index + nums[index] > max_reached:
16 if index + nums[index] >= len(nums) - 1:
17 return True
18
19 for i in range(max_reached + 1, index + nums[index] + 1):
20 stack.append(i)
21
22 max_reached = index + nums[index]
23
24 return False
25
26 nums = [2,3,1,0,4]
27 # nums = [3, 2, 1, 0, 4]
28 solution = Solution()
29 print(solution.can_jump2(nums)) | 2 - warning: redefined-outer-name
10 - warning: redefined-outer-name
|
1 #654
2
3 from utils.treeNode import TreeNode
4
5 class Solution:
6 def build_maximum_tree(self, nums):
7 if not nums:
8 return None
9
10 return self.helper(nums, 0, len(nums) - 1)
11
12 def helper(self, nums, start, end):
13 if start > end:
14 return None
15
16 max_num, index = float('-inf'), -1
17 for i, num in enumerate(nums[start: end + 1]):
18 if num > max_num:
19 max_num, index = num, i + start
20
21 root = TreeNode(max_num)
22 root.left = self.helper(nums, start, index - 1)
23 root.right = self.helper(nums, index + 1, end)
24
25 return root
26
27 nums = [3,2,1,6,0,5]
28 solution = Solution()
29 print(solution.build_maximum_tree(nums)) | 6 - warning: redefined-outer-name
12 - warning: redefined-outer-name
|
1 class Solution:
2 def get_summary_ranges(self, nums):
3 result = []
4 for i, num in enumerate(nums):
5 if not result or nums[i] > nums[i - 1] + 1:
6 result.append(str(num))
7 else:
8 start = result[-1].split(' -> ')[0]
9 result[-1] = ' -> '.join([start, str(num)])
10 return result
11
12 solution = Solution()
13 nums = [0, 1, 2, 4, 5, 7]
14 print(solution.get_summary_ranges(nums)) | 2 - warning: redefined-outer-name
1 - refactor: too-few-public-methods
|
1 class Solution:
2 def get_interesection(self, nums1, nums2):
3 set1 = set(nums1)
4 intersection = set()
5 for num in nums2:
6 if num in set1:
7 intersection.add(num)
8 return list(intersection)
9
10 | 1 - refactor: too-few-public-methods
|
1 class Solution(object):
2 # O(n) time and space
3 def basic_calculator(self, expression):
4 if not expression:
5 return
6
7 stack = []
8 num = 0
9 operation = '+'
10
11 for i, c in enumerate(expression):
12 if c.isdigit():
13 num = num * 10 + int(c)
14
15 if i == len(expression) - 1 or (not c.isdigit() and c != ' '): # c is operator or end of string
16 if operation == '+':
17 stack.append(num)
18 elif operation == '-':
19 stack.append(-num)
20 elif operation == '*':
21 stack.append(stack.pop() * num)
22 elif operation == '/':
23 left = stack.pop()
24 stack.append(left // num)
25 if left // num < 0 and left % num != 0:
26 stack[-1] += 1 # negative integer division result with remainder rounds down by default
27
28 num = 0 # num has been used, so reset
29 operation = c
30
31 return sum(stack)
32
33 solution = Solution()
34 print(solution.basic_calculator('1 + 2 * 3 - 4')) | 1 - refactor: useless-object-inheritance
3 - refactor: inconsistent-return-statements
1 - refactor: too-few-public-methods
|
1 class Solution:
2 def get_unique_bst_count(self, n):
3 if n <= 0:
4 return 0
5
6 return self.get_unique_bst_count_rec(1, n)
7
8 def get_unique_bst_count_rec(self, start, end):
9 if start >= end:
10 return 1
11
12 result = 0
13 for i in range(start, end + 1):
14 left_count = self.get_unique_bst_count_rec(start, i - 1)
15 right_count = self.get_unique_bst_count_rec(i + 1, end)
16 result += left_count * right_count
17
18 return result
19
20 def get_unique_bst_count2(self, n):
21 memo = [-1 for _ in range(n + 1)]
22 memo[0], memo[1] = 1, 1
23
24 return self.helper(n, memo)
25
26 def helper(self, n, memo):
27 if memo[n] != -1:
28 return memo[n]
29
30 count = 0
31 for i in range(n):
32 # how many ways can i distribute n - 1 nodes between left and right
33 count += self.helper(i, memo) * self.helper(n - 1 - i, memo)
34
35 return count
36
37
38 solution = Solution()
39 print(solution.get_unique_bst_count2(3)) | Clean Code: No Issues Detected
|
1 class Solution(object):
2 def contains_duplicates(self, numbers):
3 number_set = set(numbers)
4 return len(numbers) != len(number_set)
5
6 def contains_duplicates2(self, numbers):
7 """
8 :type numbers: list
9 :rtype : Boolean
10 """
11
12 numbers.sort()
13 for i in range(1, len(numbers)):
14 if numbers[i] == numbers[i - 1]:
15 return True
16
17 return False
18
19 numbers = [1, 2, 1, 4]
20 solution = Solution()
21 print(solution.contains_duplicates(numbers))
| 1 - refactor: useless-object-inheritance
2 - warning: redefined-outer-name
6 - warning: redefined-outer-name
|
1 class Solution:
2 def get_minimum(self, nums):
3 left, right = 0, len(nums) - 1
4 while left < right:
5 if nums[left] <= nums[right]: # sorted array, return nums[left]
6 break
7 mid = (left + right) // 2
8 if nums[mid] < nums[left]: # min is either mid the left side of mid
9 right = mid
10 else: # nums[mid] >= nums[left] > num[right] => mid is not min
11 left = mid + 1
12 return nums[left]
13
14 solution = Solution()
15 # nums = [3, 4, 5, 6, 7, 1, 2]
16 # nums = [1, 2, 3, 4, 5, 6]
17 nums = [7, 8, 1, 2, 3, 4, 5, 6]
18 print(solution.get_minimum(nums)) | 2 - warning: redefined-outer-name
1 - refactor: too-few-public-methods
|
1 #19
2
3 from utils.listNode import ListNode
4
5 class Solution:
6 def delete_from_end(self, head, n):
7 if not head:
8 return
9
10 front, back = head, head
11
12 dummy = prev = ListNode(None)
13
14 while n > 0:
15 back = back.next
16 n -= 1
17
18 while back:
19 back = back.next
20 prev.next = front
21 prev = front
22 front = front.next
23
24 # front is the node I need to delete, and prev is right behind it
25
26 prev.next = prev.next.next
27
28 return dummy.next
29
30 class Solution2:
31 def delete_from_end(self, head, n):
32 first, second = head, head
33
34 for _ in range(n):
35 first = first.next
36
37 if not first: # n is the length of the linked list. the first element needs to be removed
38 return head.next
39
40 while first.next:
41 first = first.next
42 second = second.next
43
44 # second is right before the nth element from the end
45 second.next = second.next.next
46
47 return head
48
49 one = ListNode(1)
50 two = ListNode(2)
51 three = ListNode(3)
52 four = ListNode(4)
53 five = ListNode(5)
54
55 one.next = two
56 two.next = three
57 three.next = four
58 four.next = five
59
60 print(one)
61
62 solution = Solution()
63 print(solution.delete_from_end(one, 2)) | 6 - refactor: inconsistent-return-statements
5 - refactor: too-few-public-methods
30 - refactor: too-few-public-methods
|
1 # 561
2
3 class Solution:
4 def partition(self, nums):
5 result = 0
6
7 if not nums:
8 return result
9
10 nums.sort()
11
12 for i in range(0, len(nums), 2):
13 result += nums[i]
14
15 return result
16
17 class Solution2:
18 def partition(self, nums):
19 return sum(sorted(nums)[::2])
20
21 solution = Solution2()
22 nums = [1,4, 3, 2]
23 print(solution.partition(nums)) | 4 - warning: redefined-outer-name
3 - refactor: too-few-public-methods
18 - warning: redefined-outer-name
17 - refactor: too-few-public-methods
|
1 class Solution:
2 def connect(self, node):
3 if not node:
4 return
5
6 level = [node]
7
8 while level:
9 prev = None
10 next_level = []
11
12 for node in level:
13 if prev:
14 prev.next = node
15
16 prev = node
17
18 if node.left:
19 next_level.append(node.left)
20 if node.right:
21 next_level.append(node.right)
22
23 level = next_level
24 | 12 - refactor: redefined-argument-from-local
1 - refactor: too-few-public-methods
|
1 import unittest
2
3 class Solution(object):
4 def compare_versions(self, version1, version2):
5 """
6 :type version1: str
7 :type version2: str
8 :rtype: int
9 """
10
11 if not version1 or not version2:
12 return None
13
14 digits1 = list(map(int, version1.split('.')))
15 digits2 = list(map(int, version2.split('.')))
16
17 for i in range(max(len(digits1), len(digits2))):
18 v1 = digits1[i] if i < len(digits1) else 0
19 v2 = digits2[i] if i < len(digits2) else 0
20
21 if v1 < v2:
22 return -1
23 if v1 > v2:
24 return 1
25
26 return 0
27
28 class Test(unittest.TestCase):
29 data = [('1.2.3', '1.2.1', 1), ('1.2', '1.2.4', -1), ('1', '1.0.0', 0)]
30
31 def test_compare_versions(self):
32 solution = Solution()
33 for test_data in self.data:
34 actual = solution.compare_versions(test_data[0], test_data[1])
35 self.assertEqual(actual, test_data[2])
36
37 if __name__ == '__main__':
38 unittest.main() | 3 - refactor: useless-object-inheritance
3 - refactor: too-few-public-methods
|
1 import unittest
2
3 class Solution(object):
4 def time_conversion(self, time_str):
5 if not time_str:
6 return None
7
8 time_list = list(time_str)
9 is_pm = time_list[-2].lower() == 'p'
10
11 # handle the 12 AM case. It should be converted to 00
12 if not is_pm and time_str[:2] == '12':
13 time_list[:2] = ['0', '0']
14 elif is_pm:
15 hour = str(int(time_str[:2]) + 12)
16 time_list[:2] = list(hour)
17
18 return ''.join(map(str, time_list[:-2]))
19
20 class Test(unittest.TestCase):
21 test_data = [('03:22:22PM', '15:22:22'), ('12:22:22AM', '00:22:22')]
22 def test_time_conversion(self):
23 solution = Solution()
24
25 for data in self.test_data:
26 actual = solution.time_conversion(data[0])
27 self.assertEqual(actual, data[1])
28
29 if __name__ == '__main__':
30 unittest.main() | 3 - refactor: useless-object-inheritance
3 - refactor: too-few-public-methods
|
1 # 328
2
3 from utils.listNode import ListNode
4
5 class Solution:
6 def odd_even_list(self, head):
7 if not head:
8 return None
9
10 odd = head
11 even_head, even = head.next, head.next
12
13 while even and even.next:
14 odd.next = even.next
15 odd = odd.next
16 even.next = odd.next
17 even = even.next
18
19 odd.next = even_head
20
21 return head
22
23
24 class Solution2:
25 def odd_even_list(self, head):
26 if not head:
27 return None
28
29 odd_head = odd_tail = ListNode(None)
30 even_head = even_tail = ListNode(None)
31
32 node = head
33 count = 1
34
35 while node:
36 if count == 1:
37 odd_tail.next = node
38 odd_tail = odd_tail.next
39 else:
40 even_tail.next = node
41 even_tail = even_tail.next
42
43 count = 1 - count
44 node = node.next
45
46 even_tail.next = None
47 odd_tail.next = even_head.next
48
49 return odd_head.next
50
51 one = ListNode(1)
52 two = ListNode(2)
53 three = ListNode(3)
54 four = ListNode(4)
55 five = ListNode(5)
56
57 one.next = two
58 two.next = three
59 three.next = four
60 four.next = five
61
62 print(one)
63
64 solution = Solution()
65 print(solution.odd_even_list(one)) | 5 - refactor: too-few-public-methods
24 - refactor: too-few-public-methods
|
1 class Solution:
2 def has_increasing_subsequence(self, nums):
3 smallest, next_smallest = float('inf'), float('inf')
4 for num in nums:
5 # if num <= smallest:
6 # smallest = num
7 # elif num <= next_smallest:
8 # next_smallest = num
9 # else:
10 # return True
11 # A second way of doing the same
12 smallest = min(smallest, num)
13 if smallest < num:
14 next_smallest = min(next_smallest, min)
15 if next_smallest < num:
16 return True
17 return False | 1 - refactor: too-few-public-methods
|
1 from utils.matrix import Matrix
2
3 class Solution:
4 def min_path_sum(self, matrix):
5 row_count, col_count = matrix.row_count, matrix.col_count
6
7 if not row_count or not col_count:
8 return 0
9
10 sum_row = [float('inf') for _ in range(col_count + 1)]
11 sum_row[1] = 0
12
13 for row in range(1, row_count + 1):
14 new_sum_row = [float('inf') for _ in range(col_count + 1)]
15 for col in range(1, col_count + 1):
16 new_sum_row[col] = matrix[row - 1][col - 1] + min(new_sum_row[col - 1], sum_row[col])
17 sum_row = new_sum_row
18
19 return sum_row[-1]
20
21 matrix = Matrix([[5,2,8],[6,1,0],[3,3,7]])
22 print(matrix)
23 solution = Solution()
24 print(solution.min_path_sum(matrix))
25
| 4 - warning: redefined-outer-name
3 - refactor: too-few-public-methods
|
1 # 565
2
3 class Solution:
4 def array_nesting(self, nums):
5 result = 0
6 if not nums:
7 return result
8
9 for i in range(len(nums)):
10 if nums[i] == float('inf'):
11 continue
12
13 start, count = i, 0
14 while nums[start] != float('inf'):
15 temp = start
16 start = nums[start]
17 nums[temp] = float('inf')
18 count += 1
19
20 result = max(result, count)
21
22 return result
| 3 - refactor: too-few-public-methods
|
1 from collections import defaultdict
2
3 # Gotcha 1: there is no sort for strings.
4 # You have to convert the word to a list, then sort it using list.sort(),
5 # then reconstruct the string using ''.join(sorted_list)
6
7 # Gotcha 2: defaultdict is part of the collections library
8
9 class Solution(object):
10 # Time: O(n * k * log k) where n is the number of words, and k is the length of the longest word
11 # Space: O(n * k) to hold the result - k * n is the total number of characters
12 def group_anagrams(self, words):
13 """
14 :type words: List[str]
15 :rtype: List[List[str]]
16 """
17
18 sorted_dict = defaultdict(list)
19
20 for word in words:
21 letter_list = list(word) # or [c for c in word]
22 letter_list.sort()
23 sorted_word = ''.join(letter_list)
24 sorted_dict[sorted_word].append(word)
25
26 return list(sorted_dict.values())
27
28 solution = Solution()
29 print(solution.group_anagrams(['bat', 'car', 'atb', 'rca', 'aaa'])) | 9 - refactor: useless-object-inheritance
9 - refactor: too-few-public-methods
|
1 class Solution:
2 def get_major(self, nums):
3 candidate1, candidate2 = None, None
4 count1, count2 = 0, 0
5
6 for num in nums:
7 if num == candidate1:
8 count1 += 1
9 elif num == candidate2:
10 count2 += 1
11 elif count1 == 0:
12 candidate1 = num
13 count1 = 1
14 elif count2 == 0:
15 candidate2 = num
16 count2 = 1
17 else:
18 count1 -= 1
19 count2 -= 1
20
21 return [candidate for candidate in [candidate1, candidate2] if nums.count(candidate) > len(nums) // 3]
22
23 solution = Solution()
24 nums = [1,2,3,2,2,1,3,1,2,1]
25 print(solution.get_major(nums)) | 2 - warning: redefined-outer-name
1 - refactor: too-few-public-methods
|
1 def countAndSay(n):
2 result = '1'
3 for _ in range(n - 1):
4 count, last = 0, None
5 newString = ''
6
7 for digit in result:
8 if last is None or digit == last:
9 count += 1
10 last = digit
11 else:
12 newString += str(count) + last
13 last = digit
14 count = 1
15
16 newString += str(count) + last
17 result = newString
18
19 return result
20
21 # Time: O(2 ^ n) because the sequence at worst double during each iteration
22 # Space: O(2 ^ n)
23 def countAndSay2 (n):
24 sequence = [1]
25 for _ in range(n - 1):
26 next = []
27 for digit in sequence:
28 if not next or next[-1] != digit:
29 next += [1, digit]
30 else:
31 next[-2] = next[-2] + 1
32 sequence = next
33
34 return ''.join(map(str, sequence))
| 26 - warning: redefined-builtin
|
1 import unittest
2
3 # Time: O(N) - Space: O(N)
4 class Solution(object):
5 def super_reduced_string(self, str):
6 res = []
7 for c in str:
8 if res and res[-1] == c:
9 res.pop()
10 else:
11 res.append(c)
12
13 return ''.join(res)
14
15
16 class Test(unittest.TestCase):
17 test_data = [('aaabccbddd', 'ad')]
18
19 def test_super_reduced_string(self):
20 solution = Solution()
21 for data in self.test_data:
22 actual = solution.super_reduced_string(data[0])
23 self.assertEqual(actual, data[1])
24
25 if __name__ == '__main__':
26 unittest.main() | 4 - refactor: useless-object-inheritance
5 - warning: redefined-builtin
4 - refactor: too-few-public-methods
|
1 class Solution:
2 def get_stack_count(self, n):
3 stack_count = 0
4 if n == 0:
5 return stack_count
6
7 remain = n
8 while remain >= stack_count + 1:
9 stack_count += 1
10 remain -= stack_count
11
12 return stack_count
13
14 def get_stack_count2(self, n):
15 if n == 0:
16 return 0
17
18 left, right = 1, n
19 while left <= right:
20 mid = (left + right) // 2
21 s = mid * (mid + 1) // 2
22 if s > n:
23 right = mid - 1
24 else:
25 left = mid + 1
26
27 return left - 1
28
29 solution = Solution()
30 print("n = {} : stack_count = {}".format(5, solution.get_stack_count2(5)))
31 print("n = {} : stack_count = {}".format(6, solution.get_stack_count2(6)))
32 print("n = {} : stack_count = {}".format(8, solution.get_stack_count2(8)))
33 print("n = {} : stack_count = {}".format(9, solution.get_stack_count2(9))) | Clean Code: No Issues Detected
|
1 import random
2
3 class Solution:
4 def __init__(self, nums):
5 self.original = nums
6
7 # def shuffle(self):
8 # shuffled = []
9 # copy = list(self.original)
10 # for i in range(len(copy) - 1, -1, -1):
11 # index = random.randint(0, i)
12 # shuffled.append(copy[index])
13 # copy[index] = copy[-1]
14 # copy.pop()
15 # return shuffled
16
17 def shuffle(self):
18 shuffled = list(self.original)
19 for i in range(len(shuffled)):
20 swap = random.randint(i, len(shuffled) - 1)
21 shuffled[i], shuffled[swap] = shuffled[swap], shuffled[i]
22 return shuffled
23
24 def restore(self):
25 return self.original
26
27 nums = [1,2,3,4]
28 solution = Solution(nums)
29 print(solution.shuffle())
30 print(solution.shuffle())
31 print(solution.restore()) | 4 - warning: redefined-outer-name
|
1 # 203
2
3 from utils.listNode import ListNode
4
5 class Solution:
6 def remove_element(self, head, target):
7 if not head:
8 return
9
10 dummy, prev = ListNode(None), ListNode(None)
11
12 dummy.next = head
13 prev = dummy
14
15 while head:
16 if head.value == target:
17 prev.next = head.next
18 else:
19 prev = head
20
21 head = head.next
22
23 return dummy.next
24
25 one = ListNode(6)
26 two = ListNode(2)
27 three = ListNode(6)
28 four = ListNode(3)
29 five = ListNode(4)
30 six = ListNode(5)
31 seven = ListNode(6)
32
33 one.next = two
34 two.next = three
35 three.next = four
36 four.next = five
37 five.next = six
38 six.next = seven
39
40 print(one)
41 # solution = Solution()
42 # print(solution.remove_element(one, 6)) | 6 - refactor: inconsistent-return-statements
5 - refactor: too-few-public-methods
|
1 class Solution:
2 def get_first_bad_version(self, n):
3 left, right = 1, n
4 while left < right:
5 mid = (left + right) // 2
6 if not self.is_bad(mid):
7 left = mid + 1 # this will avoid an infinite loop, because left <= mid < right
8 else:
9 right = mid
10
11 return left
12
13 def get_first_bad_version2(self, n):
14 left, right = 1, n
15 while left <= right:
16 mid = (left + right) // 2
17 if self.is_bad(mid):
18 right = mid - 1
19 else:
20 left = mid + 1
21
22 return left
23
24 def is_bad(self, n):
25 return n >= 4
26
27 solution = Solution()
28 print(solution.get_first_bad_version2(8)) | Clean Code: No Issues Detected
|
1 # 309
2
3 class Solution:
4 def get_max_profit(self, prices):
5 buy, sell, prev_sell = float('-inf'), 0, 0
6
7 for price in prices:
8 sell, prev_sell = max(prev_sell, buy + price), sell
9 buy = max(buy, prev_sell - price)
10
11 return sell
| 3 - refactor: too-few-public-methods
|
1 from utils.listNode import ListNode
2
3 class Solution:
4 def merge(self, l1, l2):
5 if not l1 or not l2:
6 return l1 or l2
7
8 node1, node2 = l1, l2
9 head = None
10 curr = None
11
12 while node1 and node2:
13 min_value = min(node1.value, node2.value)
14
15 if min_value == node1.value:
16 node1 = node1.next
17 else:
18 node2 = node2.next
19
20 if not head:
21 head = ListNode(min_value)
22 curr = head
23 else:
24 curr.next = ListNode(min_value)
25 curr = curr.next
26
27 if node1:
28 curr.next = node1
29 elif node2:
30 curr.next = node2
31
32 return head
33
34 # time: O(m + n)
35 # space: O(1)
36 class Solution2:
37 def merge(self, l1, l2):
38 prev = dummy = ListNode(None)
39
40 while l1 and l2:
41 if l1.value < l2.value:
42 prev.next = l1
43 l1 = l1.next
44 else:
45 prev.next = l2
46 l2 = l2.next
47
48 prev = prev.next
49
50 prev.next = l1 or l2
51
52 return dummy.next
53
54 one = ListNode(1)
55 two = ListNode(2)
56 four = ListNode(4)
57
58 one.next = two
59 two.next = four
60
61 one_ = ListNode(1)
62 three_ = ListNode(3)
63 four_ = ListNode(4)
64
65 one_.next = three_
66 three_.next = four_
67
68 print(one)
69 print(one_)
70
71 solution = Solution2()
72 print(solution.merge(one, one_)) | 3 - refactor: too-few-public-methods
36 - refactor: too-few-public-methods
|
1 # 515
2
3 from utils.treeNode import TreeNode
4
5 # time: O(N)
6 # space: O(N)
7 class Solution:
8 def max_rows(self, root):
9 result = []
10 if not root:
11 return result
12
13 self.traverse(root, 0, result)
14
15 return result
16
17 def traverse(self, root, level, result):
18 if not root:
19 return
20
21 if len(result) == level:
22 result.append(root.value)
23 else:
24 result[level] = max(result[level], root.value)
25
26 self.traverse(root.left, level + 1, result)
27 self.traverse(root.right, level + 1, result)
28
29 # time: O(N)
30 # space: O(N)
31 class Solution2:
32 def max_rows(self, root):
33 result = []
34 if not root:
35 return result
36
37 level = [root]
38 while level:
39 new_level = []
40 max_value = max(map(lambda node: node.value, level))
41 result.append(max_value)
42
43 for node in level:
44 if node.left:
45 new_level.append(node.left)
46
47 if node.right:
48 new_level.append(node.right)
49
50 level = new_level
51
52 return result
53
54
55
56 one = TreeNode(1)
57 two = TreeNode(2)
58 three = TreeNode(3)
59 four = TreeNode(4)
60 five = TreeNode(5)
61 six = TreeNode(6)
62 seven = TreeNode(7)
63
64 one.left = five
65 five.left = three
66 five.right = four
67 one.right = two
68 two.right = six
69 six.right = seven
70
71 print(one)
72 print('===========')
73 solution = Solution2()
74 print(solution.max_rows(one)) | 31 - refactor: too-few-public-methods
|
1 class Solution(object):
2 def add_one(self, arr):
3 """
4 :type arr: list[int]
5 :rtype: list[int]
6 """
7 sum = 0
8 carry = 1
9 arr.reverse()
10
11 for i, c in enumerate(arr):
12 sum = c + carry
13 arr[i] = sum % 10
14 carry = sum // 10
15
16 if carry == 1:
17 arr.append(1)
18
19 arr.reverse()
20 return arr
21
22 def add_one2(self, digits):
23 """
24 :type digits: list[int]
25 :rtype: list[int]
26 """
27 i = len(digits) - 1
28 while i >= 0 and digits[i] == 9:
29 digits[i] = 0
30 i -= 1
31
32 if i == -1:
33 return [1] + digits
34
35 return digits[:i] + [digits[i] + 1] + digits[i + 1 :]
36
37 solution = Solution()
38 print(solution.add_one2([9, 8, 9])) | 1 - refactor: useless-object-inheritance
7 - warning: redefined-builtin
|
1 # 147
2
3 from utils.listNode import ListNode
4
5 # time: O(N ** 2)
6 # space: O(1)
7 class Solution:
8 def insert_sort_list(self, head):
9 sorted_tail = dummy = ListNode(float('-inf'))
10 dummy.next = head
11
12 while sorted_tail.next:
13 node = sorted_tail.next
14
15 if node.value >= sorted_tail.value:
16 sorted_tail = sorted_tail.next
17 continue
18
19 sorted_tail.next = node.next
20
21 insertion = dummy
22 while insertion.next.value <= node.value:
23 insertion = insertion.next
24
25 node.next = insertion.next
26 insertion.next = node
27
28 return dummy.next
29
30 one = ListNode(1)
31 two = ListNode(2)
32 three = ListNode(3)
33 four = ListNode(4)
34
35 one.next = two
36 two.next = three
37 three.next = four
38
39 print(one)
40
41 solution = Solution()
42 print(solution.insert_sort_list(one)) | 7 - refactor: too-few-public-methods
|
1 from collections import defaultdict
2 from string import ascii_lowercase
3
4 class Solution(object):
5 # Time: O(n * k * k) to build the graph. n = # of words. k = max number of character in a word
6 # O(b ^ (d/2)) to perform a bidrectional BFS search, where b is the branching factor ( the average number of children(neighbors) at each node),
7 # and d is the depth
8 # Space: O(n * k)
9
10 def word_ladder(self, start_word, end_word, word_list):
11 """
12 :type start_word: str
13 :type end_word: str:
14 :type word_list: Set[str]
15 :rtye: int
16 """
17
18 if not start_word or not end_word or not word_list:
19 return 0
20
21 word_list.add(end_word)
22
23 graph = self.build_graph(word_list)
24
25 visited = set()
26 length = 0
27 front, back = {start_word}, {end_word}
28
29 while front:
30 if front & back:
31 return length
32
33 new_front = set()
34 for word in front:
35 visited.add(word)
36 for i in range(len(word)):
37 wildcard = word[:i] + '-' + word[i + 1 :]
38 new_words = graph[wildcard]
39 new_words -= visited
40 new_front |= new_words
41
42 front = new_front
43 length += 1
44
45 if len(back) < len(front):
46 front, back = back, front
47
48 return 0
49
50 def build_graph(self, word_list):
51 """
52 :type word_list: Set[str]
53 :rtype: defaultdict
54 """
55
56 graph = defaultdict(set)
57 for word in word_list:
58 for i in range(len(word)):
59 wildcard = word[:i] + '-' + word[i + 1 :]
60 graph[wildcard].add(word)
61
62 return graph | 4 - refactor: useless-object-inheritance
2 - warning: unused-import
|
1 from utils.listNode import ListNode
2
3 class Solution:
4 def has_cycle(self, head):
5 if not head or not head.next:
6 return False
7
8 slow, fast = head.next, head.next.next
9
10 while fast and fast.next:
11 if fast == slow:
12 return True
13
14 slow = slow.next
15 fast = fast.next.next
16
17 return False
18
19
20 one = ListNode(1)
21 two = ListNode(2)
22 three = ListNode(3)
23 four = ListNode(4)
24 five = ListNode(5)
25 six = ListNode(6)
26 seven = ListNode(7)
27
28 one.next = two
29 two.next = three
30 three.next = four
31 four.next = five
32 five.next = six
33 six.next = three
34
35 solution = Solution()
36 print(solution.has_cycle(one)) | 3 - refactor: too-few-public-methods
|
1 from utils.treeNode import TreeNode
2
3 class Solution:
4 #O(N) time and space
5 def is_balanced(self, root):
6 return self.absHeight(root) != -1
7
8 def absHeight(self, root):
9 if not root:
10 return 0
11
12 left_height = self.absHeight(root.left)
13 right_height = self.absHeight(root.right)
14
15 if left_height == -1 or right_height == -1 or abs(left_height - right_height) > 1:
16 return -1
17
18 return 1 + max(left_height, right_height)
19
20
| 1 - warning: unused-import
|
1 from utils.matrix import Matrix
2
3 class Solution:
4 # O(m * n * min(m, n)) time and O(1) space
5 def get_max_square(self, matrix):
6 """
7 :type matrix: Matrix
8 :rtype: int
9 """
10 max_area = 0
11 for row in range(1, matrix.row_count):
12 for col in range(1, matrix.col_count):
13 if matrix[row][col] == 0:
14 continue
15
16 max_length = matrix[row - 1][col - 1]
17 length = 1
18 while length <= max_length:
19 if matrix[row - length][col] == 0 or matrix[row][col - 1] == 0 or matrix[row - 1][col - 1] == 0:
20 break
21 length += 1
22 matrix[row][col] = length ** 2
23 max_area = max(max_area, matrix[row][col])
24
25 return max_area
26
27 # dynamic programming: changing the matrix itself
28 def get_max_square2(self, matrix):
29 """
30 :type matrix: Matrix
31 :rtype: int
32 """
33 max_side = 0
34 if not matrix or not matrix.row_count or not matrix.col_count:
35 return max_side
36
37 for row in range(1, matrix.row_count):
38 for col in range(1, matrix.col_count):
39 if matrix[row][col] == 0:
40 continue
41
42 matrix[row][col] = 1 + min(matrix[row - 1][col], matrix[row][col - 1], matrix[row - 1][col - 1])
43 max_side = max(max_side, matrix[row][col])
44
45 return max_side ** 2
46
47 # dynamic programming: keeping an array of longest square sides
48 def get_max_square3(self, matrix):
49 """
50 :type matrix: Matrix
51 :rtype: int
52 """
53 max_side = 0
54 if not matrix or not matrix.row_count or not matrix.col_count:
55 return max_side
56
57 max_sides = [0 for _ in range(matrix.col_count)]
58
59 for row in range(matrix.row_count):
60 new_max_sides = [matrix[row][0]] + [0 for _ in range(1, matrix.col_count)]
61 max_side = max(max_side, matrix[row][0])
62
63 for col in range(1, matrix.col_count):
64 if matrix[row][col] == 0:
65 continue
66
67 new_max_sides[col] = 1 + min(new_max_sides[col - 1], max_sides[col], max_sides[col - 1])
68 max_side = max(max_side, new_max_sides[col])
69
70 max_sides = new_max_sides
71
72 return max_side ** 2
73
74
75 matrix = Matrix([[1, 0, 1, 0, 0], [1, 0, 1, 1, 1], [1, 1, 1, 1, 1], [1, 0, 0, 1, 0]])
76 print(matrix)
77 print('===============')
78 solution = Solution()
79 print(solution.get_max_square3(matrix)) | 5 - warning: redefined-outer-name
28 - warning: redefined-outer-name
48 - warning: redefined-outer-name
|
1 class Solution:
2 def spiral(self, matrix):
3 rows_count = len(matrix[0])
4 cols_count = len(matrix)
5 row, col = 0, -1
6 d_row, d_col = 0, 1
7 row_leg, col_leg = rows_count, cols_count - 1
8 leg_count = 0
9 spiral = []
10
11 for _ in range(rows_count * cols_count):
12 row += d_row
13 col += d_col
14 spiral.append(matrix[row][col])
15 leg_count += 1
16
17 if (d_row == 0 and leg_count == row_leg) or (d_col == 0 and leg_count == col_leg):
18 # change direction
19 # decrease the right leg (possible number of moves through the axis)
20 if d_row == 0:
21 row_leg -= 1
22 else:
23 col_leg -= 1
24
25 # get the new direction
26 d_row, d_col = d_col, - d_row
27 leg_count = 0
28
29 return spiral
30
31 def print_matrix(self, matrix):
32 for row in matrix:
33 print(row)
34
35 solution = Solution()
36 matrix = [[1,2,3],[5,6,7],[9,10,11],[13,14,15]]
37 solution.print_matrix(matrix)
38 print(solution.spiral(matrix))
39
40
| 2 - warning: redefined-outer-name
31 - warning: redefined-outer-name
|
1 class Solution:
2 def get_unique_count(self, n):
3 if n == 0:
4 return 1
5 res = 10
6 available_numbers = 9
7
8 for digit in range(2, min(n, 10) + 1):
9 available_numbers *= 11 - digit
10 res += available_numbers
11
12 return res
13
14 solution = Solution()
15 print(solution.get_unique_count(3)) | 1 - refactor: too-few-public-methods
|
1 class Solution:
2 # time: O(rows_count * cols_count). space: O(cols_count)
3 def get_unique_paths_count(self, rows_count, cols_count):
4 row_paths = [1 for _ in range(cols_count)]
5 for _ in range(1, rows_count):
6 new_row_paths = [1]
7 for col in range(1, cols_count):
8 new_row_paths.append(new_row_paths[-1] + row_paths[col])
9 row_paths = new_row_paths
10
11 return row_paths[-1]
12
13 def get_unique_paths_count2(self, rows_count, cols_count):
14 if rows_count == 0 or cols_count == 0:
15 return 0
16
17 if rows_count == 1 or cols_count == 1:
18 return 1
19
20 res = 1
21 for i in range(1, cols_count):
22 res *= (cols_count + rows_count - 1 - i) / i
23
24 return int(res)
25
26 solution = Solution()
27 print(solution.get_unique_paths_count2(6, 3)) | Clean Code: No Issues Detected
|
1 #684
2
3 from collections import defaultdict
4
5 class Solution:
6 def find_redundant_connection(self, edges):
7 graph = defaultdict(set)
8
9 for u, v in edges:
10 visited = set()
11 if u in graph and v in graph and self.dfs(u, v, graph, visited):
12 return [u, v]
13
14 graph[u].add(v)
15 graph[v].add(u)
16
17 def dfs(self, source, target, graph, visited):
18 if source in visited:
19 return False
20
21 visited.add(source)
22
23 if source == target:
24 return True
25
26 return any(self.dfs(nbr, target, graph, visited) for nbr in graph[source])
27
28 solution = Solution()
29 edges = [[1,2], [1,3], [2,3]]
30 # edges = [[1,2], [2,3], [3,4], [1,4], [1,5]]
31 print(solution.find_redundant_connection(edges)) | 6 - warning: redefined-outer-name
6 - refactor: inconsistent-return-statements
|
1 class Solution:
2 def get_ugly_number(self, n, primes):
3 if n <= 0:
4 return 0
5 if n == 1:
6 return 1
7
8 uglys = [1]
9 indices = [0 for _ in range(len(primes))]
10 candidates = primes[:]
11
12 while len(uglys) < n:
13 ugly = min(candidates)
14
15 uglys.append(ugly)
16
17 # increment the correct indexes to avoid duplicates, and set the new candidates
18 for i in range(len(indices)):
19 if candidates[i] == ugly:
20 indices[i] += 1
21 candidates[i] = uglys[indices[i]] * primes[i]
22
23 return uglys[-1]
24
25 solution = Solution()
26 primes = [2, 3, 5]
27 print(solution.get_ugly_number(11, primes))
28
29
| 2 - warning: redefined-outer-name
1 - refactor: too-few-public-methods
|
1 import unittest
2
3 class Solution:
4 def get_unique_paths_count(self, matrix):
5 row_count, col_count = len(matrix), len(matrix[0])
6 if row_count == 0 or col_count == 0:
7 raise Exception('Unvalid Matrix')
8
9 if matrix[0][0] or matrix[-1][-1]:
10 return 0
11
12 row_paths = [0 for _ in range(col_count)]
13 path_count = 0
14
15 for row in range(row_count):
16 new_row_paths = []
17 for col in range(col_count):
18 if row == 0 and col == 0:
19 path_count = 1
20 elif matrix[row][col] == 1:
21 path_count = 0
22 else:
23 path_count = row_paths[col]
24 path_count += new_row_paths[-1] if col > 0 else 0
25 new_row_paths.append(path_count)
26 row_paths = new_row_paths
27
28 return row_paths[-1]
29
30 def uniquePathsWithObstacles(self, grid):
31 """
32 :type obstacleGrid: List[List[int]]
33 :rtype: int
34 """
35
36 if grid[0][0] or grid[-1][-1]:
37 return 0
38
39 m, n = len(grid), len(grid[0])
40
41 ways = [0] * (n + 1)
42 ways[1] = 1
43
44 for row in range(1, m + 1):
45 new_ways = [0]
46 for col in range(1, n + 1):
47 if grid[row - 1][col - 1] == 1:
48 new_ways.append(0)
49 else:
50 new_ways.append(new_ways[-1] + ways[col])
51
52 ways = new_ways
53
54 return ways[-1]
55
56 class Test(unittest.TestCase):
57 test_data = [([[0,0,0], [0,1,0], [0,0,0]], 2), ([[0,0,0], [1,0,1], [0,0,0]], 1)]
58
59 def test_get_unique_paths_count(self):
60 solution = Solution()
61 for data in self.test_data:
62 actual = solution.uniquePathsWithObstacles(data[0])
63 self.assertEqual(actual, data[1])
64
65 if __name__ == '__main__':
66 unittest.main() | 7 - warning: broad-exception-raised
|
1 class Solution:
2 def coin_change(self, coins, amount):
3 if amount < 1:
4 return -1
5
6 memo = [0 for _ in range(amount)]
7 return self.helper(coins, amount, memo)
8
9 def helper(self, coins, amount, memo):
10 if amount < 0:
11 return -1
12
13 if amount == 0:
14 return 0
15
16 if memo[amount - 1]:
17 return memo[amount - 1]
18
19 min_count = float('inf')
20 for coin in coins:
21 res = self.helper(coins, amount - coin, memo)
22 if res >= 0 and res < min_count:
23 min_count = res
24
25 memo[amount - 1] = -1 if min_count == float('inf') else 1 + min_count
26 return memo[amount - 1] | 22 - refactor: chained-comparison
|
1 class Solution(object):
2 def reverse_words(self, string):
3 if not string:
4 return ''
5
6 # words = string.split()
7 # return ' '.join(words[::-1])
8 word_lists = [[]]
9 for i, c in enumerate(string):
10 if c != ' ':
11 word_lists[-1].append(c)
12 elif string[i] == ' ' and i < len(string) - 1 and string[i + 1] != ' ':
13 word_lists.append([])
14
15 words = [''.join(word_list) for word_list in word_lists]
16
17 return ' '.join(words[::-1])
18
19 class Solution2(object):
20 # time: O(n)
21 # space: O(n) because we transform the str to list, otherwise it is O(1)
22 def reverse_words(self, s):
23 string_list = list(s)
24
25 self.reverse(string_list, 0, len(string_list) - 1)
26
27 string_list.append(' ')
28 start = 0
29 for i, c in enumerate(string_list):
30 if string_list[i] == ' ':
31 self.reverse(string_list, start, i - 1)
32 start = i + 1
33
34 string_list.pop()
35 return ''.join(string_list)
36
37 def reverse(self, s, left, right):
38 while left < right:
39 s[left], s[right] = s[right], s[left]
40 left += 1
41 right -= 1
42
43 solution = Solution2()
44 print(solution.reverse_words('The sky is blue')) | 1 - refactor: useless-object-inheritance
1 - refactor: too-few-public-methods
19 - refactor: useless-object-inheritance
29 - warning: unused-variable
|
1 # 725
2
3 from utils.listNode import ListNode
4
5 class Solution:
6 def split(self, head, k):
7 if not head:
8 return []
9
10 nodes_count = self.get_count(head)
11 part_length, odd_parts = divmod(nodes_count, k)
12
13 result = []
14 prev, node = None, head
15
16 for _ in range(k):
17 required = part_length
18 if odd_parts:
19 required += 1
20 odd_parts -= 1
21
22 result.append(node)
23
24 for _ in range(required):
25 # we'll only get here if required > 0, i.e. node is not null
26 prev, node = node, node.next
27
28 if prev:
29 prev.next = None
30
31 return result
32
33 def get_count(self, head):
34 count = 0
35
36 while head:
37 head = head.next
38 count += 1
39
40 return count
41
42 one = ListNode(1)
43 two = ListNode(2)
44 three = ListNode(3)
45 four = ListNode(4)
46 five = ListNode(5)
47 six = ListNode(6)
48 seven = ListNode(7)
49
50 one.next = two
51 two.next = three
52 three.next = four
53 four.next = five
54 five.next = six
55 six.next = seven
56
57 print(one)
58
59 solution = Solution()
60 print(solution.split(one, 10)) | Clean Code: No Issues Detected
|
1 class Solution(object):
2 def pascal_triangle(self, numRows):
3 pascal = []
4 for k in range(numRows):
5 pascal.append([1] * (k + 1))
6 for i in range(1, k):
7 pascal[k][i] = pascal[k - 1][i - 1] + pascal[k - 1][i]
8
9 return pascal
10
11 def pascal_triangle2(self, numRows):
12 all_rows = []
13 row = []
14
15 for k in range(numRows):
16 row.append(1)
17 for i in range(k - 1, 0, -1):
18 row[i] = row[i] + row[i - 1]
19 all_rows.append(list(row))
20
21 return all_rows
22
23 def pascal_triangle_row(self, k):
24 row = []
25 for j in range(k + 1):
26 row.append(1)
27 for i in range(j - 1, 0, -1):
28 row[i] = row[i] + row[i - 1]
29
30 return row
31
32 solution = Solution()
33 print(solution.pascal_triangle_row(2)) | 1 - refactor: useless-object-inheritance
|
1 # 234
2
3 from utils.listNode import ListNode
4
5 class Solution:
6 def is_palindrome(self, head):
7 if not head:
8 return False
9
10 rev, slow, fast = None, head, head
11
12 while fast and fast.next:
13 fast = fast.next.next
14 rev, rev.next, slow = slow, rev, slow.next
15
16 if fast:
17 slow = slow.next
18
19 while rev and rev.value == slow.value:
20 rev = rev.next
21 slow = slow.next
22
23 return not rev
24
25
26 one = ListNode(1)
27 two = ListNode(2)
28 three = ListNode(3)
29 four = ListNode(4)
30 five = ListNode(3)
31 six = ListNode(2)
32 seven = ListNode(1)
33
34 one.next = two
35 two.next = three
36 three.next = four
37 four.next = five
38 five.next = six
39 six.next = seven
40
41 print(one)
42 solution = Solution()
43 print(solution.is_palindrome(one))
44
| 13 - warning: bad-indentation
14 - warning: bad-indentation
5 - refactor: too-few-public-methods
|
1 #687
2
3 class Solution:
4 def longest_univalue_path(self, root):
5 if not root:
6 return 0
7
8 return max(self.longest_univalue_path(root.left),
9 self.longest_univalue_path(root.right),
10 self.straight_univalue_path(root.left, root.value) + self.straight_univalue_path(root.right, root.value))
11
12 def straight_univalue_path(self, root, value):
13 if not root or root.value != value:
14 return 0
15
16 return max(self.straight_univalue_path(root.left, value), self.straight_univalue_path(root.right, value)) + 1
17
18
19
20
21
22
| Clean Code: No Issues Detected
|
1 import random
2
3 class RandomizedSet:
4 def __init(self):
5 self.mapping = {}
6 self.items = []
7
8 def insert(self, value):
9 if value not in self.mapping:
10 self.items.append(value)
11 self.mapping[value] = len(self.items) - 1
12 return True
13 return False
14
15 def remove(self, value):
16 if value not in self.mapping:
17 return False
18 index = self.mapping[value]
19 self.items[index] = self.items[-1]
20 self.mapping[self.items[index]] = index
21 self.items.pop()
22 del self.mapping[value]
23 return True
24
25 def get_random(self):
26 index = random.randint(0, len(self.items) - 1)
27 return self.items[index]
28
29 class RandomizedSet2:
30 def __init__(self):
31 self.mapping = {}
32 self.items = []
33
34 def insert(self, value):
35 if value not in self.mapping:
36 self.items.append(value)
37 self.mapping[value] = len(self.items) - 1
38 return True
39
40 return False
41
42 def remove(self, value):
43 if value in self.mapping:
44 index = self.mapping[value]
45 self.items[index] = self.items[-1]
46 self.mapping[self.items[-1]] = index
47 self.items.pop()
48 del self.mapping[value]
49 return True
50
51 return False
52
53 def get_random(self):
54 index = random.randint(0, len(self.items) - 1)
55 return self.items[index] | 4 - warning: unused-private-member
5 - warning: attribute-defined-outside-init
6 - warning: attribute-defined-outside-init
|
1 class Solution:
2 def get_ones(self, n):
3 if n < 0:
4 return 0
5
6 ones = [0 for _ in range(n + 1)]
7
8 for i in range(1, n + 1):
9 ones[i] = ones[i // 2] + i % 2
10
11 return ones
12
13
14 solution = Solution()
15 print(solution.get_ones(5)) | 1 - refactor: too-few-public-methods
|
1 class Solution(object):
2 def countSegments(self, string):
3 count = 0
4 for i, char in enumerate(string):
5 if char != ' ' and (i == 0 or string[i - 1] == ' '):
6 count += 1
7
8 return count
9
10 # time: O(N)
11 # space: O(N) because we have to build the array of results first
12 def connt_segments2(self, s):
13 return sum([s[i] != ' ' and (i == 0 or s[i - 1] == ' ') for i in range(len(s))])
14
15 solution = Solution()
16 print(solution.connt_segments2('Hello, my name is Aymane')) | 1 - refactor: useless-object-inheritance
13 - refactor: consider-using-generator
|
1 class Solution:
2 def get_combinations(self, k, target):
3 result = []
4 self.backtrack([], 1, target, k, result)
5 return result
6
7
8 def backtrack(self, prefix, current_num, remaining, k, result):
9 if len(prefix) > k or remaining < 0:
10 return
11
12 if remaining == 0 and len(prefix) == k:
13 result.append(prefix)
14 return
15
16 for i in range(10 - current_num):
17 self.backtrack(
18 prefix + [current_num + i],
19 current_num + i + 1,
20 remaining - current_num - i,
21 k,
22 result
23 )
24
25 solution = Solution()
26 print(solution.get_combinations(3, 9))
27 | 8 - refactor: too-many-arguments
8 - refactor: too-many-positional-arguments
|
1 # 655
2
3 #time: O(H * 2**H - 1) need to fill the result array
4 # space: O(H * 2**H - 1) the number of elements in the result array
5
6 from utils.treeNode import TreeNode
7
8 class Solution:
9 def print(self, root):
10 if not root:
11 return []
12
13 height = self.get_height(root)
14
15 result = [["" for _ in range((2 ** height - 1))] for _ in range(height)]
16
17 self.traverse(root, 0, (2 ** height) - 2, 0, result)
18
19 return result
20
21 # DFS traverse
22 def traverse(self, root, start, end, level, result):
23 if not root:
24 return
25
26 mid = (start + end) // 2
27
28 result[level][mid] = root.value
29
30 self.traverse(root.left, start, mid - 1, level + 1, result)
31 self.traverse(root.right, mid + 1, end, level + 1, result)
32
33
34 def get_height(self, root):
35 if not root:
36 return 0
37
38 return 1 + max(self.get_height(root.left), self.get_height(root.right))
39
40 one = TreeNode(1)
41 two = TreeNode(2)
42 three = TreeNode(3)
43 four = TreeNode(4)
44 five = TreeNode(5)
45
46 one.left = two
47 two.left = three
48 three.left = four
49 one.right = five
50
51 print(one)
52
53 print('==============')
54
55 solution = Solution()
56 print(solution.print(one)) | 22 - refactor: too-many-arguments
22 - refactor: too-many-positional-arguments
|
1 # 368
2
3 class Solution:
4 #O(N ** 2) time, O(N) space
5 def get_largest_divisible_subset(self, nums):
6 if not nums:
7 return []
8
9 max_to_set = dict()
10 nums.sort()
11
12 for num in nums:
13 new_set = set()
14 for max_in_s, s in max_to_set.items():
15 if num % max_in_s == 0 and len(s) > len(new_set):
16 new_set = s
17 max_to_set[num] = new_set | { num }
18
19 return list(max(max_to_set.values(), key=len))
20
21
22 def get_max_divisible_subset_length(self, nums):
23 """
24 returns the length of the longest divisible subset
25 """
26 if not nums:
27 return 0
28
29 max_lengths = [1]
30 max_length = 1
31
32 for i in range(1, len(nums)):
33 max_length_here = 1
34 for j in range(i - 1, -1, -1):
35 if nums[i] % nums[j] == 0:
36 max_length_here = max(max_length_here, 1 + max_lengths[j])
37 max_lengths.append(max_length_here)
38 max_length = max(max_length, max_length_here)
39
40 return max_length
41
42 solution = Solution()
43 nums = [1,2,3]
44 print(solution.get_largest_divisible_subset(nums))
| 5 - warning: redefined-outer-name
9 - refactor: use-dict-literal
22 - warning: redefined-outer-name
|
1 class Solution:
2 # time: O(log(min(m, n) * (m + n) * min(m, n)))
3 # space: O(m ** 2)
4 def get_max_length(self, A, B):
5
6 def mutual_subarray(length):
7 # generate all subarrays of A with length length
8 subarrays = set(tuple(A[i: i + length]) for i in range(len(A) - length + 1))
9
10 return any(tuple(B[j: j + length]) in subarrays for j in range(len(B) - length + 1))
11
12 left, right = 0, min(len(A), len(B)) - 1
13
14 while left <= right: # search for smallest length with no mutual subarray
15 mid = (right + left) // 2
16
17 if mutual_subarray(mid):
18 left = mid + 1
19 else:
20 right = mid - 1
21
22 return left - 1
23
24
25 #time: O(M * N)
26 #space: O(M * N)
27 def get_max_length2(self, A, B):
28 # rows = A, cols = B
29 memo = [[0 for _ in range(len(B) + 1)] for _ in range(len(A) + 1)]
30
31 result = 0
32
33 for row in range(1, len(A) + 1):
34 for col in range(1, len(B) + 1):
35 if A[row - 1] == B[col - 1]:
36 memo[row][col] = memo[row - 1][col - 1] + 1
37 result = max(result, memo[row][col])
38
39 return result
40
41
42 ## this is the solution for the problem if the subarrays do not need to be continuous
43 ## in this case, dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
44 def get_max_length3(self, A, B):
45 dp = [[0 for _ in range(len(B) + 1)] for _ in range(len(A) + 1)]
46
47 for i in range(1, len(A) + 1):
48 for j in range(1, len(B) + 1):
49 if A[i - 1] == B[j - 1]:
50 dp[i][j] = 1 + dp[i - 1][j - 1]
51 else:
52 dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
53
54 return dp[-1][-1]
55
56
57 solution = Solution()
58 A = [3, 2, 1, 8, 6, 9]
59 B = [7, 6, 3, 2, 1, 9]
60 print(solution.get_max_length3(A, B)) | 4 - warning: redefined-outer-name
4 - warning: redefined-outer-name
27 - warning: redefined-outer-name
27 - warning: redefined-outer-name
44 - warning: redefined-outer-name
44 - warning: redefined-outer-name
|
1 class Solution(object):
2 # At most one transaction
3 def get_max_profit(self, prices):
4 max_profit = 0
5 if not prices:
6 return max_profit
7 buy = prices[0]
8
9 for i in range(1, len(prices)):
10 price = prices[i]
11 buy = min(price, buy)
12 max_profit = max(max_profit, price - buy)
13
14 return max_profit
15
16 # At most one transaction
17 def get_max_profit3(self, prices):
18 buy = float('inf')
19 profit = 0
20 for price in prices:
21 buy = min(price, buy)
22 profit = max(profit, price - buy)
23
24 return profit
25
26 # At most one transaction
27 def get_max_profit2(self, prices):
28 currMax = 0
29 maxSoFar = 0
30
31 for i in range(1, len(prices)):
32 currMax = max(0, currMax + prices[i] - prices[i - 1])
33 maxSoFar = max(currMax, maxSoFar)
34
35 return maxSoFar
36
37 # unlimited transactions
38 def get_max_profit4(self, prices):
39 return sum([max(prices[i] - prices[i - 1], 0) for i in range(1, len(prices))])
40
41
42 solution = Solution()
43 print(solution.get_max_profit([7, 1, 5, 3, 6, 4]))
44 print(solution.get_max_profit([7, 6, 5, 4, 3, 1])) | 1 - refactor: useless-object-inheritance
39 - refactor: consider-using-generator
|
1 class Solution:
2 def rotate_image(self, image):
3 if not self.isValidImage(image):
4 raise Exception('Invalid image')
5
6 n = len(image)
7
8 for row in range(n//2):
9 start = row
10 end = n - 1 - row
11 for col in range(start, end): # end should not be included, because it is already taken care of in the first iteration
12 x = row
13 y = col
14 prev = image[x][y]
15 for _ in range(4):
16 new_row = y
17 new_col = n - x - 1
18 new_cell = image[new_row][new_col]
19 image[new_row][new_col] = prev
20 x = new_row
21 y = new_col
22 prev = new_cell
23
24 def isValidImage(self, image):
25 n = len(image)
26 return n > 0 and len(image[0]) == n
27
28 def print_image(self, image):
29 for row in image:
30 print(row)
31
32 image = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
33 solution = Solution()
34 solution.print_image(image)
35 solution.rotate_image(image)
36 print('===============')
37 solution.print_image(image) | 2 - warning: redefined-outer-name
4 - warning: broad-exception-raised
24 - warning: redefined-outer-name
28 - warning: redefined-outer-name
|
1 class ListNode:
2 def __init__(self, value):
3 self.value = value
4 self.next = None
5
6 # def __repr__(self):
7 # return '(value = {}, next: {})'.format(self.value, self.next)
8
9 def __repr__(self):
10 nodes = []
11 while self:
12 nodes.append(str(self.value))
13 self = self.next
14 return ' -> '.join(nodes) | 13 - warning: self-cls-assignment
1 - refactor: too-few-public-methods
|
1 # 560
2
3 from collections import defaultdict
4
5 # time: O(N)
6 # space: O(N)
7 class Solution:
8 def subarray_sum(self, nums, k):
9 result = 0
10 if not nums:
11 return result
12
13 sum_map = defaultdict(int)
14 sum_map[0] = 1
15
16 curr_sum = 0
17
18 for num in nums:
19 curr_sum += num
20
21 result += sum_map[curr_sum - k]
22
23 sum_map[curr_sum] += 1
24
25 return result
26
27 nums = [1, 1, 1]
28 solution = Solution()
29 print(solution.subarray_sum(nums, 2))
| 8 - warning: redefined-outer-name
7 - refactor: too-few-public-methods
|
1 # 198
2
3 class Solution:
4 def rob(self, homes):
5 if not homes:
6 return 0
7 curr, prev = 0, 0
8
9 for home in homes:
10 curr, prev = max(curr, prev + home), curr
11
12 return curr
13
| 3 - refactor: too-few-public-methods
|
1 from utils.treeNode import TreeNode
2
3 class Solution:
4 def build_tree(self, in_order, post_order):
5 if not in_order:
6 return None
7
8 return self.build(len(post_order) - 1, 0, len(in_order) - 1, in_order, post_order)
9
10 def build(self, post_end, in_start, in_end, in_order, post_order):
11 if post_end < 0 or in_start > in_end:
12 return None
13
14 value = post_order[post_end]
15 in_index = in_order.index(value)
16
17 root = TreeNode(value)
18
19 root.right = self.build(post_end - 1, in_index + 1, in_end, in_order, post_order)
20 root.left = self.build(post_end - 1 - in_end + in_index, in_start, in_index - 1, in_order, post_order)
21
22 return root
23
24 in_order = [4, 2, 5, 1, 3, 6, 7]
25 post_order = [4, 5, 2, 7, 6, 3, 1]
26
27 solution = Solution()
28 print(solution.build_tree(in_order, post_order))
| 4 - warning: redefined-outer-name
4 - warning: redefined-outer-name
10 - refactor: too-many-arguments
10 - refactor: too-many-positional-arguments
10 - warning: redefined-outer-name
10 - warning: redefined-outer-name
|
1 from bisect import bisect
2
3 class Solution:
4 # Time: O(n log n) - Space: O(n)
5 def get_longest_increasing_sequence(self, nums):
6 """
7 :type nums: List[int]
8 :rtype: int
9 """
10 if not nums:
11 return 0
12
13 dp = []
14 for num in nums:
15 index = bisect(dp, num)
16 if index == len(dp):
17 dp.append(num)
18 else:
19 # num is smaller than the current value at dp[index], therefore, num can be used to build a
20 # longer increasing sequence
21 dp[index] = num
22
23 return len(dp)
24
25 solution = Solution()
26 nums = [5, 2, 3, 8, 1, 19, 7]
27 print(solution.get_longest_increasing_sequence(nums)) | 5 - warning: redefined-outer-name
3 - refactor: too-few-public-methods
|
1 class Solution(object):
2 def missing_element(self, numbers):
3 """
4 :type numbers: List[int]
5 :rtype: int
6 """
7 n = len(numbers)
8 return (n * (n + 1) // 2) - sum(numbers)
9
10 solution = Solution()
11 numbers = [0, 2, 5, 3, 1]
12 print(solution.missing_element(numbers)) | 1 - refactor: useless-object-inheritance
2 - warning: redefined-outer-name
1 - refactor: too-few-public-methods
|
1 from bisect import bisect
2
3 class Solution:
4 # n = len(houses), m = len(heathers)
5 # O(m log m + n log m) = O(max(mlogm, nlogm)) time - O(1) space
6 def get_heathers_radius(self, houses, heathers):
7 heathers = [float('-inf')] + sorted(heathers) + [float('inf')]
8 result = 0
9 for house in houses:
10 i = bisect(heathers, house)
11 min_distance = min(house - heathers[i-1], heathers[i] - house)
12 result = max(result, min_distance)
13
14 return result
15
16 houses = [1, 2, 3, 4]
17 heathers = [2]
18 solution = Solution()
19 print(solution.get_heathers_radius(houses, heathers)) | 6 - warning: redefined-outer-name
6 - warning: redefined-outer-name
3 - refactor: too-few-public-methods
|
1 # 572
2
3 from utils.treeNode import TreeNode
4
5 class Solution:
6 def is_substree(self, s, t):
7 return self.traverse(s, t)
8
9 def traverse(self, s, t):
10 return s and (self.equal(s, t) or self.traverse(s.left, t) or self.traverse(s.right, t))
11
12 def equal(self, s, t):
13 if not s and not t:
14 return True
15
16 if not s or not t or s.value != t.value:
17 return False
18
19 return self.equal(s.left, t.left) and self.equal(s.right, t.right)
20
21 # time: O(m + n)
22 # space: O(m + n)
23
24 class Solution2:
25 def is_substree(self, s, t):
26 def serialize(root):
27 if not root:
28 serial.append('#')
29 return
30
31 serial.append(str(root.value))
32 serialize(root.left)
33 serialize(root.right)
34
35 serial = []
36 serialize(s)
37 s_serialized = ','.join(serial)
38
39 serial = []
40 serialize(t)
41 t_serialized = ','.join(serial)
42
43 return t_serialized in s_serialized | 24 - refactor: too-few-public-methods
3 - warning: unused-import
|
1 from utils.matrix import Matrix
2
3 class Solution:
4 def exist(self, matrix, word):
5 """
6 :type matrix: Matrix
7 :type word: Str
8 :rtype: boolean
9 """
10 if not matrix.row_count or not matrix.col_count:
11 return False
12
13 for row in range(matrix.row_count):
14 for col in range(matrix.col_count):
15 if self.can_find(matrix, row, col, 0, word):
16 return True
17
18 return False
19
20 def can_find(self, matrix, row, col, index, word):
21 """
22 :type matrix: Matrix
23 :type row: int
24 :type col: int
25 :type index: int
26 :type word: str
27 :rtype: boolean
28 """
29 if index == len(word):
30 return True
31
32 if not matrix.is_valid_cell(row, col):
33 return False
34
35 if matrix[row][col] != word[index]:
36 return False
37
38 # in order to avoid using the same cell twice, we should mark it
39 matrix[row][col]= '*'
40
41 found = (
42 self.can_find(matrix, row + 1, col, index + 1, word) or
43 self.can_find(matrix, row - 1, col, index + 1, word) or
44 self.can_find(matrix, row, col + 1, index + 1, word) or
45 self.can_find(matrix, row, col - 1, index + 1, word)
46 )
47
48 if found:
49 return True
50
51 matrix[row][col] = word[index]
52 return False
53
54 matrix = Matrix([['A', 'B', 'C', 'E'], ['S', 'F', 'C', 'S'], ['A', 'D', 'E', 'E']])
55 solution = Solution()
56 print(matrix)
57 print(solution.exist(matrix, 'ABCCED')) | 4 - warning: redefined-outer-name
20 - refactor: too-many-arguments
20 - refactor: too-many-positional-arguments
20 - warning: redefined-outer-name
|
1 from utils.treeNode import TreeNode
2
3 class Solution:
4 def has_path_sum(self, node, sum):
5 if not node:
6 return False
7
8 sum -= node.value
9
10 if not sum and not node.left and not node.right:
11 return True
12
13 return self.has_path_sum(node.left, sum) or self.has_path_sum(node.right, sum) | 4 - warning: redefined-builtin
3 - refactor: too-few-public-methods
1 - warning: unused-import
|
1 from collections import defaultdict
2
3 class Solution:
4 def solve_queries(self, equations, values, queries):
5 graph = self.build_graph(equations, values)
6
7 result = []
8
9 for query in queries:
10 result.append(self.dfs(query[0], query[1], 1, graph, set()))
11
12 return result
13
14 def dfs(self, start, target, temp_result, graph, visited):
15 if not start in graph or start in visited:
16 return -1
17
18 if start == target:
19 return temp_result
20
21 visited.add(start)
22
23 for nbr, division in graph[start].items():
24 result = self.dfs(nbr, target, temp_result * division, graph, visited)
25
26 if result != -1: # found the target
27 return result
28
29 return -1
30
31 def build_graph(self, equations, values):
32 graph = defaultdict(dict)
33
34 for i, eq in enumerate(equations):
35 graph[eq[0]][eq[1]] = values[i]
36 graph[eq[1]][eq[0]] = 1 / values[i]
37
38 return graph
39
40 equations = [ ["a", "b"], ["b", "c"] ]
41 values = [2.0, 3.0]
42 queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ]
43
44 solution = Solution()
45 print(solution.solve_queries(equations, values, queries)) | 4 - warning: redefined-outer-name
4 - warning: redefined-outer-name
4 - warning: redefined-outer-name
14 - refactor: too-many-arguments
14 - refactor: too-many-positional-arguments
31 - warning: redefined-outer-name
31 - warning: redefined-outer-name
|
1 from utils.treeNode import TreeNode
2
3 class Solution:
4 def get_paths(self, node):
5 result = []
6 if not node:
7 return result
8
9 self.helper([], node, result)
10 return [" -> ".join(path) for path in result]
11
12 def helper(self, prefix, node, result):
13 if not node.left and not node.right:
14 #reached a leaf
15 result.append(prefix + [str(node.value)])
16 return
17
18 if node.left:
19 self.helper(prefix + [str(node.value)], node.left, result)
20
21 if node.right:
22 self.helper(prefix + [str(node.value)], node.right, result)
23
24
25 node1 = TreeNode(1)
26 node2 = TreeNode(2)
27 node3 = TreeNode(3)
28 node4 = TreeNode(4)
29 node5 = TreeNode(5)
30 node6 = TreeNode(6)
31 node7 = TreeNode(7)
32
33 node1.left = node2
34 node1.right = node3
35
36 node2.left = node4
37 node2.right = node5
38
39 node3.left = node6
40 node6.left = node7
41
42 print(node1)
43 solution = Solution()
44 print(solution.get_paths(node1))
45
46 | Clean Code: No Issues Detected
|
1 #83
2
3 from utils.listNode import ListNode
4
5 class Solution:
6 def remove_duplicates(self, head):
7 if not head:
8 return
9
10 curr = head
11
12 while curr and curr.next:
13 if curr.value == curr.next.value:
14 curr.next = curr.next.next
15 else:
16 curr = curr.next
17
18 return head
19
20 one = ListNode(1)
21 two = ListNode(2)
22 three = ListNode(3)
23 four = ListNode(1)
24
25 one.next = four
26 four.next = two
27 two.next = three
28
29 print(one)
30
31 solution = Solution()
32 print(solution.remove_duplicates(one))
33
34
35
| 6 - refactor: inconsistent-return-statements
5 - refactor: too-few-public-methods
|
1 # 543
2
3 from utils.treeNode import TreeNode
4
5 # time: O(N)
6 # space: O(N)
7 class Solution:
8 def dimater(self, root):
9 self.result = 0
10 if not root:
11 return self.result
12
13 def depth(root):
14 left_depth = 1 + depth(root.left) if root.left else 0
15 right_depth = 1 + depth(root.right) if root.right else 0
16 self.result = max(self.result, left_depth + right_depth)
17
18 return max(left_depth, right_depth)
19
20 depth(root)
21 return self.result
22
23
24 # time = O(N)
25 # space = O(N)
26 class Solution2:
27 heights_map = dict()
28
29 def dimater(self, root):
30 if not root:
31 return 0
32
33 return max(
34 self.height(root.left) + self.height(root.right),
35 self.dimater(root.left),
36 self.dimater(root.right)
37 )
38
39 def height(self, root):
40 if not root:
41 return 0
42
43 if root in self.heights_map:
44 return self.heights_map[root]
45
46 height = 1 + max(self.height(root.left), self.height(root.right))
47 self.heights_map[root] = height
48
49 return height
50
51 one = TreeNode(1)
52 two = TreeNode(2)
53 three = TreeNode(3)
54 four = TreeNode(4)
55 five = TreeNode(5)
56 six = TreeNode(6)
57 seven = TreeNode(7)
58
59 one.left = two
60 two.left = three
61 three.left = four
62 two.right = five
63 five.right = six
64 six.right = seven
65
66 print(one)
67 print('===============')
68
69 solution = Solution()
70 print(solution.dimater(one))
71
72 class SOlution:
73 def get_diameter(self, root):
74 depth_map = dict()
75
76 if not root:
77 return 0
78
79 def depth(root):
80 if not root:
81 return 0
82
83 if root in depth_map:
84 return depth_map[root]
85
86 result = 1 + max(depth(root.left), depth(root.right))
87 depth_map[root] = result
88
89 return result
90
91 return max(
92 1 + depth(root.left) + depth(root.right),
93 self.get_diameter(root.left),
94 self.get_diameter(root.right)
95 )
| 9 - warning: attribute-defined-outside-init
16 - warning: attribute-defined-outside-init
7 - refactor: too-few-public-methods
27 - refactor: use-dict-literal
74 - refactor: use-dict-literal
72 - refactor: too-few-public-methods
|
1 class Solution(object):
2 def merge_sorted_arrays(self, nums1, nums2):
3 m = len(nums1)
4 n = len(nums2)
5
6 nums1 += [0] * n
7
8 i = m - 1
9 j = n - 1
10 k = i + j + 1
11
12 while i >= 0 and j >= 0:
13 nums1[k] = max(nums1[i], nums2[j])
14 k -= 1
15 if nums1[i] < nums2[j]:
16 j -= 1
17 else:
18 i -= 1
19
20 # nothing to move if only nums1 digits are left, move the rest of digits2 if any
21 if j >= 0:
22 nums1[:k+ 1] = nums2[:j + 1]
23
24 return nums1
25
26 arr1 = [5, 7, 12, 20]
27 arr2 = [2, 6, 9, 40, 80]
28 solution = Solution()
29 print(solution.merge_sorted_arrays(arr1, arr2)) | 16 - warning: bad-indentation
1 - refactor: useless-object-inheritance
1 - refactor: too-few-public-methods
|
1 import collections
2 import unittest
3
4 # time: O(M + N) - space: O(N)
5 # def can_construct(ransom, magazine):
6 # if not magazine:
7 # return False
8
9 # ransom_dict = dict()
10
11 # for s in ransom:
12 # if s not in ransom_dict:
13 # ransom_dict[s] = 1
14 # else:
15 # ransom_dict[s] += 1
16
17 # for char in magazine:
18 # if char in ransom_dict:
19 # if ransom_dict[char] > 1:
20 # ransom_dict[char] -= 1
21 # else:
22 # del ransom_dict[char]
23
24 # return not ransom_dict
25
26 # def can_construct(ransom, magazine):
27 # return all(ransom.count(x) <= magazine.count(x) for x in set(ransom))
28
29 #time: O(M+N) - space: O(M+N)
30 # each time a Counter is produced through an operation, any items with zero or negative counts are discarded
31 class Solution(object):
32 def can_construct(self, ransom, magazine):
33 return not collections.Counter(ransom) - collections.Counter(magazine)
34
35 class Test(unittest.TestCase):
36 test_data = [('ab', 'aab', True), ('abb', 'aab', False)]
37
38 def test_can_construct(self):
39 solution = Solution()
40 for data in self.test_data:
41 actual = solution.can_construct(data[0], data[1])
42 self.assertIs(actual, data[2])
43
44 if __name__ == '__main__':
45 unittest.main() | 31 - refactor: useless-object-inheritance
31 - refactor: too-few-public-methods
|
1 # 731
2
3 # time: o(N**2)
4 # space: O(N)
5 class MyCalendar2:
6 def __inint__(self):
7 self.calendar = []
8 self.overlap = []
9
10 def book(self, start, end):
11 for s, e in self.overlap:
12 # conflict
13 if s < end and start < e:
14 return False
15
16 for s, e in self.calendar:
17 if s < end and start > e:
18 #conflict. The intersection becomes an overlap
19 self.overlap.append(max(start, s), min(end, e))
20
21 self.calendar.append((start, end))
22 return True | 7 - warning: attribute-defined-outside-init
8 - warning: attribute-defined-outside-init
|
1 # 817
2
3 from utils.listNode import ListNode
4
5 class Solution:
6 # time: O(len of linked list)
7 # space: O(len of G)
8 def get_connected_count(self, head, G):
9 count = 0
10
11 if not head:
12 return count
13
14 values_set = set(G)
15
16 prev = ListNode(None)
17 prev.next = head
18
19 while prev.next:
20 if prev.value not in values_set and prev.next.value in values_set:
21 count += 1
22
23 prev = prev.next
24
25 return count
26
27 zero = ListNode(0)
28 one = ListNode(1)
29 two = ListNode(2)
30 three = ListNode(3)
31 four = ListNode(4)
32 five = ListNode(5)
33
34 zero.next = one
35 one.next = two
36 two.next = three
37 three.next = four
38 four.next = five
39
40 print(zero)
41 G = [0, 3, 1, 4]
42 print(G)
43
44
45 solution = Solution()
46 print(solution.get_connected_count(zero, G))
47
48
| 8 - warning: redefined-outer-name
5 - refactor: too-few-public-methods
|
1 from utils.graph import Vertex, Graph
2
3 class Solution:
4 # DFS
5 def search(self, graph, start, end):
6 if not end:
7 return
8
9 if start == end:
10 return True
11
12 visited = set()
13
14 set.add(start)
15
16 for nbr in graph[start]:
17 if nbr not in visited:
18 if self.search(graph, nbr, end):
19 return True
20
21 return False
22
23 def search_BFS(self, graph, start, end):
24 if start == end:
25 return True
26
27 start.visited = True
28 queue = [start]
29
30 while queue:
31 new_queue = []
32 for node in queue:
33 for nbr in graph[node]:
34 if nbr == end:
35 return True
36
37 if not nbr.visited:
38 nbr.visited = True
39 new_queue.append(nbr)
40
41 queue = new_queue
42
43 return False
44
45
46
47
48
49
| 5 - refactor: inconsistent-return-statements
1 - warning: unused-import
1 - warning: unused-import
|
1 # 532
2
3 from collections import Counter
4
5 # time: O(N)
6 # space: O(N)
7 class Solution:
8 def k_diff_pairs(self, nums, k):
9 if k < 0:
10 return 0
11
12 freq = Counter(nums)
13 pairs = 0
14
15 for num in freq:
16 if k == 0:
17 if freq[num] > 1:
18 pairs += 1
19
20 else:
21 if k + num in freq: # this will ensure we get unique pairs
22 pairs += 1
23
24 return pairs
25
26 # time: O(N log N + N)
27 # space: O(1)
28 class Solution2:
29 def k_diff_pairs(self, nums, k):
30 result = []
31 if not nums or len(nums) < 2:
32 return result
33
34 nums.sort()
35 left, right = 0, 1
36
37 while left < len(nums) and right < len(nums):
38 diff = nums[right] - nums[left]
39 if diff == k:
40 result.append((nums[left], nums[right]))
41 # move both left and right
42 right = self.move(right, nums)
43
44 left = self.move(left, nums)
45
46 elif diff < k:
47 # move right
48 right = self.move(right, nums)
49
50 else:
51 # move left
52 left = self.move(left, nums)
53
54 if left == right:
55 # move right
56 right = self.move(right, nums)
57
58 return result
59
60 def move(self, index, nums):
61 index += 1
62 while index < len(nums) and nums[index] == nums[index - 1]:
63 index += 1
64
65 return index
66
67 nums, k = [3, 1, 4, 1, 5], 2
68 # nums, k = [1, 2, 3, 4, 5], 1
69 # nums, k = [3, 1, 4, 1, 5], 0
70
71 solution = Solution()
72 print(solution.k_diff_pairs(nums, k)) | 8 - warning: redefined-outer-name
8 - warning: redefined-outer-name
7 - refactor: too-few-public-methods
29 - warning: redefined-outer-name
29 - warning: redefined-outer-name
60 - warning: redefined-outer-name
|
1 from collections import defaultdict
2
3 class Solution:
4 def networkDelayTime(self, times, K):
5 graph = self.build_graph(times)
6 dist = { node: int('float') for node in graph }
7
8 def dfs(node, elapsed):
9 if elapsed >= dist[node]:
10 return
11
12 dist[node] = elapsed
13 for time, nbr in sorted(graph[node]): # start with the node with the smallest travel time, as it has more chances of reaching all the nodes quicker
14 dfs(nbr, elapsed + time)
15
16 dfs(K, 0)
17
18 ans = max(dist.values())
19 return ans if ans != float('inf') else -1
20
21 def build_graph(self, times):
22 graph = defaultdict(list)
23 for u, v, w in times:
24 graph[u].append((w, v))
25
26 return graph | Clean Code: No Issues Detected
|
1 # 746
2
3 class Solution:
4 def min_cost(self, costs):
5
6 one_before, two_before = costs[1], costs[0]
7
8 for i in range(2, len(costs)):
9 one_before, two_before = min(one_before, two_before) + costs[i], one_before
10
11 return min(one_before, two_before)
12
13 solution = Solution()
14 costs = [10, 15, 20]
15 # costs = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
16 print(solution.min_cost(costs)) | 4 - warning: redefined-outer-name
3 - refactor: too-few-public-methods
|
1 class Solution:
2 def word_break(self, s, wordDict):
3 if not wordDict:
4 return False
5
6 if not s:
7 return True
8
9 can_make = [True] + [False for _ in range(len(s))]
10
11 for i in range(1, len(s) + 1):
12 for j in range(i - 1, -1, -1):
13 if can_make[j] and s[j:i] in wordDict:
14 can_make[i] = True
15 break
16
17 return can_make[-1] | 1 - refactor: too-few-public-methods
|
1 from utils.treeNode import TreeNode
2
3 class Solution:
4 #O(N) time, O(1) space
5 def get_left_leaves_sum(self, node):
6 result = 0
7
8 if not node:
9 return result
10
11 if node.left and not node.left.left and not node.left.right:
12 result += node.left.value
13 else:
14 result += self.get_left_leaves_sum(node.left)
15
16 result += self.get_left_leaves_sum(node.right)
17
18 return result
19
20
21 node1 = TreeNode(1)
22 node2 = TreeNode(2)
23 node3 = TreeNode(3)
24 node4 = TreeNode(4)
25 node5 = TreeNode(5)
26 node6 = TreeNode(6)
27 node7 = TreeNode(7)
28
29 node1.left = node2
30 node1.right = node3
31
32 node2.left = node4
33 node2.right = node5
34
35 node3.left = node6
36 node6.left = node7
37
38 print(node1)
39 solution = Solution()
40 print(solution.get_left_leaves_sum(node1))
41
42 def left_leaves_sum(root):
43 if not root:
44 return 0
45
46 result = 0
47
48 if root.left and not root.left.left and not root.left.right:
49 result += root.left.value
50
51 result += left_leaves_sum(root.left) + left_leaves_sum(root.right) | 3 - refactor: too-few-public-methods
42 - refactor: inconsistent-return-statements
|
1 from utils.treeNode import TreeNode
2 from utils.treeUtils import generate_tree
3
4 class Solution:
5 def preorder_traversal(self, node):
6 result, rights = [], []
7
8 while node or rights:
9 if not node:
10 node = rights.pop()
11
12 result.append(node.value)
13
14 if node.right:
15 rights.append(node.right)
16 node = node.left
17
18 return result
19
20 def preorder_traversal2(self, root):
21 result = []
22 if not root:
23 return result
24
25 stack = [root]
26
27 while stack:
28 node = stack.pop()
29 result.append(node.value)
30
31 if node.right:
32 stack.append(node.right)
33 if node.left:
34 stack.append(node.left)
35
36 return result
37
38 def preorder_traversal3(self, node):
39 result = []
40 self.preorder_traversal_rec(node, result)
41 return result
42
43 def preorder_traversal_rec(self, node, result):
44 if not node:
45 return
46
47 result.append(node.value)
48 self.preorder_traversal_rec(node.left, result)
49 self.preorder_traversal_rec(node.right, result)
50
51 root = generate_tree()
52 print(root)
53 solution = Solution()
54 print(solution.preorder_traversal2(root)) | 20 - warning: redefined-outer-name
1 - warning: unused-import
|
1 from collections import defaultdict
2
3 class Solution:
4 def get_min_height_trees(self, n, edges):
5 graph = defaultdict(set)
6
7 for edge in edges:
8 graph[edge[0]].add(edge[1])
9 graph[edge[1]].add(edge[0])
10
11 height_to_nodes = defaultdict(set)
12
13 for node in graph:
14 self.bfs(node, graph, set(), height_to_nodes)
15
16 min_height = min(height_to_nodes.keys())
17 return list(height_to_nodes[min_height])
18
19 def bfs(self, node, graph, visited, height_to_nodes):
20 height = -1
21 queue = [node]
22 visited.add(node)
23
24 while queue:
25 height += 1
26 new_queue = []
27 for curr in queue:
28 for nbr in graph[curr]:
29 if nbr in visited:
30 continue
31
32 visited.add(nbr)
33 new_queue.append(nbr)
34
35 queue = new_queue
36
37 height_to_nodes[height].add(node)
38
39 def get_min_height_trees2(self, n, edges):
40 graph = defaultdict(set)
41
42 for edge in edges:
43 graph[edge[0]].add(edge[1])
44 graph[edge[1]].add(edge[0])
45
46 leaves = [i for i in graph if len(graph[i]) == 1]
47
48 while len(graph) > 2:
49 new_leaves = []
50 for leaf in leaves:
51 nbr = graph[leaf].pop()
52 del graph[leaf]
53
54 graph[nbr].remove(leaf)
55 if len(graph[nbr]) == 1:
56 new_leaves.append(nbr)
57
58 leaves = new_leaves
59
60 return list(graph.keys())
61
62
63
64 solution = Solution()
65 # edges = [[1, 0], [1, 2], [1, 3]]
66 # print(solution.get_min_height_trees2(4, edges))
67 edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
68 print(solution.get_min_height_trees2(6, edges))
| 4 - warning: redefined-outer-name
4 - warning: unused-argument
39 - warning: redefined-outer-name
39 - warning: unused-argument
|
1 from utils.treeNode import TreeNode
2 from utils.treeUtils import generate_tree
3
4 class Solution:
5 def get_root_to_leaves_sum(self, node):
6 leaves = [0]
7 self.get_sum_helper("", node, leaves)
8 return sum([int(num) for num in leaves])
9
10 def get_sum_helper(self, path, node, leaves):
11 if not node:
12 return
13
14 path += str(node.value)
15
16 if not node.left and not node.right:
17 leaves.append(path)
18
19 self.get_sum_helper(path, node.left, leaves)
20 self.get_sum_helper(path, node.right, leaves)
21
22 path = path[:-1]
23
24 def get_root_to_leaves_sum2(self, node):
25 return self.helper(0, node)
26
27 def helper(self, partial, node):
28 if not node:
29 return 0
30
31 partial = partial * 10 + node.value
32 if not node.left and not node.right:
33 return partial
34
35 return self.helper(partial, node.left) + self.helper(partial, node.right)
36
37
38 root = generate_tree()
39 print(root)
40 solution = Solution()
41 print(solution.get_root_to_leaves_sum2(root)) | 8 - refactor: consider-using-generator
1 - warning: unused-import
|
1 #143
2
3 from utils.listNode import ListNode
4
5 class Solution:
6 def reorder(self, head):
7 if not head:
8 return head
9
10 fast, slow = head, head
11
12 while fast and fast.next:
13 fast = fast.next.next
14 slow = slow.next
15
16 rev, node = None, slow
17 while node:
18 rev, rev.next, node = node, rev, node.next
19
20 first, second = head, rev
21 while second.next:
22 first.next, first = second, first.next
23 second.next, second = first, second.next
24
25 return head
26
27
28 class Solution2:
29 def reorder(self, head):
30 list_map = dict()
31 curr, i = head, 1
32 while curr:
33 list_map[i] = curr
34 curr = curr.next
35 i += 1
36
37 left, right = 1, i - 1
38
39 node = head
40 while left <= right:
41 node.next = list_map[right]
42 left += 1
43
44 if left <= right:
45 node = node.next
46 node.next = list_map[left]
47 right -= 1
48 node = node.next
49
50 node.next = None
51
52 return head
53
54 one = ListNode(1)
55 two = ListNode(2)
56 three = ListNode(3)
57 four = ListNode(4)
58 five = ListNode(5)
59
60 one.next = two
61 two.next = three
62 three.next = four
63 four.next = five
64
65 print(one)
66
67 solution = Solution()
68 print(solution.reorder(one))
69
70 def reorder(head):
71 if not head:
72 return None
73
74 slow = fast = head
75
76 while fast and fast.next:
77 fast = fast.next.next
78 slow = slow.next
79
80 rev = ListNode(None)
81 while slow:
82 rev, rev.next, slow = slow, rev, slow.next
83
84 first, second = head, rev
85 while second.next:
86 first.next, first = second, first.next
87 second.next, second = first, second.next
| 5 - refactor: too-few-public-methods
30 - refactor: use-dict-literal
28 - refactor: too-few-public-methods
70 - refactor: inconsistent-return-statements
|
1
2
3 # Time: O(N) - Space: O(1): the length of the set/map is bounded by the number of the alphabet
4 # set.clear() is O(1)
5 class Solution(object):
6 def longest_unique_substring(self, str):
7 if not str:
8 return 0
9 str_set = set()
10 result = 0
11
12 for char in str:
13 if char not in str_set:
14 # Non repeated character
15 str_set.add(char)
16 result = max(result, len(str_set))
17 else:
18 # Repeated character
19 str_set.clear()
20 str_set.add(char)
21
22 # result = max(result, len(str_set))
23 return result
24
25 # Sliding window technique
26 # Maitain a sliding window, updating the start whenever we see a character repeated
27 def longest_unique_substring2(self, s):
28 """
29 :type str: str
30 :rtype: int
31 """
32 if not s:
33 return 0
34 start = 0 # start index of the current window(substring)
35 longest = 0
36 last_seen = {} # mapping from character to its last seen index
37
38 for i, char in enumerate(s):
39 if char in last_seen and last_seen[char] >= start: # start a new substring after the previous c
40 start = last_seen[char] + 1
41 else:
42 longest = max(longest, i - start + 1)
43
44 last_seen[char] = i # update the last sightning index
45
46 return longest
47
48 | 5 - refactor: useless-object-inheritance
6 - warning: redefined-builtin
|
1 class Solution(object):
2 def move_zeroes(self, numbers):
3 if not numbers:
4 return None
5
6 insert_pos = 0
7 for i, num in enumerate(numbers):
8 if num != 0:
9 numbers[insert_pos] = num
10 insert_pos += 1
11
12 for i in range(insert_pos, len(numbers)):
13 numbers[i] = 0
14
15
16 solution = Solution()
17 numbers = [0, 0, 3, 0, 12, 5, 6, 0, 0, 0]
18 solution.move_zeroes(numbers)
19 print(numbers) | 1 - refactor: useless-object-inheritance
2 - warning: redefined-outer-name
2 - refactor: inconsistent-return-statements
1 - refactor: too-few-public-methods
|
1 class Solution:
2 def get_min_path(self, triangle):
3 """
4 type triangle: List[List[int]]
5 rtype: int
6 """
7
8 if not triangle:
9 return 0
10
11 for row in range(len(triangle) - 2, -1, -1):
12 for col in range(row + 1):
13 triangle[row][col] += min(triangle[row + 1][col], triangle[row + 1][col + 1])
14
15 return triangle[0][0]
16
17 triangle = [[2], [3, 4], [6, 5, 7], [4, 1, 8, 3]]
18 solution = Solution()
19 print(solution.get_min_path(triangle)) | 2 - warning: redefined-outer-name
1 - refactor: too-few-public-methods
|
1 import unittest
2
3 def add_binary(str1, str2):
4 """
5 :type str1: str
6 :type str2: str
7 :rtype: str
8 """
9 carry = 0
10 result = []
11 i = len(str1) - 1
12 j = len(str2) - 1
13
14 while carry or i >= 0 or j >= 0:
15 total = carry
16
17 if i >= 0:
18 total += int(str1[i])
19 i -= 1
20
21 if j >= 0:
22 total += int(str2[j])
23 j -= 1
24
25 result.append(str(total % 2))
26 carry = total // 2
27
28 return ''.join(result[::-1])
29
30 class Test(unittest.TestCase):
31 data = [('11', '1', '100')]
32
33 def test_add_binary(self):
34 for test_data in self.data:
35 actual = add_binary(test_data[0], test_data[1])
36 self.assertEqual(actual, test_data[2])
37
38 if __name__ == '__main__':
39 unittest.main() | Clean Code: No Issues Detected
|
1 class Matrix:
2 def __init__(self, rows):
3 self.rows = rows
4 self.row_count = len(rows)
5 self.col_count = len(rows[0])
6
7 def is_valid_cell(self, row, col):
8 return (
9 row >= 0 and row < self.row_count and
10 col >= 0 and col < self.col_count
11 )
12
13 def __repr__(self):
14 result = ''
15 for row in self.rows:
16 result += str(row) + '\n'
17 return result
18
19 def __getitem__(self, index):
20 return self.rows[index]
21
22 def __setitem__(self, index, value):
23 self.rows[index] = value | 9 - refactor: chained-comparison
|
1 class Solution:
2 def remove_duplicates(self, nums):
3 if len(nums) <= 2:
4 return len(nums)
5
6 j = 1
7 for i in range(2, len(nums)):
8 if nums[i] > nums[j - 1]:
9 j += 1
10 nums[j] = nums[i]
11
12 j += 1
13 for _ in range(j, len(nums)):
14 nums.pop()
15
16 return j
17
18 solution = Solution()
19 nums = [1,1,1,2,2,3]
20 print(solution.remove_duplicates(nums))
21 print(nums) | 2 - warning: redefined-outer-name
1 - refactor: too-few-public-methods
|
1 class Solution:
2 def sqrt(self, n):
3 if n == 0:
4 return 0
5
6 left, right = 1, n
7 # while True:
8 # mid = (left + right) // 2
9 # if mid * mid > n:
10 # right = mid - 1
11 # else:
12 # if (mid + 1) * (mid + 1) > n:
13 # return mid
14 # left = mid + 1
15
16 # use the while left <= right and return left - 1 when looking for the max value that satisfies a condition. because we do left = mid + 1, the last value of left will be our result + 1
17 while left <= right:
18 mid = (left + right) // 2
19 if mid * mid > n:
20 right = mid - 1
21 else:
22 left = mid + 1
23
24 return left - 1
25
26 solution = Solution()
27 print(solution.sqrt(24)) | 1 - refactor: too-few-public-methods
|
1 from collections import defaultdict
2
3 class Solution:
4 def target_sum(self, nums, target):
5 if not nums:
6 return 0
7
8 sums = defaultdict(int)
9 sums[0] = 1
10
11 running = nums[:]
12
13 for i in range(len(running) - 2, -1, -1):
14 running[i] += running[i + 1]
15
16 for i, num in enumerate(nums):
17 new_sums = defaultdict(int)
18 for old_sum in sums:
19 if target <= old_sum + running[i]: # if I can reach the target from this sum
20 new_sums[num + old_sum] += sums[old_sum]
21 if target >= old_sum - running[i]:
22 new_sums[old_sum - num] += sums[old_sum]
23
24 sums = new_sums
25
26 return sums[target]
27
28 nums = [1, 1, 1, 1, 1]
29 target = 3
30 solution = Solution()
31 print(solution.target_sum(nums, target))
32
| 4 - warning: redefined-outer-name
4 - warning: redefined-outer-name
3 - refactor: too-few-public-methods
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.