code
stringlengths 20
13.2k
| label
stringlengths 21
6.26k
|
---|---|
1 class Interval:
2 def __init__(self, start, end):
3 self.start = start
4 self.end = end
5
6 def __repr__(self):
7 return "[{0}, {1}]".format(self.start, self.end) | 1 - refactor: too-few-public-methods
|
1 # 832
2
3 class Solution:
4 def flip(self, matrix):
5
6 for row in matrix:
7 for i in range((len(row) + 1) // 2):
8 row[i], row[-1 -i] = 1 - row[-1 -i], 1 - row[i]
9
10 return matrix
11
12 solution = Solution()
13 matrix = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
14 print(solution.flip(matrix)) | 4 - warning: redefined-outer-name
3 - refactor: too-few-public-methods
|
1 class Solution:
2 def can_construct(self, org, seqs):
3 extended = [None] + seqs
4 pairs = set((u, v) for u, v in zip(extended, org))
5 num_to_index = { num: i for i, num in enumerate(extended)}
6
7 for seq in seqs:
8 for u, v in zip([None]+seq, seq):
9 if v not in num_to_index or num_to_index[v] <= num_to_index[u]:
10 return False
11 pairs.discard((u,v))
12
13 return not pairs | 1 - refactor: too-few-public-methods
|
1 from utils.matrix import Matrix
2
3 class Solution:
4 def pacific_atlantic(self, matrix):
5 if not matrix or not matrix[0]:
6 return []
7
8 rows, cols = len(matrix), len(matrix[0])
9 pacific, atlantic = set(), set()
10
11 for row in range(rows):
12 atlantic.add((row, cols - 1))
13 pacific.add((row, 0))
14
15 for col in range(cols):
16 atlantic.add((rows - 1, col))
17 pacific.add((0, col))
18
19 for ocean in [atlantic, pacific]:
20 frontier = set(ocean)
21
22 while frontier:
23 new_frontier = set()
24 for row, col in frontier:
25 for dir_r, dir_c in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
26 new_row, new_col = row + dir_r, col + dir_c
27
28 if new_row < 0 or new_row >= rows or new_col < 0 or new_col >= cols or (new_row, new_col) in ocean:
29 continue
30
31 if matrix[new_row][new_col] >= matrix[row][col]:
32 new_frontier.add((new_row, new_col))
33
34 frontier = new_frontier
35 ocean |= frontier
36
37 return list(atlantic & pacific)
38
39
40 def pacific_atlantic2(self, matrix):
41 """
42 type matrix: Matrix
43 rtype: List([int, int])
44 """
45
46 if not matrix or not matrix.rows_count or matrix.cols_count:
47 raise Exception('Invalid Matrix')
48
49 reached_cells = [[0 for _ in range(matrix.rows_count)] for _ in range(matrix.cols_count)]
50 pacific_queue = []
51 atlantic_queue = []
52
53 for row in range(matrix.rows_count):
54 pacific_queue.append((row, 0))
55 atlantic_queue.append((row, matrix.rows_count - 1))
56 reached_cells[row][0] += 1
57 reached_cells[row][matrix.rows_count - 1] += 1
58
59 for col in range(matrix.cols_count):
60 pacific_queue.append((0, col))
61 atlantic_queue.append((col, matrix.rows_cols - 1))
62 reached_cells[0][col] += 1
63 reached_cells[row][matrix.rows_cols - 1] += 1
64
65 self.bfs(pacific_queue, matrix, pacific_queue[:], reached_cells)
66 self.bfs(atlantic_queue, matrix, atlantic_queue[:], reached_cells)
67
68 return [[row, col] for row in range(matrix.rows_count) for col in range(matrix.cols_count) if reached_cells[row][col] == 2]
69
70 def bfs(self, queue, matrix, visited, reached_cells):
71 while queue:
72 new_queue = []
73 for (row, col) in queue:
74 for dir_r, dir_c in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
75 new_row, new_col = row + dir_r, col + dir_c
76 if not matrix.is_valid_cell(new_row, new_col) or (new_row, new_col) in visited or matrix[row][col] > matrix[new_row][new_col]:
77 continue
78 new_queue.append((new_row, new_col))
79 matrix[new_row][new_col] += 1
80
81 queue = new_queue
| 47 - warning: broad-exception-raised
70 - warning: unused-argument
1 - warning: unused-import
|
1 class Solution:
2 def get_longest_common_prefix(self, words):
3 if not words:
4 return ''
5
6 min_word_length = min(words, key=len)
7
8 start, end = 0, len(min_word_length) - 1
9
10 while start <= end:
11 mid = (start + end) // 2
12 if not self.is_common_prefix(mid, words):
13 end = mid - 1
14 else:
15 start = mid + 1
16
17 return words[0][:end + 1]
18
19 def is_common_prefix(self, length, words):
20 prefix = words[0][:length + 1]
21
22 for word in words:
23 if not word.startswith(prefix):
24 return False
25
26 return True
27
28 list_strings = ['abu', 'abcd', 'abce', 'abcee']
29 solution = Solution()
30 print(solution.get_longest_common_prefix(list_strings)) | Clean Code: No Issues Detected
|
1 class Solution:
2 # Time: O(rows * cols) - space: O(1)
3 def fill_zeroes(self, matrix):
4 rows_count, col_count = len(matrix), len(matrix[0])
5 for row in range(rows_count):
6 for col in range(col_count):
7 if not matrix[row][col]:
8 matrix[row][col] = 'X'
9 self.fill_row(row, 'X', matrix)
10 self.fill_col(col, 'X', matrix)
11
12 for row in range(rows_count):
13 for col in range(col_count):
14 if matrix[row][col] == 'X':
15 matrix[row][col] = 0
16
17 def fill_row(self, row, val, matrix):
18 col_count = len(matrix[0])
19 for col in range(col_count):
20 matrix[row][col] = val
21
22 def fill_col(self, col, val, matrix):
23 row_count = len(matrix)
24 for row in range(row_count):
25 matrix[row][col] = val
26
27 def print_matrix(self, matrix):
28 for row in matrix:
29 print(row)
30
31 def fill_zeroes2(self, matrix):
32 should_fill_row, should_fill_col = False, False
33 rows_count, col_count = len(matrix), len(matrix[0])
34
35 for row in range(rows_count):
36 for col in range(col_count):
37 if not matrix[row][col]:
38 if row == 0:
39 should_fill_row = True
40 if col == 0:
41 should_fill_col = True
42 matrix[0][col] = 0
43 matrix[row][0] = 0
44
45 for row in range(1, rows_count):
46 for col in range(1, rows_count):
47 if not matrix[row][0] or not matrix[0][col]:
48 matrix[row][col] = 0
49
50 if should_fill_row:
51 self.fill_row(0, 0, matrix)
52
53 if should_fill_col:
54 self.fill_col(0, 0, matrix)
55
56
57 matrix = [[1,0,1,1,1],[1,1,1,1,1],[1,1,1,1,1], [1,1,1,0,1], [1,1,1,1,1]]
58 solution = Solution()
59 solution.print_matrix(matrix)
60 solution.fill_zeroes2(matrix)
61 print('===============')
62 solution.print_matrix(matrix)
63
| 3 - warning: redefined-outer-name
17 - warning: redefined-outer-name
22 - warning: redefined-outer-name
27 - warning: redefined-outer-name
31 - warning: redefined-outer-name
|
1 class Node:
2 def __init__(self, label):
3 self.label = label
4 self.neighbors = []
5
6 class Solution:
7 def clone_graph(self, node):
8 if not node:
9 return None
10
11 cloned_start = Node(node.key)
12 node_mapping = { node: cloned_start}
13 queue = [node]
14
15 while queue:
16 node = queue.pop()
17 cloned_node = node_mapping[node]
18
19 for nbr in node.neighbors:
20 if nbr not in node_mapping:
21 cloned_nbr = Node(nbr.key)
22 node_mapping[nbr] = cloned_nbr
23 queue.append(nbr)
24 else:
25 cloned_nbr = node_mapping[nbr]
26
27 cloned_node.neighbors.append(cloned_nbr)
28
29 return cloned_start
30
31 def clone_graph2(self, node):
32 mapping = dict()
33 return self.helper(node, mapping)
34
35 def helper(self, node, mapping):
36 if node in mapping:
37 return mapping[node]
38
39 cloned_node = Node(node.key)
40
41 for nbr in node.neighbors:
42 cloned_nbr = self.helper(nbr, mapping)
43 cloned_node.neighbors.append(cloned_nbr)
44
45 mapping[node] = cloned_node
46
47 return cloned_node | 1 - refactor: too-few-public-methods
32 - refactor: use-dict-literal
|
1 # time: O(n ** 3)
2
3 class Solution:
4 ELEMENTS_COUNT = 4
5
6 def four_way(self, nums, target):
7 results = []
8 self.n_way(sorted(nums), target, [], self.ELEMENTS_COUNT, results)
9 return results
10
11 def n_way(self, nums, target, partial, n, results):
12 if len(nums) < n or nums[0] * n > target or nums[-1] * n < target:
13 return
14
15 if n == 2:
16 left, right = 0, len(nums)
17 while left < right:
18 if nums[left] + nums[right] == target:
19 results.append(partial + [nums[left], nums[right]])
20 left += 1
21 right -= 1
22 while nums[right] == nums[right + 1] and right > left:
23 right -= 1
24 while nums[left] == nums[left - 1] and left < right:
25 left += 1
26 elif nums[left] + nums[right] < target:
27 left += 1
28 else:
29 right -= 1
30 else:
31 # add the next element in the list to partial, in order to get to 2-sum
32 for i in range(len(nums) - n + 1):
33 if i == 0 or nums[i] != nums[i - 1]: # avoid dups if possible
34 self.n_way(nums[i + 1 :], target - nums[i], partial + [nums[i]], n - 1, results) | 11 - refactor: too-many-arguments
11 - refactor: too-many-positional-arguments
|
1 from utils.listNode import ListNode
2
3 #237
4
5 class Solution:
6 def delete_node(self, node):
7 # node is not the tail => node.next exists
8 node.value = node.next.value
9 node.next = node.next.next | 5 - refactor: too-few-public-methods
1 - warning: unused-import
|
1 from utils.treeNode import TreeNode
2
3 def generate_tree():
4 node1 = TreeNode(1)
5 node2 = TreeNode(2)
6 node3 = TreeNode(3)
7 node4 = TreeNode(4)
8 node5 = TreeNode(5)
9 node6 = TreeNode(6)
10 node7 = TreeNode(7)
11
12 node1.left = node2
13 node1.right = node3
14
15 node2.left = node4
16 node2.right = node5
17
18 node3.left = node6
19 node6.left = node7
20
21 return node1 | Clean Code: No Issues Detected
|
1 # iterate over the list, and keep track of where the next 0 and 1 should be placed
2 # because 2 will always be last, replace the current element with 2
3 # TAKEAWAY: when sorting in place, have a counter to keep track of where an element should placed next
4 class Solution:
5 def sort_colors(self, colors):
6 next_red, next_white = 0, 0
7 for i, c in enumerate(colors):
8 if c < 2:
9 colors[i] = 2
10 colors[next_white] = 1
11 next_white += 1
12 if c == 0:
13 colors[next_red] = 0
14 next_red += 1
15
16 solution = Solution()
17 colors = [2, 1, 2, 2, 1, 0, 0]
18 print(colors)
19 solution.sort_colors(colors)
20 print(colors)
| 5 - warning: redefined-outer-name
4 - refactor: too-few-public-methods
|
1 from math import floor, sqrt
2
3 class Solution:
4 def get_min_square_count(self, n):
5 if n == 0:
6 return 0
7 memo = [-1 for _ in range(n + 1)]
8 memo[0] = 0
9
10 return self.get_min_square_rec(memo, n)
11
12 def get_min_square_rec(self, memo, n):
13 if memo[n] < 0:
14 biggest_square = floor(sqrt(n)) ** 2
15 memo[n] = (n // biggest_square) + self.get_min_square_rec(memo, n % biggest_square)
16
17 return memo[n]
18
19 def get_min_squares(self, n):
20 memo = [0] + [float('inf') for _ in range(n)]
21
22 for i in range(1, n + 1):
23 min_count = float('inf')
24 j = 1
25 while i - j*j >= 0:
26 min_count = min(min_count, 1 + memo[i - j * j])
27 j += 1
28
29 memo[i] = min_count
30
31 return memo[-1]
32
33 solution = Solution()
34 for i in range(10):
35 print("n = {} : {}".format(i, solution.get_min_square_count(i)))
36 print("n = {} : {}".format(i, solution.get_min_squares(i))) | 22 - warning: redefined-outer-name
|
1 import random
2 from collections import defaultdict
3
4 class Solution:
5 # O(1) space and time in initialization. O(n) time and O(1) space when getting the rand index
6 def __init__(self, nums):
7 self.nums = nums
8
9 def get_random_index(self, target):
10 result, count = None, 0
11 for i, num in enumerate(self.nums):
12 if num == target:
13 if random.randint(0, count) == 0:
14 result = i
15 count += 1
16 return result
17
18 #Solution 2:
19 # O(N) space and time in initilization. O(1) space and time when picking random index
20 # def __init__(self, nums):
21 # self.nums = nums
22 # self.mapping = defaultdict(list)
23 # for i, num in enumerate(nums):
24 # self.mapping[num].append(i)
25
26 # def get_random_index(self, target):
27 # return random.choice(self.mapping[target])
28
29 nums = [1, 3, 2, 2, 3, 3, 3, 4]
30 solution = Solution(nums)
31 print(solution.get_random_index(2))
| 6 - warning: redefined-outer-name
4 - refactor: too-few-public-methods
2 - warning: unused-import
|
1 from utils.treeNode import TreeNode
2
3 class BSTIterator:
4 # O(n) worst case for time and space
5 def __init__(self, root):
6 self.stack = []
7 while root:
8 self.stack.append(root)
9 root = root.left
10
11 # O(1) time and space
12 def has_next(self):
13 return len(self.stack) > 0
14
15 #time: O(n) worst case, O(1) average
16 # space: O(n) worst case, O(log n) if balanced
17 def next(self):
18 if not self.has_next():
19 return None
20
21 node = self.stack.pop()
22 result = node.value
23
24 if node.right:
25 node = node.right
26
27 while node:
28 self.stack.append(node)
29 node = node.left
30
31 return result
32
| 1 - warning: unused-import
|
1 #671
2
3 from utils.treeNode import TreeNode
4
5 class Solution:
6 def second_minimum(self, root):
7 if not root:
8 return -1
9
10 level = [root]
11 curr_min = root.value
12
13 while level:
14 next_level = []
15 for node in level:
16 if node.left:
17 next_level.append(node.left)
18 next_level.append(node.right)
19
20 candidates = [node.value for node in next_level if node.value > curr_min]
21 if candidates:
22 return min(candidates)
23
24 level = next_level
25
26 return -1
27
28
29 # one = TreeNode(2)
30 # two = TreeNode(2)
31 # three = TreeNode(5)
32 # four = TreeNode(5)
33 # five = TreeNode(7)
34
35 # one.left = two
36 # one.right = three
37 # three.left = four
38 # three.right = five
39
40 one = TreeNode(2)
41 two = TreeNode(2)
42 three = TreeNode(2)
43
44 one.left = two
45 one.right = three
46
47 print(one)
48
49 print('=========')
50 solution = Solution()
51 print(solution.second_minimum(one))
52 | 5 - refactor: too-few-public-methods
|
1 # 795
2
3 class Solution:
4 def subarray_count(self, nums, L, R):
5 # dp is the number of subarrays ending with nums[i]
6 result, dp = 0, 0
7 prev_invalid_index = -1
8
9 if not nums:
10 return result
11
12 for i, num in enumerate(nums):
13 if num < L:
14 result += dp
15
16 elif num > R:
17 dp = 0
18 prev_invalid_index = i
19
20 else:
21 dp = i - prev_invalid_index
22 result += dp
23
24 return result
25
26 class Solution2:
27 def subarray_count(self, nums, L, R):
28 prev_invalid_index = -1
29 res = count = 0
30
31 for i, num in enumerate(nums):
32 if num < L:
33 res += count
34
35 elif num > R:
36 count = 0
37 prev_invalid_index = i
38
39 else:
40 count = i - prev_invalid_index
41 res += count
42
43 return res
| 3 - refactor: too-few-public-methods
26 - refactor: too-few-public-methods
|
1 class Solution(object):
2 def two_sum(self, arr, target):
3 if not arr:
4 return None
5
6 remainders = dict()
7 for i, num in enumerate(arr):
8 if target - num in remainders:
9 return (remainders[target - num], i)
10 remainders[num] = i
11
12 solution = Solution()
13 print(solution.two_sum([1, 3, 5, 9], 10)) | 1 - refactor: useless-object-inheritance
6 - refactor: use-dict-literal
2 - refactor: inconsistent-return-statements
1 - refactor: too-few-public-methods
|
1 class Solution(object):
2
3 def simplify_path(self, path):
4 """
5 :type path: str
6 :rtype: str
7 """
8
9 directories = path.split('/') # get the directories from the path
10 result = [] # stack to hold the result
11
12 for dir in directories:
13 if dir == '..' and result: # go up one level if possible
14 result.pop()
15 elif dir and dir != '.': # add the dir to the stack
16 result.append(dir)
17 # else ignore '' and '.'
18
19 return '/' + result[-1] if result else '/'
20
21 solution = Solution()
22 print(solution.simplify_path('/a/b/c/./../')) | 1 - refactor: useless-object-inheritance
12 - warning: redefined-builtin
1 - refactor: too-few-public-methods
|
1 class Solution:
2 def get_max_break(self, n):
3 memo = [0, 1]
4
5 for i in range(2, n + 1):
6 max_product = 0
7 for j in range(1, (i // 2) + 1):
8 max_product = max(max_product, max(j, memo[j]) * max(i - j, memo[i - j]))
9 memo.append(max_product)
10
11 return memo[-1]
12
13 def get_max_break2(self, n):
14 memo = [0 for _ in range(n + 1)]
15 memo[1] = 1
16
17 for i in range(2, n+1):
18 memo[i] = max(max(j, memo[j]) * max(i - j, memo[i - j]) for j in range(1, (i//2) + 1))
19
20 return memo[-1]
21
22 solution = Solution()
23 for i in range(2, 10):
24 print('get_max_break({}) = {}'.format(i, solution.get_max_break2(i))) | 5 - warning: redefined-outer-name
17 - warning: redefined-outer-name
|
1 from utils.listNode import ListNode
2
3 class Solution:
4 def get_intersection(self, head1, head2):
5 if not head1 or not head2:
6 return None
7
8 l1, l2 = self.get_length(head1), self.get_length(head2)
9 node1, node2 = self.move_ahead(head1, l1 - l2), self.move_ahead(head2, l2 - l1)
10
11 while node1 and node2:
12 if node1 == node2:
13 return node1
14
15 node1 = node1.next
16 node2 = node2.next
17
18 return None
19
20 def get_length(self, head):
21 count = 0
22 node = head
23 while node:
24 count += 1
25 node = node.next
26
27 return count
28
29 def move_ahead(self, head, l):
30 if l <= 0:
31 return head
32
33 curr = head
34 while l > 0:
35 curr = curr.next
36 l -= 1
37
38 return curr
39
40 class Solution2:
41 def get_intersection(self, head1, head2):
42 if not head1 or not head2:
43 return None
44
45 savedA, savedB = head1, head2
46
47 while head1 != head2:
48 head1 = savedB if not head1 else head1.next
49 head2 = savedA if not head2 else head2.next
50
51 return head1
52
53 one = ListNode(1)
54 two = ListNode(2)
55 three = ListNode(3)
56 four = ListNode(4)
57 five = ListNode(5)
58 six = ListNode(6)
59 seven = ListNode(7)
60
61 one.next = two
62 two.next = three
63 three.next = four
64 four.next = five
65 six.next = seven
66 seven.next = two
67
68 print(one)
69 print(six)
70
71 solution = Solution()
72 print(solution.get_intersection(one, six))
73
| 40 - refactor: too-few-public-methods
|
1 class Solution(object):
2 def remove_duplicate(self, arr):
3 """
4 type arr: list
5 rtype: int
6 """
7 if not arr:
8 return 0
9
10 j = 0
11 for i in range(1, len(arr)):
12 if arr[i] != arr[j]:
13 j += 1
14 arr[j] = arr[i]
15 j += 1
16
17 for i in range(len(arr) - j):
18 arr.pop()
19
20 return j
21
22 solution = Solution()
23 arr = [1, 1, 2, 3, 4, 4]
24 print(solution.remove_duplicate(arr))
25 print(arr) | 1 - refactor: useless-object-inheritance
2 - warning: redefined-outer-name
1 - refactor: too-few-public-methods
|
1 class Solution:
2 def topological_sort(self, graph):
3 result = []
4 discovered = set()
5 path = []
6
7 for node in graph:
8 self.helper(node, result, discovered, path)
9
10 return result.reverse()
11
12 def helper(self, node, result, discovered, path):
13 if node in discovered:
14 return
15
16 path.append(node)
17
18 discovered.add(node)
19
20 for nbr in node.neighbors:
21 if nbr in path:
22 raise Exception('Cyclic graph')
23
24 self.helper(nbr, result, discovered, path)
25
26 path.pop()
27 result.append(node.key) | 22 - warning: broad-exception-raised
|
1 class Solution(object):
2 def two_sum(self, numbers, target):
3 """
4 :type numbers: List[int]
5 :type target: int
6 :rtype: Tuple(int)
7 """
8
9 left, right = 0, len(numbers) - 1
10 while left < right:
11 pair_sum = numbers[left] + numbers[right]
12 if pair_sum == target:
13 return (left + 1, right + 1)
14 elif pair_sum < target:
15 left += 1
16 else:
17 right -= 1
18
19 solution = Solution()
20 numbers = [1, 4, 8, 10, 18]
21 print(solution.two_sum(numbers, 12)) | 1 - refactor: useless-object-inheritance
2 - warning: redefined-outer-name
12 - refactor: no-else-return
2 - refactor: inconsistent-return-statements
1 - refactor: too-few-public-methods
|
1 class Solution(object):
2 # time: O(N), space: O(N)
3 def maximum_subarray(self, arr):
4 if not arr:
5 return 0
6
7 result = arr[0]
8 dp = [arr[0]]
9
10 for i in range(1, len(arr)):
11 dp.append(arr[i] + max(dp[i - 1], 0)) # longest subarray until index i
12 result = max(result, dp[i])
13
14 return result
15
16 # time: O(N), space: O(1)
17 def maximum_subarray2(self, arr):
18 if not arr:
19 return 0
20
21 result = arr[0]
22 max_ending_here = arr[0]
23
24 for i in range(1, len(arr)):
25 max_ending_here = arr[i] + max(max_ending_here, 0)
26 result = max(result, max_ending_here)
27
28 return result
29
30
31 test_arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
32 solution = Solution()
33 print(solution.maximum_subarray2(test_arr))
34
| 1 - refactor: useless-object-inheritance
|
1 from utils.treeNode import TreeNode
2 from utils.treeUtils import generate_tree
3
4 class Solution:
5 def get_side_view(self, node):
6 result = []
7 if not node:
8 return result
9
10 level_nodes = [node]
11
12 while level_nodes:
13 result.append(level_nodes[-1].value)
14 new_level_nodes = []
15
16 for node in level_nodes:
17 if node.left:
18 new_level_nodes.append(node.left)
19
20 if node.right:
21 new_level_nodes.append(node.right)
22
23 level_nodes = new_level_nodes
24
25 return result
26
27 def get_side_view2(self, node):
28 result = []
29 self.helper(node, 0, result)
30 return result
31
32 def helper(self, node, level, result):
33 if not node:
34 return
35
36 if len(result) == level:
37 result.append(node.value)
38 else:
39 result[level] = node.value
40
41 self.helper(node.left, level + 1, result)
42 self.helper(node.right, level + 1, result)
43
44 root = generate_tree()
45 print(root)
46 solution = Solution()
47 print(solution.get_side_view2(root))
48
| 16 - refactor: redefined-argument-from-local
1 - warning: unused-import
|
1 import unittest
2
3 # O(N) time and O(1) space
4
5
6
7 # def lengthOfLastWord(string):
8 # list = string.split(' ')
9 # return len(list[-1]) if list else 0
10
11 # def length_of_last_word(string):
12 # current_length, prev_length = 0, 0
13 # for char in string:
14 # if char == ' ':
15 # if current_length != 0:
16 # prev_length = current_length
17 # current_length = 0
18 # else:
19 # current_length += 1
20
21 # return current_length if current_length != 0 else prev_length
22
23 # def length_of_last_word(string):
24 # result = 0
25 # i = len(string) - 1
26
27 # while string[i] == ' ' and i >= 0:
28 # i -= 1
29
30 # if i == -1:
31 # # Reached the beginning of the word, and did not find any words
32 # return 0
33 # # result = 1
34
35 # while string[i] != ' ' and i >= 0:
36 # result += 1
37 # i -= 1
38
39 # return result
40
41
42 def length_of_last_word(string):
43 i = len(string) - 1
44 end = -1
45
46 while i >= 0:
47 if string[i] == ' ' and end != -1:
48 # already found a word, and encoutered a space
49 return end - i
50 if string[i] != ' ' and end == -1:
51 # found a letter for the first time
52 end = i
53 i -= 1
54
55 return end + 1 if end != -1 else 0
56
57 class Test(unittest.TestCase):
58 dataTrue = [('Hello World', 5), ('qwerte', 6), (' ', 0)]
59 dataFalse = [('Hello World', 7), ('qwerte', 2), (' ', 3)]
60
61 def test_length_of_last_word(self):
62 # true check
63 for test_data in self.dataTrue:
64 actual = length_of_last_word(test_data[0])
65 self.assertEqual(actual, test_data[1])
66
67 # false check
68 for test_data in self.dataFalse:
69 actual = length_of_last_word(test_data[0])
70 self.assertNotEqual(actual, test_data[1])
71
72 if __name__ == '__main__':
73 unittest.main()
74
75 def length_of_last_word(word):
76 if not word:
77 return None
78
79 i = len(word) - 1
80 end = -1
81
82 while i >= 0:
83 if word[i] == ' ' and end != -1:
84 return end - i
85
86 if word[i] != ' ' and end == -1:
87 end = i
88
89 i -= 1
90
91 return end + 1 if end != -1 else 0 | 75 - error: function-redefined
|
1 from collections import defaultdict
2
3 class Vertex:
4 def __init__(self, key):
5 self.id =key
6 self.connectedTo = {}
7
8 def add_neighbor(self, nbr, weight = 0):
9 self.connectedTo[nbr] = weight
10
11 def __str__(self):
12 return str(self.id) + ' connectedTo: ' + str([x.id for x in self.connectedTo])
13
14 def get_connections(self):
15 return self.connectedTo.keys()
16
17 def get_id(self):
18 return self.id
19
20 def get_weight(self, nbr):
21 return self.connectedTo[nbr]
22
23 class Graph:
24 def __init__(self):
25 self.vert_list = defaultdict(set)
26
27 def add(self, node1, node2):
28 self.vert_list[node1].add(node2)
29 self.vert_list[node2].add(node1)
30
31 def get_vertices(self):
32 return self.vert_list.keys()
33
34 def __iter__(self):
35 return iter(self.vert_list.keys())
36
37 def is_connected(self, node1, node2):
38 return node2 in self.vert_list[node1] and node1 in self.vert_list[node2]
39
| Clean Code: No Issues Detected
|
1 # 513
2
3 from utils.treeNode import TreeNode
4
5 # time: O(N)
6 # space: O(N)
7 class Solution:
8 def find_bottom_left_value(self, root):
9 level = [root]
10 most_left = None
11
12 while level:
13 most_left = level[0].value
14 new_level = []
15
16 for node in level:
17 if node.left:
18 new_level.append(node.left)
19
20 if node.right:
21 new_level.append(node.right)
22
23 level = new_level
24
25 return most_left
26
27 one = TreeNode(1)
28 two = TreeNode(2)
29 three = TreeNode(3)
30 four = TreeNode(4)
31 five = TreeNode(5)
32 six = TreeNode(6)
33 seven = TreeNode(7)
34
35 one.left = five
36 five.left = three
37 five.right = four
38 one.right = two
39 two.right = six
40 # six.right = seven
41
42 print(one)
43 print('===========')
44 solution = Solution()
45 print(solution.find_bottom_left_value(one)) | 7 - refactor: too-few-public-methods
|
1 from utils.treeNode import TreeNode
2
3 class Solution:
4 def get_level_order_traversal(self, root):
5 """
6 type root: TreeNode
7 rtype: List[List[Int]]
8 """
9 result = []
10 if not root:
11 return result
12
13 level_nodes = [root]
14 while level_nodes:
15 result.append([])
16 new_level_nodes = []
17
18 for node in level_nodes:
19 result[-1].append(node.value)
20
21 if node.left:
22 new_level_nodes.append(node.left)
23 if node.right:
24 new_level_nodes.append(node.right)
25
26 level_nodes = new_level_nodes
27
28 return result[::-1]
29
30 def get_level_order_traversal2(self, root):
31 result = []
32 if not root:
33 return result
34
35 self.helper(root, 0, result)
36 return result[::-1]
37
38 def helper(self, root, level, result):
39 if not root:
40 return
41
42 if len(result) == level:
43 # create a new array for this level
44 result.append([])
45
46 result[level].append(root.value)
47
48 self.helper(root.left, level + 1, result)
49 self.helper(root.right, level + 1, result)
50
51 node5 = TreeNode(5)
52 node4 = TreeNode(4)
53 node3 = TreeNode(3, node4, node5)
54 node2 = TreeNode(2)
55 node1 = TreeNode(1, node2, node3)
56 print(node1)
57 solution = Solution()
58 print(solution.get_level_order_traversal(node1))
| Clean Code: No Issues Detected
|
1 class Solution(object):
2 def parenthesis_generator(self, n):
3 """
4 :type n: int
5 :rtype: List[str]
6 """
7 result = []
8 self.generator_helper([], n, n, result)
9 return result
10
11 def generator_helper(self, curr, left, right, result):
12 if left == 0 and right == 0:
13 result.append(''.join(curr))
14 return
15
16 if left != 0:
17 curr.append('(')
18 self.generator_helper(curr, left - 1, right, result)
19 curr.pop()
20
21 if right > left:
22 curr.append(')')
23 self.generator_helper(curr, left, right - 1, result)
24 curr.pop()
25
26 solution = Solution()
27 print(solution.parenthesis_generator(3)) | 1 - refactor: useless-object-inheritance
|
1 from collections import Counter
2 import unittest
3
4 class Solution(object):
5 ### time: O(N**3), space: O(N)
6 def length_substring(self, string, k):
7 """
8 :type string: str
9 :type k: int
10 :rtype: int
11 """
12 if not string:
13 return 0
14
15 if k == 1:
16 return len(string) # return the length of the entire string
17
18 longest = 0
19
20 for i in range(1, len(string)): # iterate over the string
21 for j in range(0, i): # get all the possible susbstrings ending at i
22 substring = string[j: i + 1]
23 if self.is_valid_substring(substring, k): # check if the current substring meets the criteria
24 longest = max(longest, len(substring))
25
26 return longest
27
28 def is_valid_substring(self, substring, k):
29 """
30 :type substring: str
31 :type k: int
32 :rtype : boolean
33 """
34 frequencies = Counter(substring)
35 return all(frequencies[c] >= k for c in set(substring))
36
37 # time: O(N**3), space: O(N)
38 def length_substring2(self, string, k):
39 """
40 :type string: str
41 :type k: int
42 :rtype: int
43 """
44 if not string:
45 return 0
46
47 if k == 1:
48 return len(string) # return the length of the entire string
49
50 to_split = [string]
51 longest = 0
52
53 while to_split:
54 t = to_split.pop()
55 splitted = [t]
56 freq = Counter(t)
57 for c in freq:
58 if freq[c] < k:
59 new_splitted = []
60 for spl in splitted:
61 new_splitted += spl.split(c)
62 splitted = new_splitted
63
64 if len(splitted) == 1:
65 longest = max(longest, len(splitted[0]))
66 else:
67 to_split += [sub for sub in splitted if len(sub) > longest]
68
69 return longest
70
71 def length_substring4(self, s, k):
72 if not s or len(s) < k:
73 return 0
74
75 if k == 1:
76 return len(s)
77
78 longest = 0
79 to_split = [s]
80
81 while to_split:
82 t = to_split.pop()
83 frequencies = Counter(t)
84 new_splitted = []
85
86 for c in frequencies:
87 if frequencies[c] < k: # t is splittable
88 new_splitted += t.split(c)
89
90 if not new_splitted: # t is not splittable:
91 longest = max(longest, len(t))
92 else: # t was splittable, add the new splitted elements to to_split
93 to_split += [sp for sp in new_splitted if len(sp) > longest]
94
95 return longest
96
97 # recursive method
98 def length_substring3(self, string, k):
99 return self.helper(string, 0, len(string), k)
100
101 def helper(self, string, start, end, k):
102 if end - start < k:
103 return 0
104
105 substring = string[start : end]
106 freq = Counter(substring)
107 for i, c in enumerate(substring):
108 if freq[c] < k: # found an infrequent char, split by it
109 left = self.helper(string, start, i, k)
110 right = self.helper(string, i + 1, end, k)
111 return max(left, right)
112
113 return end - start # all chars are frequent
114
115
116 class Test(unittest.TestCase):
117 test_data = [('aaabb', 3, 3), ('ababbc', 2, 5), ('aabbccbcdeee', 3, 6)]
118 def test_length_substring(self):
119 solution = Solution()
120 for data in self.test_data:
121 actual = solution.length_substring4(data[0], data[1])
122 self.assertEqual(actual, data[2])
123
124 if __name__ == '__main__':
125 unittest.main()
| 4 - refactor: useless-object-inheritance
|
1 #time: O(N**2) - space: O(N)
2
3 class Solution:
4 def is_bypartite(self, graph):
5 colors = dict()
6 for node in range(len(graph)):
7 if node not in colors[node]:
8 colors[node] = 0
9 if not self.dfs(node, graph, colors):
10 return False
11
12 return True
13
14 def dfs(self, node, graph, colors):
15 for nbr in graph[node]:
16 if nbr in colors:
17 if colors[nbr] == colors[node]:
18 return False
19 else:
20 colors[nbr] = 1 - colors[node]
21
22 if not self.dfs(nbr, graph, colors):
23 return False
24
25 return True
26
27 | 5 - refactor: use-dict-literal
|
1 class Solution(object):
2 def get_third_max(self, numbers):
3 if not numbers:
4 return None
5
6 max1, max2, max3 = None, None, None
7
8 for num in numbers:
9 if num in (max1, max2, max3):
10 continue
11 elif not max1 or max1 < num:
12 max3 = max2
13 max2 = max1
14 max1 = num
15 elif not max2 or max2 < num:
16 max3 = max2
17 max2 = num
18 elif not max3 or max3 < num:
19 max3 = num
20
21 return max3 if max3 else max1
22
23 solution = Solution()
24 numbers = [3, 5, 8, 5, 5, 2, 5]
25 print(solution.get_third_max(numbers))
26
| 1 - refactor: useless-object-inheritance
2 - warning: redefined-outer-name
9 - refactor: no-else-continue
1 - refactor: too-few-public-methods
|
1 class Solution:
2 def pow(self, x, n):
3 if n == 0:
4 return 1
5 if n < 0:
6 n *= -1
7 x = 1/x
8 # return x * pow(x, n - 1)
9 return pow(x*x, n // 2) if n % 2 == 0 else x * pow(x * x, n // 2)
10
11 solution = Solution()
12 print(solution.pow(2, 3)) | 1 - refactor: too-few-public-methods
|
1 class Solution:
2 def generate_spiral(self, n):
3 if n <= 0:
4 raise Exception('n should be bigger than 0')
5
6 # matrix = [[0] * n] * n # for some reason this does not work
7 matrix = [[0 for _ in range(n)] for _ in range(n)]
8 row, col = 0, 0
9 d_row, d_col = 0, 1
10 for i in range(n ** 2):
11 matrix[row][col] = i + 1
12 next_row, next_col = row + d_row, col + d_col
13 if self.is_out_of_border(next_row, next_col, n) or matrix[next_row][next_col] != 0:
14 # the next cell is either out of border, or already processed. Change direction
15 d_row, d_col = d_col, - d_row
16 # move to the next cell
17 row += d_row
18 col += d_col
19
20 return matrix
21
22 def is_out_of_border(self, row, col, n):
23 return row < 0 or row == n or col < 0 or col == n
24
25 def print_matrix(self, matrix):
26 for row in matrix:
27 print(row)
28
29
30 solution = Solution()
31 solution.print_matrix(solution.generate_spiral(3)) | 4 - warning: broad-exception-raised
|
1 import unittest
2
3 def reverse_vowels(str):
4 if not str: return str
5
6 vowels = ['a', 'e', 'i', 'o', 'u']
7
8 list_str = list(str)
9
10 head, tail = 0, len(list_str) - 1
11
12 while head < tail:
13 if list_str[head].lower() not in vowels:
14 head += 1
15
16 elif list_str[tail].lower() not in vowels:
17 tail -= 1
18
19 else:
20 list_str[head], list_str[tail] = list_str[tail], list_str[head]
21 head += 1
22 tail -= 1
23
24 return ''.join(list_str)
25
26 print(reverse_vowels('leEtcode'))
27
28 class Solution:
29 vowels = ['a', 'e', 'i', 'o', 'u']
30
31 def reverse_vowels(self, string):
32 if not string:
33 return string
34
35 string_list = list(string)
36 head, tail = 0, len(string) - 1
37
38 while head < tail:
39 if string_list[head] not in self.vowels:
40 head += 1
41 elif string_list[tail] not in self.vowels:
42 tail -= 1
43 else:
44 string_list[head], string_list[tail] = string_list[tail], string_list[head]
45 head += 1
46 tail -= 1
47
48 return ''.join(string_list)
49 | 3 - warning: redefined-builtin
28 - refactor: too-few-public-methods
1 - warning: unused-import
|
1 #162
2
3 class Solution:
4 def get_peak(self, nums):
5 left, right = 0, len(nums) - 1
6 while left < right:
7 mid = (left + right) // 2
8 mid2 = mid + 1 # will not exceed len(nums) - 1 because left < right
9 if nums[mid] < nums[mid2]: #mid2 is potential peak
10 left = mid2 #notice how it is mid2 and not mid2+1
11 else: #mid is potential peak
12 right = mid #notice how it is mid and not mid - 1
13 return nums[left]
14
15 nums = [1, 2, 3, 1]
16 solution = Solution()
17 print(solution.get_peak(nums)) | 4 - warning: redefined-outer-name
3 - refactor: too-few-public-methods
|
1 from utils.treeNode import TreeNode
2
3 class TreeLinkNode(TreeNode):
4 def __init__(self, **kwargs):
5 super().__init__(**kwargs)
6 self.next = None
7
8
9 class Solution:
10 #O(N) time and space
11 def set_next_right_pointers(self, node):
12 if not node or not node.left:
13 return
14
15 # node has children
16 node.left.next = node.right
17
18 node.right.next = None if not node.next else node.next.left
19
20 self.set_next_right_pointers(node.right)
21 self.set_next_right_pointers(node.left)
22
23 #O(N) time and space
24 def set_next_right_pointers2(self, node):
25 level = [node]
26
27 while level and level[0]:
28 prev = None
29 next_level = []
30
31 for node in level:
32 if prev:
33 prev.next = node
34
35 prev = node
36
37 next_level.append(node.left)
38 next_level.append(node.right)
39
40 level = next_level
| 3 - refactor: too-few-public-methods
31 - refactor: redefined-argument-from-local
|
1 from utils.treeUtils import TreeNode
2
3 class Solution:
4 def build_tree(self, pre_order, in_order):
5 if not pre_order:
6 return None
7
8 return self.helper(0, 0, len(in_order) - 1, pre_order, in_order)
9
10 def helper(self, pre_start, in_start, in_end, pre_order, in_order):
11 if pre_start > len(pre_order) - 1 or in_start > in_end:
12 return None
13
14 value = pre_order[pre_start]
15 in_order_index = in_order.index(value)
16
17 root = TreeNode(value)
18 root.left = self.helper(pre_start + 1, in_start, in_order_index - 1, pre_order, in_order)
19 root.right = self.helper(pre_start + 1 + in_order_index - in_start, in_order_index + 1, in_end, pre_order, in_order)
20
21 return root
22
23 in_order = [4, 2, 5, 1, 3, 6, 7]
24 pre_order = [1, 2, 4, 5, 3, 6, 7]
25
26 solution = Solution()
27 print(solution.build_tree(pre_order, in_order))
28
| 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 class Solution(object):
2 def contains_duplicates(self, values, k):
3 hash_set = set()
4 for i, val in enumerate(values):
5 if i > k:
6 hash_set.remove(values[i - k - 1])
7 if val in hash_set:
8 return True
9 hash_set.add(val)
10
11 return False
12
13 solution = Solution()
14 values = [1, 2, 3, 4, 1, 7, 5]
15 print(solution.contains_duplicates(values, 3)) | 1 - refactor: useless-object-inheritance
2 - warning: redefined-outer-name
1 - refactor: too-few-public-methods
|
1 class Solution:
2 def surrond(self, matrix):
3 if not matrix or not matrix.rows_count or not matrix.cols_count:
4 return matrix
5
6 for row in range(matrix.rows_count):
7 self.dfs(row, 0, matrix)
8 self.dfs(row, matrix.cols_count - 1, matrix)
9
10 for col in range(matrix.cols_count):
11 self.dfs(0, col, matrix)
12 self.dfs(matrix.rows_count - 1, col, matrix)
13
14 for row in range(matrix.rows_count):
15 for col in range(matrix.cols_count):
16 if matrix[row][col] == 'O':
17 matrix[row][col] = 'X'
18 elif matrix[row][col] == '*':
19 matrix[row][col] = 'O'
20
21 def dfs(self, row, col, matrix):
22 if not matrix.is_valid_cell(row, col):
23 return
24
25 if matrix[row][col] != 'O':
26 return
27
28 matrix[row][col] = '*'
29
30 directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
31
32 for dr, dc in directions:
33 self.dfs(row + dr, col + dc, matrix)
| 2 - refactor: inconsistent-return-statements
|
1 #Gotcha: because int are immutable in python, changing it in a function does not update its value outside of this method
2 # therefore, we have to return its value from the function that changes it
3
4 class Solution(object):
5 def decode_ways(self, nums):
6 """
7 :type nums: str
8 :rtype: int
9 """
10
11 if not nums:
12 return 0
13
14 result = 0
15
16 result = self.decode_ways_count(nums, 0, result)
17
18 return result
19
20 def decode_ways_count(self, nums, index, result):
21 # went through all the digits in the string, increment the result count
22 if index == len(nums):
23 result += 1
24 elif nums[index] != '0':
25 # The digit at index is not 0, I can use it to get a character
26 result = self.decode_ways_count(nums, index + 1, result)
27
28 # Check if we can build a character using 2 digits
29 if index < len(nums) - 1 and 10 <= int(nums[index: index + 2]) <= 26:
30 result = self.decode_ways_count(nums, index + 2, result)
31
32 return result
33
34 def get_decode_ways(self, code):
35 """
36 type code: str
37 rtype: int
38 """
39 if not code:
40 return 0
41
42 ways = [0 for _ in range(len(code) + 1)]
43 ways[0] = 1
44 if code[0] != '0':
45 ways[1] = 1
46
47 for i in range(1, len(code)):
48 if code[i] != '0':
49 ways[i + 1] += ways[i]
50
51 if 10 <= int(code[i-1: i+1]) <= 26:
52 ways[i + 1] += ways[i - 1]
53
54 return ways[-1]
55
56 solution = Solution()
57 print(solution.decode_ways('12123'))
58 print(solution.get_decode_ways('12123'))
| 4 - refactor: useless-object-inheritance
|
1 from collections import defaultdict
2
3 class Solution:
4 def course_schedule(self, classes):
5 if not classes:
6 return[]
7
8 graph = self.build_graph(classes)
9
10 result = []
11 path = []
12 discovered = set()
13
14 for node in graph:
15 self.topological_sort(node, graph, path, discovered, result)
16
17 return result.reverse()
18
19 def build_graph(self, classes):
20 graph = defaultdict(set)
21 for dep in classes:
22 graph[dep[1]].add(dep[0])
23
24 return graph
25
26 def topological_sort(self, node, graph, path, discovered, result):
27 if node in discovered:
28 return
29
30 discovered.add(node)
31 path.append(node)
32
33 for nbr in graph[node]:
34 if nbr in path:
35 raise Exception('Cyclic dependency. Cannot finish all the courses')
36
37 self.topological_sort(nbr, graph, path, discovered, result)
38
39 result.append(result)
40 path.pop()
41
42
43 def can_finish(self, courses_count, prerequisites):
44 " Returns True if can finish all the courses "
45 nb_prerequisites = defaultdict(int) # mapping between each course and the number of its pre-requisites
46 preq_map = defaultdict(list) # mapping between each course and the courses depending on it
47
48 for after, before in prerequisites:
49 nb_prerequisites[after] += 1
50 preq_map[before].append(after)
51
52 # get the list of courses with no dependencies
53 can_take = set(range(courses_count)) - set(nb_prerequisites.keys())
54
55 while can_take:
56 course = can_take.pop()
57 courses_count -= 1
58 for dep in preq_map[course]:
59 nb_prerequisites[dep] -= 1
60 if nb_prerequisites[dep] == 0:
61 can_take.add(dep)
62
63 return courses_count == 0
64
65 def get_order(self, num_courses, prerequisites):
66 nb_prerequisites = defaultdict(int)
67 preq_list = defaultdict(list)
68
69 result = []
70
71 for (after, before) in prerequisites:
72 nb_prerequisites[after] += 1
73 preq_list[before].append(after)
74
75 can_take = set(i for i in range(num_courses)) - set(nb_prerequisites.keys())
76
77 while can_take:
78 course = can_take.pop()
79 result.append(course)
80
81 for dep in preq_list[course]:
82 nb_prerequisites[dep] -= 1
83 if nb_prerequisites[dep] == 0:
84 can_take.append(dep)
85
86 return result if len(result) == num_courses else []
| 26 - refactor: too-many-arguments
26 - refactor: too-many-positional-arguments
35 - warning: broad-exception-raised
65 - refactor: inconsistent-return-statements
|
1 from utils.matrix import Matrix
2
3 class Solution:
4 def get_islands_count(self, grid):
5 if not grid or not len(grid) or not len(grid[0]):
6 return 0
7
8 count = 0
9
10 for row in range(len(grid)):
11 for col in range(len(grid[0])):
12 if grid[row][col] == '1':
13 self.dfs(row, col, grid)
14 count += 1
15
16 return count
17
18 def dfs(self, row, col, grid):
19 """
20 type row: int
21 type col: int
22 type grid: Matrix
23 rtype: None
24 """
25 if not grid.is_valid_cell(row, col):
26 return
27
28 if grid[row][col] != '1':
29 return
30
31 grid[row][col] = 'X'
32
33 self.dfs(row - 1, col, grid)
34 self.dfs(row + 1, col, grid)
35 self.dfs(row, col + 1, grid)
36 self.dfs(row, col - 1, grid) | 1 - warning: unused-import
|
1 from utils.treeNode import TreeNode
2
3 class Solution:
4 #O(min(N1, N2)) time and space
5 def is_same_tree(self, node1, node2):
6 """
7 type node1: TreeNode
8 type node2: TreeNode
9 rtype: bool
10 """
11 if not node1 and not node2:
12 return True
13
14 if not node1 or not node2:
15 return False
16
17 if node1.value != node2.value:
18 return False
19
20 return self.is_same_tree(node1.left, node2.left) and self.is_same_tree(node1.right, node2.right)
21
| 3 - refactor: too-few-public-methods
1 - warning: unused-import
|
1 #24
2
3 from utils.listNode import ListNode
4
5 class Solution:
6 def swap_pairs(self, head):
7 if not head:
8 return None
9
10 dummy = prev = ListNode(None)
11
12 while head and head.next:
13 next_head = head.next.next
14 prev.next = head.next
15 head.next.next = head
16 prev = head
17 head = next_head
18
19 prev.next = head
20
21 return dummy.next
22
23 one = ListNode(1)
24 two = ListNode(2)
25 three = ListNode(3)
26 four = ListNode(4)
27
28 one.next = two
29 two.next = three
30 three.next = four
31
32 print(one)
33
34 solution = Solution()
35 print(solution.swap_pairs(one)) | 5 - refactor: too-few-public-methods
|
1 class Solution:
2 def get_kth_smallest(self, node, k):
3 count = self.count(node.left)
4
5 if k <= count:
6 return self.get_kth_smallest(node.left, k)
7
8 elif k > count + 1:
9 return self.get_kth_smallest(node.right, k - count - 1)
10
11 return node.value
12
13 def count(self, node):
14 if not node:
15 return 0
16
17 return 1 + self.count(node.left) + self.count(node.right)
18
19 def get_kth_smallest2(self, node, k):
20 stack = []
21
22 while node:
23 stack.append(node.value)
24 node = node.left
25
26 while stack:
27 node = stack.pop()
28 k -= 1
29 if k == 0:
30 return node.value
31
32 if node.right:
33 node = node.right
34 while node:
35 stack.append(node)
36 node = node.left
37
38 def get_kth_smallest3(self, node, k):
39 self.k = k
40 self.result = None
41 self.helper(node)
42 return self.result
43
44 def helper(self, node):
45 if not node:
46 return
47
48 self.helper(node.left)
49
50 self.k -= 1
51
52 if self.k == 0:
53 self.result = node.value
54 return
55
56 self.helper(node.right)
57
58 def get_kth_smallest(root, k):
59 left_count = get_count(root.left)
60
61 if left_count <= k:
62 return get_kth_smallest(root.left, k)
63
64 if left_count == k + 1:
65 return root.value
66
67 return get_kth_smallest(root.right, k - left_count - 1)
68
69 def get_count(root):
70 if not root:
71 return 0
72
73 return 1 + get_count(root.left) + get_count(root.right)
74
75 def get_kth_smallest4(root, k):
76 stack = []
77
78 while root:
79 stack.append(root)
80 root = root.left
81
82 while stack:
83 node = stack.pop()
84 k -= 1
85 if k == 0:
86 return node.value
87
88 if node.right:
89 node = node.right
90 while node:
91 stack.append(node)
92 node = node.left
93
| 5 - refactor: no-else-return
19 - refactor: inconsistent-return-statements
39 - warning: attribute-defined-outside-init
40 - warning: attribute-defined-outside-init
53 - warning: attribute-defined-outside-init
75 - refactor: inconsistent-return-statements
|
1 class Solution(object):
2 # O(N) time and space
3 def rotate_array(self, numbers, k):
4 """
5 :type numbers: List[int]
6 :type k: int
7 :rtype: List[int]
8 """
9 n = len(numbers)
10 if k > n:
11 raise ValueError('The array is not long enough to be rotated')
12 return numbers[n - k:] + numbers[:n - k]
13
14 # O(N) time, O(1) time
15 def rotate_array2(self, numbers, k):
16 """
17 :type numbers: List[int]
18 :type k: int
19 :rtype: List[int]
20 """
21 n = len(numbers)
22 if k > n:
23 raise ValueError('The array is not long enough')
24 self.reverse(numbers, 0, n - 1)
25 self.reverse(numbers, 0, k - 1)
26 self.reverse(numbers, k, n - 1)
27
28 def reverse(self, numbers, left, right):
29 while left < right:
30 numbers[left], numbers[right] = numbers[right], numbers[left]
31 left += 1
32 right -= 1
33
34
35 solution = Solution()
36 # print(solution.rotate_array([1,2,3,4,5,6,7], 1))
37 numbers = [1,2,3,4,5,6,7]
38 solution.rotate_array2(numbers, 3)
39 print(numbers)
| 1 - refactor: useless-object-inheritance
3 - warning: redefined-outer-name
15 - warning: redefined-outer-name
28 - warning: redefined-outer-name
|
1 class Solution:
2 def repeated_string_pattern(self, string):
3 if not string:
4 return False
5
6 length = len(string)
7
8 for i in range(2, (length // 2) + 1):
9 pattern_length = length // i
10 if length % i == 0 and all(string[j * pattern_length : (j + 1) * pattern_length] == string[:pattern_length] for j in range(i)):
11 return True
12
13 return False
14
15 def repeated_string_pattern2(self, string):
16 if not string:
17 return False
18
19 return string in (string * 2)[1 : -1]
20
21 solution = Solution()
22 print(solution.repeated_string_pattern2('ababab'))
| Clean Code: No Issues Detected
|
1 #669
2
3 from utils.treeNode import TreeNode
4
5 class Solution:
6 def trim(self, root, l, r):
7 if not root:
8 return root
9
10 if root.value < l:
11 return self.trim(root.right, l, r)
12
13 if root.value > r:
14 return self.trim(root.left, l, r)
15
16 root.left, root.right = self.trim(root.left, l, r), self.trim(root.right, l, r)
17 return root
18
19
20 class Solution2:
21 def trim(self, root, l, r):
22 if not root:
23 return root
24
25 root.left, root.right = self.trim(root.left, l, r), self.trim(root.right, l, r)
26
27 if root.value < l:
28 return root.right
29
30 if root.value > r:
31 return root.left
32
33 return root
34
35 # one = TreeNode(1)
36 # zero = TreeNode(0)
37 # two = TreeNode(2)
38
39 # one.left = zero
40 # one.right = two
41
42 one = TreeNode(1)
43 zero = TreeNode(0)
44 two = TreeNode(2)
45 three = TreeNode(3)
46 four = TreeNode(4)
47
48 three.left = zero
49 zero.right = two
50 two.left = one
51 three.right = four
52
53 print(three)
54 print('=============')
55 solution = Solution()
56 print(solution.trim(three, 1, 3)) | 5 - refactor: too-few-public-methods
20 - refactor: too-few-public-methods
|
1 class Solution:
2 # time: O(N) worst case, O(height) average
3 # space: O(N) worst case, O(height) average
4 def delete_node(self, root, value):
5 if not root:
6 return None
7
8 if root.value > value:
9 root.left = self.delete_node(root.left, value)
10 elif root.value < value:
11 root.right = self.delete_node(root.right, value)
12 else:
13 if not root.left or not root.right:
14 # one or no children
15 root = root.left or root.right
16 else:
17 # has both children
18 next_biggest = root.right
19 while next_biggest.left:
20 next_biggest = next_biggest.left
21 root.value = next_biggest.value
22 root.right = self.delete_node(root.right, root.value)
23
24 return root
25
| 1 - refactor: too-few-public-methods
|
1 from utils.listNode import ListNode
2
3 class Solution:
4 def reverse(self, head, m, n):
5 if not head:
6 return head
7
8 dummy = prev = ListNode(None)
9 node = head
10 rev, rev_tail = None, None
11
12 count = 1
13 while node:
14 if count > n:
15 rev_tail.next = node
16 break
17
18 if count >= m:
19 if count == m: # set the rev tail
20 rev_tail = node
21 rev, rev.next, node = node, rev, node.next
22 prev.next = rev
23
24 else:
25 prev.next = node
26 prev = prev.next
27 node = node.next
28
29 count += 1
30
31 return dummy.next
32
33 one = ListNode(1)
34 two = ListNode(2)
35 three = ListNode(3)
36 four = ListNode(4)
37 five = ListNode(5)
38
39 one.next = two
40 two.next = three
41 three.next = four
42 four.next = five
43
44 print(one)
45
46 solution = Solution()
47 print(solution.reverse(one, 2, 4))
48
49
| 3 - refactor: too-few-public-methods
|
1 from utils.treeNode import TreeNode
2
3 class Solution:
4 def get_unique_bst(self, n):
5 result = []
6 if n <= 0:
7 return result
8
9 return self.get_unique_bst_helper(1, n)
10
11 def get_unique_bst_helper(self, start, end):
12 result = []
13
14 if start > end:
15 return [None] # return [None] so that I can get in the for lefts and rights loops below
16
17 for i in range(start, end + 1):
18 lefts = self.get_unique_bst_helper(start, i - 1)
19 rights = self.get_unique_bst_helper(i + 1, end)
20
21 for left in lefts:
22 for right in rights:
23 root = TreeNode(i, left, right)
24 result.append(root)
25
26 return result
27
28 solution = Solution()
29 print(solution.get_unique_bst(3)) | Clean Code: No Issues Detected
|
1 from utils.interval import Interval
2
3 class Solution:
4 def merge_intervals(self, intervals):
5 """
6 type: intervals: List[Interval]
7 rtype: List[Interval]
8 """
9 result = []
10 intervals.sort(key=lambda interval:interval.start)
11 for interval in intervals:
12 if not result or interval.start > result[-1].end:
13 result.append(interval)
14 else:
15 result[-1].end = max(result[-1].end, interval.end)
16
17 return result
18
19
20 interval1 = Interval(2, 5)
21 interval2 = Interval(7, 10)
22 interval3 = Interval(4, 6)
23 intervals = [interval1, interval3, interval2]
24 print(intervals)
25 solution = Solution()
26 print(solution.merge_intervals(intervals)) | 4 - warning: redefined-outer-name
3 - refactor: too-few-public-methods
|
1 class Solution(object):
2 def remove_element(self, arr, val):
3 if not arr:
4 return 0
5
6 j = 0
7 for i in range(len(arr)):
8 if arr[i] != val:
9 arr[j] = arr[i]
10 j += 1
11
12 for i in range(len(arr) - j):
13 arr.pop()
14
15 return j
16
17 solution = Solution()
18 arr = [1, 2, 3, 2, 4, 5]
19 print(solution.remove_element(arr, 2))
20 print(arr)
| 1 - refactor: useless-object-inheritance
2 - warning: redefined-outer-name
1 - refactor: too-few-public-methods
|
1 class Solution:
2 def combination_sum_unlimited(self, nums, target):
3 '''
4 In this method, each number can be used an unlimited time
5 type nums: List[int]
6 type target: int
7 rtype: List[List[int]
8 '''
9 nums.sort()
10 results = []
11 # for i, num in enumerate(nums):
12 # self.helper(nums, num, [nums[i]], i, target, results)
13 self.backtrack_unlimited(nums, target, [], 0, results)
14 return results
15
16 def helper(self, nums, sum, partial, index, target, results):
17 if sum > target:
18 return
19
20 if sum == target: # found a solution
21 results.append(partial)
22 return
23
24 self.helper(nums, sum + nums[index], partial + [nums[index]], index, target, results) ## add the number to current sum
25
26 if index < len(nums) - 1:
27 self.helper(nums, sum + nums[index + 1], partial + [nums[index + 1]], index + 1, target, results) # move to the next number
28
29 def backtrack_unlimited(self, nums, remainder, partial, start, results):
30 if remainder < 0:
31 return
32
33 if remainder == 0:
34 results.append(partial)
35 return
36
37 for i in range(start, len(nums)):
38 self.backtrack_unlimited(nums, remainder - nums[i], partial + [nums[i]], i, results)
39
40 def combination_sum_once(self, nums, target):
41 nums.sort()
42 results = []
43 self.backtrack_once(nums, target, [], 0, results)
44 return results
45
46 def backtrack_once(self, nums, remainder, partial, start, results):
47 if remainder < 0:
48 return
49
50 if remainder == 0:
51 results.append(partial)
52 return
53
54 for i in range(start, len(nums)):
55 self.backtrack_once(nums, remainder - nums[i], partial + [nums[i]], i + 1, results)
56
57
58 solution = Solution()
59 nums = [2, 6, 5, 3, 7]
60 # print(solution.combination_sum_unlimited(nums, 7))
61 print(solution.combination_sum_once(nums, 7))
62
63
| 2 - warning: redefined-outer-name
16 - refactor: too-many-arguments
16 - refactor: too-many-positional-arguments
16 - warning: redefined-outer-name
16 - warning: redefined-builtin
29 - refactor: too-many-arguments
29 - refactor: too-many-positional-arguments
29 - warning: redefined-outer-name
40 - warning: redefined-outer-name
46 - refactor: too-many-arguments
46 - refactor: too-many-positional-arguments
46 - warning: redefined-outer-name
|
1 #814
2
3 from utils.treeNode import TreeNode
4
5 class Solution:
6 def prune(self, root):
7 if not root:
8 return root
9
10 root.left, root.right = self.prune(root.left), self.prune(root.right)
11
12 return root if root.value == 1 or root.left or root.right else None
13
14 | 5 - refactor: too-few-public-methods
3 - warning: unused-import
|
1 from utils.matrix import Matrix
2
3 class Solution:
4 def traverse(self, matrix):
5 """
6 :type matrix: Matrix
7 :rtype: List[int]
8 """
9 if not matrix.row_count or not matrix.col_count:
10 return
11
12 row, col = 0, 0
13 d_row, d_col = -1, 1
14 result = []
15 for _ in range(matrix.row_count * matrix.col_count):
16 result.append(matrix[row][col])
17 row += d_row
18 col += d_col
19 if not self.is_valid_cell(row, col, matrix):
20 if col == matrix.col_count:
21 col -= 1
22 row += 2
23 elif row < 0:
24 row = 0
25 elif row == matrix.row_count:
26 row -= 1
27 col += 2
28 elif col < 0:
29 col = 0
30 d_row, d_col = d_col, d_row
31 return result
32
33 def is_valid_cell(self, row, col, matrix):
34 return (
35 row >= 0 and row < matrix.row_count and
36 col >= 0 and col < matrix.col_count
37 )
38
39 # matrix = Matrix([[1,2,3],[4,5,6]])
40 matrix = Matrix([[1,2,3],[4,5,6], [7,8,9]])
41 print(matrix)
42 solution = Solution()
43 print(solution.traverse(matrix)) | 4 - warning: redefined-outer-name
4 - refactor: inconsistent-return-statements
33 - warning: redefined-outer-name
35 - refactor: chained-comparison
|
1 class Solution:
2 def get_duplicate(self, nums):
3 if not nums:
4 return
5
6 slow = nums[0]
7 fast = nums[slow] # which is nums[nums[0]]
8 while slow != fast:
9 slow = nums[slow]
10 fast = nums[nums[fast]]
11
12 fast = 0
13 while slow != fast:
14 slow = nums[slow]
15 fast = nums[fast]
16
17 return fast
18
19 nums = [1, 3, 2, 4, 3]
20 solution = Solution()
21 print(solution.get_duplicate(nums)) | 2 - warning: redefined-outer-name
2 - refactor: inconsistent-return-statements
1 - refactor: too-few-public-methods
|
1 class Solution:
2 # O(N) time - O(1) space
3 def climb_stairs(self, n):
4 if n < 0:
5 return 0
6
7 if n <= 2:
8 return n
9
10 curr, prev = 2, 1
11 for _ in range(2, n):
12 curr, prev = curr + prev, curr
13
14 return curr
15
16 def climbStairs3(self, n):
17 """
18 :type n: int
19 :rtype: int
20 """
21 if n < 0:
22 return 0
23
24 if n <= 2:
25 return n
26
27 curr, prev = 1, 1
28
29 for i in range(2, n + 1):
30 curr, prev = curr + prev, curr
31
32 return curr
33
34 # O(N) time - O(N) space
35 def climb_stairs2(self, n):
36 memo = [0] + [-1 for _ in range(n)]
37 return self.stairs(n, memo)
38
39 def stairs(self, n, memo):
40 if n < 0:
41 return 0
42
43 if n <= 2:
44 return n
45
46 if memo[n] != -1:
47 return memo[n]
48
49 result = self.stairs(n - 1, memo) + self.stairs(n - 2, memo)
50 memo[n] = result
51 return result
52
53
54
55 solution = Solution()
56 for i in range(7):
57 print("climb_stairs({}) = {}".format(i, solution.climb_stairs2(i))) | 29 - warning: redefined-outer-name
29 - warning: unused-variable
|
1 from utils.listNode import ListNode
2
3 class Solution:
4 def rotate(self, head, k):
5 if not head:
6 return None
7
8 count, node = 1, head
9 while node.next:
10 node = node.next
11 count += 1
12
13 # link the end and the start of the list
14 node.next = head
15
16 to_move = count - (k % count)
17
18 while to_move > 0:
19 node = node.next
20 to_move -= 1
21
22 # next is the new last element of the list
23 head = node.next
24 node.next = None
25
26 return head
27
28
29 one = ListNode(1)
30 two = ListNode(2)
31 three = ListNode(3)
32 four = ListNode(4)
33 five = ListNode(5)
34
35 one.next = two
36 two.next = three
37 three.next = four
38 four.next = five
39
40 print(one)
41 solution = Solution()
42 print(solution.rotate(one, 6)) | 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_symetric(self, root):
6 """
7 type root: TreeNode
8 rtype: bool
9 """
10 if not root:
11 return True
12
13 return self.is_mirror(root.left, root.right)
14
15 def is_mirror(self, node1, node2):
16 if not node1 and not node2:
17 return True
18
19 if not node1 or not node2:
20 return False
21
22 if node1.value != node2.value:
23 return False
24
25 return self.is_mirror(node1.left, node2.right) and self.is_mirror(node1.right, node2.left) | 1 - warning: unused-import
|
1 class Solution:
2 def get_min_length(self, nums, target):
3 """
4 type nums: List[int]
5 type target: int
6 :rtype : int
7 """
8 min_length, sum_so_far, start = len(nums), 0, 0
9 for i, num in enumerate(nums):
10 sum_so_far += num
11 while sum_so_far - nums[start] >= target:
12 sum_so_far -= nums[start]
13 start += 1
14 min_length = min(min_length, i - start + 1)
15
16 return min_length if min_length < len(nums) else 0
17
18 solution = Solution()
19 nums = [2, 3, 1, 2, 4, 3]
20 print(solution.get_min_length(nums, 7)) | 2 - warning: redefined-outer-name
1 - refactor: too-few-public-methods
|
1 class Solution(object):
2 def dissapeared_numbers(self, numbers):
3 if not numbers:
4 return []
5
6 n = len(numbers)
7 result = [i for i in range(1, n + 1)]
8
9 for num in numbers:
10 result[num - 1] = 0
11
12 self.delete_zeros(result)
13 return result
14
15 def delete_zeros(self, arr):
16 insert_pos = 0
17 for num in arr:
18 if num != 0:
19 arr[insert_pos] = num
20 insert_pos += 1
21
22 for _ in range(insert_pos, len(arr)):
23 arr.pop()
24
25 def dissapeared_numbers2(self, numbers):
26 if not numbers:
27 return []
28
29 for i, num in enumerate(numbers):
30 val = abs(num) - 1
31 if (numbers[val] > 0):
32 numbers[val] = - numbers[val]
33
34 result = []
35 for i, num in enumerate(numbers):
36 if num >= 0:
37 result.append(i + 1)
38
39 return result
40
41 solution = Solution()
42 numbers = [4, 3, 2, 7, 8, 2, 3, 1]
43 print(solution.dissapeared_numbers2(numbers)) | 1 - refactor: useless-object-inheritance
2 - warning: redefined-outer-name
7 - refactor: unnecessary-comprehension
25 - warning: redefined-outer-name
|
1 # 581
2
3 #time: O(N log N)
4 # space: O(N)
5 class Solution:
6 def shortest_subarray(self, nums):
7 if not nums:
8 return []
9
10 s_nums = sorted(nums)
11 left, right = len(nums) - 1, 0
12
13 for i in range(len(nums)):
14 if nums[i] != s_nums[i]:
15 left = min(left, i)
16 right = max(right, i)
17
18 return right - left + 1 if right >= left else 0
19
20 nums = [2, 6, 4, 8, 10, 9, 15]
21 solution = Solution()
22 print(solution.shortest_subarray(nums)) | 6 - warning: redefined-outer-name
5 - refactor: too-few-public-methods
|
1 from utils.treeNode import TreeNode
2
3 class Solution:
4 def get_paths_sum(self, node, target):
5 result = []
6 if not node:
7 return result
8
9 self.get_paths_helper([], target, node, result)
10
11 return result
12
13 def get_paths_helper(self, path, target, node, result):
14 if not node:
15 return
16
17 target -= node.value
18 path.append(node.value)
19
20 if target == 0 and not node.left and not node.right:
21 result.append(path[:]) # import to add a new copy of path, because path will change
22
23 self.get_paths_helper(path, target, node.left, result)
24 self.get_paths_helper(path, target, node.right, result)
25
26 path.pop()
27 | 1 - warning: unused-import
|
1 from utils.matrix import Matrix
2
3 class RangeSumQuery:
4 def __init__(self, matrix):
5 """
6 :type matrix: Matrix
7 :rtype: None
8 """
9 matrix_sum = [[0 for _ in range(matrix.col_count + 1)] for _ in range(matrix.row_count + 1)]
10 for row in range(1, matrix.row_count + 1):
11 for col in range(1, matrix.col_count + 1):
12 matrix_sum[row][col] = (
13 matrix[row - 1][col - 1]
14 + matrix_sum[row][col - 1]
15 + matrix_sum[row - 1][col]
16 - matrix_sum[row - 1][col - 1]
17 )
18
19 self.matrix_sum = Matrix(matrix_sum)
20 print(self.matrix_sum)
21
22 def get_range_sum(self, row1, col1, row2, col2):
23 return (
24 self.matrix_sum[row2 + 1][col2 + 1]
25 - self.matrix_sum[row1][col2 + 1]
26 + self.matrix_sum[row1][col1]
27 - self.matrix_sum[row2 + 1][col1]
28 )
29
30 matrix = Matrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]])
31 print("Matrix = {}".format(matrix))
32 rangeSumQuery = RangeSumQuery(matrix)
33 print(rangeSumQuery.get_range_sum(2, 1, 4, 3))
34 print(rangeSumQuery.get_range_sum(1, 1, 2, 2))
35 print(rangeSumQuery.get_range_sum(1, 2, 2, 4))
| 4 - warning: redefined-outer-name
3 - refactor: too-few-public-methods
|
1 from utils.matrix import Matrix
2 import unittest
3
4 class Solution:
5 def search(self, matrix, value):
6 if value < matrix[0][0] or value > matrix[-1][-1]:
7 return False
8
9 row = self.get_row(matrix, value)
10 return self.binary_search_row(matrix[row], value)
11
12 def get_row(self, matrix, value):
13 left, right = 0, matrix.row_count - 1
14 while left <= right:
15 mid = (left + right) // 2
16 if value < matrix[mid][0]:
17 right = mid - 1
18 elif value > matrix[mid][-1]:
19 left = mid + 1
20 else:
21 return mid
22 return left
23
24 def binary_search_row(self, nums, value):
25 left, right = 0, len(nums) - 1
26 while left <= right:
27 mid = (right + left) // 2
28 if value == nums[mid]:
29 return True
30 if value > nums[mid]:
31 left = mid + 1
32 else:
33 right = mid - 1
34 return False
35
36 #time: O(col_count + row_count) - space: O(1)
37 def search2(self, matrix, value):
38 row, col = matrix.row_count - 1, 0
39 while row >= 0 and col < matrix.col_count:
40 if matrix[row][col] == value:
41 return True
42 elif value < matrix[row][col]:
43 row -= 1
44 else:
45 col += 1
46 return False
47
48 class Test(unittest.TestCase):
49 matrix = Matrix([[1,3,5,7],[10,11,16,20],[23,30,34,50]])
50 test_data = [(3, True), (9, False), (0, False), (56, False), (30, True)]
51
52 def test_search(self):
53 solution = Solution()
54 for data in self.test_data:
55 actual = solution.search2(self.matrix, data[0])
56 self.assertEqual(actual, data[1])
57
58 if __name__ == '__main__':
59 unittest.main()
| 40 - refactor: no-else-return
|
1 from utils.treeNode import TreeNode
2 from utils.treeUtils import generate_tree
3
4 class Solution:
5 def __init__(self):
6 self.prev = None
7
8 def flatten(self, node):
9 if not node:
10 return None
11
12 self.prev = node
13 self.flatten(node.left)
14
15 temp = node.right
16 node.right = node.left
17 node.left = None
18
19 self.prev.right = temp
20 self.flatten(self.prev.right)
21
22 root = generate_tree()
23 print(root)
24 print('==============')
25 solution = Solution()
26 solution.flatten(root)
27 print(root) | 8 - refactor: inconsistent-return-statements
4 - refactor: too-few-public-methods
1 - warning: unused-import
|
1 class Solution:
2
3 # M = len(difficulties), N = len(workers)
4 # time = O(M log M + N log N + M + N), but can omit the M and N
5 # space = O(M)
6 def max_profit_assignment(self, difficulty, profits, workers):
7 jobs = list(zip(difficulty, profits))
8 jobs.sort() # will sort by the first tuple element
9 index, best_so_far, result = 0, 0, 0
10
11 for worker in sorted(workers):
12 while index < len(jobs) and worker >= jobs[index][0]:
13 best_so_far = max(best_so_far, jobs[index][1])
14 index += 1
15
16 result += best_so_far
17
18 return result
19
20 difficulty = [2,4,6,8,10]
21 profits = [10,20,30,40,50]
22 workers = [4,5,6,7]
23
24 solution = Solution()
25 print(solution.max_profit_assignment(difficulty, profits, workers)) | 6 - warning: redefined-outer-name
6 - warning: redefined-outer-name
6 - warning: redefined-outer-name
1 - refactor: too-few-public-methods
|
1 class Solution:
2 def get_insert_position(self, nums, value):
3 left, right = 0, len(nums) - 1
4 # left <= right because we want the first occurrence of left > right, aka, left is bigger than value
5 while left <= right:
6 mid = (left + right) // 2
7 if mid == value:
8 return mid
9 if mid < value:
10 left = mid + 1
11 else:
12 right = mid - 1
13 return left
14
15 def get_insert_position2(self, nums, value):
16 left, right = 0, len(nums) - 1
17
18 while left <= right:
19 mid = (left + right) // 2
20
21 if nums[mid] > value:
22 right = mid - 1
23 else:
24 left = mid + 1
25
26 return left
27
28 nums = [1, 2, 3, 3, 5, 8]
29 solution = Solution()
30 print(solution.get_insert_position2(nums, 8))
| 2 - warning: redefined-outer-name
15 - warning: redefined-outer-name
|
1 from utils.treeNode import TreeNode
2
3 class Solution:
4 # time: O(N) - space: O(N)
5 def build_binary_tree(self, nums):
6 if not nums:
7 return None
8
9 return self.convert(nums, 0, len(nums) - 1)
10
11 def convert(self, nums, left, right):
12 if left > right:
13 return None
14
15 mid = (left + right) // 2
16 left = self.convert(nums, left, mid - 1)
17 right = self.convert(nums, mid + 1, right)
18 root = TreeNode(nums[mid], left, right)
19
20 return root
21
22 nums = [1,2,3,4,5,6,7,8,9]
23 solution = Solution()
24 print(solution.build_binary_tree(nums)) | 5 - warning: redefined-outer-name
11 - warning: redefined-outer-name
|
1 from utils.treeNode import TreeNode
2 from utils.treeUtils import generate_tree
3
4 class Solution:
5 def in_order_traversal(self, node):
6 result = []
7 self.in_order_rec(node, result)
8 return result
9
10 def in_order_rec(self, node, result):
11 if not node:
12 return
13
14 self.in_order_rec(node.left, result)
15
16 result.append(node.value)
17
18 self.in_order_rec(node.right, result)
19
20 def in_order_traversal2(self, node):
21 result = []
22 if not node:
23 return result
24
25 stack = []
26 while node or stack:
27 if node:
28 stack.append(node)
29 node = node.left
30 continue
31
32 node = stack.pop()
33 result.append(node.value)
34 node = node.right
35
36 return result
37
38 def in_order_traversal3(self, node):
39 stack, result = [], []
40 while node:
41 stack.append(node)
42 node = node.left
43
44 while stack:
45 node = stack.pop()
46 result.append(node.value)
47
48 if node.right:
49 node = node.right
50 while node:
51 stack.append(node)
52 node = node.left
53
54 return result
55
56
57
58 root = generate_tree()
59 print(root)
60 solution = Solution()
61 print(solution.in_order_traversal3(root)) | 1 - warning: unused-import
|
1 class Solution:
2 # Time: O(2 ** n), space(n * 2**n)
3 def generate_subsets_from_unique(self, nums):
4 result = []
5 self.backtrack(nums, [], 0, result)
6 return result
7
8 def generate_subsets_from_duplicates(self, nums):
9 result = []
10 nums.sort()
11 self.backtrack(nums, [], 0, result)
12 return result
13
14 def backtrack(self, nums, prefix, start, result):
15 result.append(prefix)
16 for i in range(start, len(nums)):
17 if i > start and nums[i] == nums[i-1]:
18 continue
19 self.backtrack(nums, prefix + [nums[i]], i + 1, result)
20
21 solution = Solution()
22 nums = [1,2,3]
23 # nums = [1,2,2]
24 print(solution.generate_subsets_from_unique(nums)) | 3 - warning: redefined-outer-name
8 - warning: redefined-outer-name
14 - warning: redefined-outer-name
|
1 #442
2
3 class Solution:
4 def get_duplicates(self, nums):
5 if not nums:
6 return None
7 result = []
8 for num in nums:
9 index = abs(num) - 1
10 if nums[index] < 0:
11 result.append(abs(num))
12 else:
13 nums[index] *= -1
14 return result
15
16 solution = Solution()
17 nums = [4, 3, 2, 7, 8, 2, 4, 1]
18 print(solution.get_duplicates(nums)) | 4 - warning: redefined-outer-name
3 - refactor: too-few-public-methods
|
1 # 623
2
3 from utils.treeNode import TreeNode
4
5 # time: O(N)
6 # space: O(N) or the max number of node at each level
7 class Solution:
8 def add_row(self, root, v, d):
9 if d == 1:
10 new_root = TreeNode(v)
11 new_root.left = root
12 return new_root
13
14 current_level = [root]
15 while d > 2:
16 d -= 1
17 new_level = []
18 for node in current_level:
19 if node.left:
20 new_level.append(node.left)
21
22 if node.right:
23 new_level.append(node.right)
24
25 current_level = new_level
26
27 # current_level is at d - 1
28 for node in current_level:
29 node.left, node.left.left = TreeNode(v), node.left
30 node.right, node.right.right = TreeNode(v), node.right
31
32
33 return root
34
35 # one = TreeNode(1)
36 # two = TreeNode(2)
37 # three = TreeNode(3)
38 # four = TreeNode(4)
39 # five = TreeNode(5)
40 # six = TreeNode(6)
41
42 # four.left = two
43 # four.right = six
44 # two.left = three
45 # two.right = one
46 # six.left = five
47
48 one = TreeNode(1)
49 two = TreeNode(2)
50 three = TreeNode(3)
51 four = TreeNode(4)
52 five = TreeNode(5)
53 six = TreeNode(6)
54
55 four.left = two
56 # four.right = six
57 two.left = three
58 two.right = one
59 # six.left = five
60
61 print(four)
62
63 print('==============')
64
65 solution = Solution()
66 print(solution.add_row(four, 1, 3))
| 7 - refactor: too-few-public-methods
|
1 import unittest
2
3 class Solution(object):
4 def search_insert_position(self, arr, val):
5 if not arr:
6 return 0
7
8 for i, d in enumerate(arr):
9 if d >= val:
10 return i
11
12 return len(arr)
13
14 def search_insert_position2(self, arr, val):
15 if not arr:
16 return 0
17
18 left, right = 0, len(arr) - 1
19 while left <= right:
20 mid = (left + right) // 2
21 if arr[mid] == val:
22 return mid
23 elif arr[mid] < val:
24 left = mid + 1
25 else:
26 right = mid - 1
27
28 return left
29
30 class Test(unittest.TestCase):
31 arr = [1, 3, 5, 6]
32 test_data = [(5, 2), (2, 1), (7, 4), (0, 0)]
33
34 def test_search_insert_positiion(self):
35 solution = Solution()
36
37 for data in self.test_data:
38 self.assertEqual(solution.search_insert_position2(self.arr, data[0]), data[1])
39
40 if __name__ == '__main__':
41 unittest.main()
| 3 - refactor: useless-object-inheritance
21 - refactor: no-else-return
|
1 class Solution:
2 def get_max_profit(self, prices):
3 if not prices:
4 return 0
5
6 max_profit, max_here = 0, 0
7 for i in range(1, len(prices)):
8 max_here = max(max_here + prices[i] - prices[i - 1], 0)
9 max_profit = max(max_profit, max_here)
10 return max_profit
11
12 def get_max_profit2(self, prices):
13 if not prices:
14 return 0
15
16 buy, sell = float('-inf'), 0
17
18 for price in prices:
19 buy = max(buy, - price)
20 sell = max(sell, price + buy)
21
22 return sell | 1 - refactor: too-few-public-methods
12 - warning: unused-argument
|
1 class Solution:
2 def can_partition(self, nums):
3 sum_nums = sum(nums)
4 if sum_nums % 2:
5 return False
6
7 target = sum_nums // 2
8 nums.sort(reverse = True) #Try the largest numbers first, since less operations to reach the target
9 subset_sum = [True] + [False for _ in range(target)]
10
11 for num in nums:
12 for i in range(target - 1, -1, -1): # Try the largest sums first
13 if num + i <= target and subset_sum[i]:
14 if i + num == target:
15 return True
16 subset_sum[num + i] = True
17
18 return False
| 1 - refactor: too-few-public-methods
|
1 class Solution:
2 def count_nodes(self, node):
3 if not node:
4 return 0
5
6 left_depth, right_depth = self.get_depth(node.left), self.get_depth(node.right)
7
8 if left_depth == right_depth:
9 #left side is complete
10 return 2 ** (left_depth) + self.count_nodes(node.right)
11 else:
12 # right side is complete
13 return 2 ** (right_depth) + self.count_nodes(node.left)
14
15 def get_depth(self, node):
16 depth = 0
17 while node:
18 depth += 1
19 node = node.left
20
21 return depth
22
23
| 8 - refactor: no-else-return
|
1 # 830
2
3 class Solution:
4 def position_of_large_groups(self, chars):
5 result, start = [], 0
6
7 for i in range(len(chars)):
8 if i == len(chars) - 1 or chars[i] != chars[i + 1]:
9 if i - start + 1 >= 3:
10 result.append([start, i])
11
12 start = i + 1
13
14 return result
15
16
17
18 chars = "abcdddeeeeaabbbcd"
19 solution = Solution()
20 print(solution.position_of_large_groups(chars)) | 4 - warning: redefined-outer-name
3 - refactor: too-few-public-methods
|
1 class Solution:
2 def sum_target(self, collection1, collection2, target):
3 result = []
4 sum_dict = dict()
5
6 for nums in [collection1, collection2]:
7 for num in nums:
8 remaining = target - num
9 if remaining in sum_dict:
10 result.append((remaining, num))
11 if sum_dict[remaining] == 1:
12 del sum_dict[remaining]
13 else:
14 sum_dict[remaining] -= 1
15 else:
16 sum_dict[num] = 1 if num not in sum_dict else sum_dict[num] + 1
17
18 return result
19
20 collection1 = [4, 5, 2, 1, 1, 8]
21 collection2 = [7, 1, 8, 8]
22
23 solution = Solution()
24 print(solution.sum_target(collection1, collection2, 9)) | 2 - warning: redefined-outer-name
2 - warning: redefined-outer-name
4 - refactor: use-dict-literal
1 - refactor: too-few-public-methods
|
1 # 566
2
3 # time: O(N * M)
4 # space: O(N * M)
5 class Solution:
6 def reshape(self, nums, r, c):
7 if not nums or len(nums) * len(nums[0]) != r * c:
8 return nums
9
10 rows, cols = len(nums), len(nums[0])
11
12 queue = []
13 for row in range(rows):
14 for col in range(cols):
15 queue.append(nums[row][col])
16
17 res, count =[], 0
18
19 for row in range(r):
20 res.append([])
21 for col in range(c):
22 res[-1].append(queue[count])
23 count += 1
24
25 return res
26
27 # time: O(N * M)
28 # space: O(N * M)
29 class Solution2:
30 def reshape(self, nums, r, c):
31 if not nums or len(nums) * len(nums[0]) != r * c:
32 return nums
33
34 res = [[] * r]
35
36 rows = cols = 0
37
38 for i in range(len(nums)):
39 for j in range(len(nums[0])):
40 res[rows].append(nums[i][j])
41
42 cols += 1
43 if cols == c:
44 rows += 1
45 cols = 0
46
47 return res
48
49
50 nums = [[1,2], [3,4]]
51 solution = Solution2()
52 print(solution.reshape(nums, 1, 4)) | 6 - warning: redefined-outer-name
5 - refactor: too-few-public-methods
30 - warning: redefined-outer-name
29 - refactor: too-few-public-methods
|
1 class Solution:
2 # O(N) time and space
3 def get_maximum_depth(self, root):
4 if not root:
5 return 0
6
7 return 1 + max(self.get_maximum_depth(root.left), self.get_maximum_depth(root.right)) | 1 - refactor: too-few-public-methods
|
1 from utils.treeNode import TreeNode
2
3 class Solution:
4 # O(N) time and space
5 def get_minimum_depth(self, root):
6 if not root:
7 return 0
8
9 depth = 0
10 level_nodes = [root]
11
12 while level_nodes:
13 depth += 1
14 new_level_nodes = []
15 for node in level_nodes:
16 if not node.left and not node.right:
17 #leaf node. return depth
18 return depth
19
20 if node.left:
21 new_level_nodes.append(node.left)
22
23 if node.right:
24 new_level_nodes.append(node.right)
25
26 level_nodes = new_level_nodes
27
28 return depth
29
30 # O(N) time and space
31 def get_minimum_depth2(self, root):
32 if not root:
33 return 0
34
35 left_height, right_height = self.get_minimum_depth2(root.left), self.get_minimum_depth2(root.right)
36
37 if not left_height or not right_height:
38 return 1 + left_height + right_height
39
40 return 1 + min(left_height, right_height)
41
42 solution = Solution()
43 print(solution.get_minimum_depth(None))
44
| 1 - warning: unused-import
|
1 class Solution(object):
2 def multiply(self, num1, num2):
3 """
4 :type num1: str
5 :type num2: str
6 :rtype: str
7 """
8
9 result = [0] * (len(num1) + len(num2))
10 num1, num2 = num1[::-1], num2[::-1]
11 for i in range(len(num1)):
12 for j in range(len(num2)):
13 product = int(num1[i]) * int(num2[j])
14 units = product % 10
15 tens = product // 10
16
17 result[i + j] += units
18 if result[i + j] > 9:
19 tens += result[i + j] // 10
20 result[i + j] %= 10
21
22 result[i + j + 1] += tens
23 if result[i + j + 1] > 9:
24 result[i + j + 2] += result[i + j + 1] // 10
25 result[i + j + 1] %= 10
26
27 # remove the trailing zeros from result
28 while len(result) > 0 and result[-1] == 0:
29 result.pop()
30
31 return ''.join(map(str, result[::-1])) | 1 - refactor: useless-object-inheritance
1 - refactor: too-few-public-methods
|
1 class Solution:
2 def divide(self, dividend, divisor):
3 if divisor == 0:
4 raise ValueError('divisor should not be 0')
5
6 result, right = 0, abs(divisor)
7 while right <= abs(dividend):
8 result += 1
9 right += abs(divisor)
10
11 is_result_negative = (
12 (dividend > 0 and divisor < 0) or
13 (dividend < 0 and divisor > 0)
14 )
15
16 return int('-{}'.format(str(result))) if is_result_negative else result
17
18 def divide2(self, dividend, divisor):
19 if divisor == 0:
20 raise ValueError('divisor is 0')
21
22 is_result_negative = (
23 (dividend > 0 and divisor < 0) or
24 (dividend < 0 and divisor > 0)
25 )
26
27 dividend, divisor = abs(dividend), abs(divisor)
28
29 result = 1
30 right = divisor
31 while right <= dividend:
32 result += result
33 right += right
34
35 while right > dividend:
36 result -= 1
37 right -= divisor
38
39 return -result if is_result_negative else result
40
41 solution = Solution()
42 # print(solution.divide(-10, 2))
43 print(solution.divide2(-10, 3))
44
| 12 - refactor: chained-comparison
13 - refactor: chained-comparison
23 - refactor: chained-comparison
24 - refactor: chained-comparison
|
1 class Solution:
2 def get_maximum_product(self, nums):
3 max_so_far = float('-inf')
4 max_here, min_here = 1, 1
5 for num in nums:
6 max_here, min_here = max(max_here * num, min_here * num, num), min(min_here * num, max_here * num, num)
7 max_so_far = max(max_so_far, max_here)
8 return max_so_far
9
10 solution = Solution()
11 nums = [2, 3, -2, -4]
12 print(solution.get_maximum_product(nums))
| 2 - warning: redefined-outer-name
1 - refactor: too-few-public-methods
|
1 #662
2
3 from utils.treeNode import TreeNode
4
5 class Solution2:
6 def max_width(self, root):
7 queue = [(root, 0, 0)]
8 curr_level, left, result = 0, 0, 0
9
10 for node, pos, level in queue:
11 if node:
12 queue.append((node.left, 2 * pos, level + 1))
13 queue.append((node.right, (2 * pos) + 1, level + 1))
14
15 if curr_level != level:
16 curr_level = level
17 left = pos
18
19 result = max(result, pos - left + 1)
20
21 return result
22
23
24
25 class Solution:
26 def max_width(self, root):
27 if not root:
28 return 0
29
30 level = [(root, 0)]
31 left, right, result = float('inf'), 0, 1
32
33 while level:
34 new_level = []
35 for node, pos in level:
36 if node:
37 new_level.append((node.left, 2 * pos))
38 new_level.append((node.right, (2 * pos) + 1))
39
40 left = min(left, pos)
41 right = max(right, pos)
42
43 result = max(result, right - left + 1)
44 left, right = float('inf'), 0
45 level = new_level
46
47 return result
48
49 one = TreeNode(1)
50 two = TreeNode(1)
51 three = TreeNode(1)
52 four = TreeNode(1)
53 five = TreeNode(1)
54 six = TreeNode(1)
55 seven = TreeNode(1)
56
57 one.left = two
58 two.left = three
59 three.left = four
60 one.right = five
61 five.right = six
62 six.right = seven
63
64 print(one)
65
66 print('============')
67 solution = Solution2()
68 print(solution.max_width(one))
| 12 - warning: modified-iterating-list
13 - warning: modified-iterating-list
5 - refactor: too-few-public-methods
25 - refactor: too-few-public-methods
|
1 from collections import defaultdict
2 import unittest
3 class Solution:
4 def reconstruct_itinerary(self, flights):
5 graph = self.build_graph(flights)
6
7 path = []
8
9 self.dfs('JFK', graph, path, len(flights))
10
11 return path
12
13 def dfs(self, node, graph, path, remaining):
14 if node == 'X':
15 return
16
17 print('current node: {} - current path: {}'.format(node, path))
18 path.append(node)
19
20 if remaining == 0:
21 return True
22
23 for i, nbr in enumerate(graph[node]):
24 # remove nbr from the graph
25 graph[node][i] = 'X'
26 if self.dfs(nbr, graph, path, remaining - 1):
27 return True
28 graph[node][i] = nbr
29
30 path.pop()
31 return False
32
33 def build_graph(self, flights):
34 graph = defaultdict(list)
35
36 for source, dest in flights:
37 graph[source].append(dest)
38
39 for nbrs in graph.values():
40 nbrs.sort()
41
42 return graph
43
44 class Solution3:
45 def reconstruct_itinerary(self, flights):
46 graph = self.build_graph(flights)
47 path = []
48
49 def dfs(airport):
50 path.append(airport)
51 while graph[airport]:
52 nbr = graph[airport].pop()
53 dfs(nbr)
54
55 dfs('JFK')
56 return path
57
58 def build_graph(self, flights):
59 graph = defaultdict(list)
60 for start, end in flights:
61 graph[start].append(end)
62
63
64 for node in graph:
65 graph[node].sort(reverse=True)
66
67 return graph
68
69 class Test(unittest.TestCase):
70 test_data = [[["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]], [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]]
71 expected_results = [["JFK", "MUC", "LHR", "SFO", "SJC"], ["JFK","ATL","JFK","SFO","ATL","SFO"]]
72
73 def test_reconstruct_itinerary(self):
74 solution = Solution3()
75 for i, data in enumerate(self.test_data):
76 self.assertEqual(solution.reconstruct_itinerary(data), self.expected_results[i])
77
78 if __name__ == '__main__':
79 unittest.main()
| 13 - refactor: inconsistent-return-statements
|
1 # 508
2
3 from utils.treeNode import TreeNode
4 from collections import defaultdict
5
6 # time: O(N)
7 # space: O(N)
8 class Solution:
9 def most_frequent_substree_sum(self, root):
10 sum_mapping = defaultdict(int)
11
12 def helper(node):
13 if not node:
14 return 0
15
16 substree_sum = node.value + helper(node.left) + helper(node.right)
17 sum_mapping[substree_sum] += 1
18
19 return substree_sum
20
21 helper(root)
22
23 max_frequency = max(sum_mapping.values())
24 return [substree_sum for substree_sum in sum_mapping if sum_mapping[substree_sum] == max_frequency]
25
26 one = TreeNode(6)
27 two = TreeNode(2)
28 three = TreeNode(-5)
29
30 one.left = two
31 one.right = three
32
33 print(one)
34 print('===========')
35
36 solution = Solution()
37 print(solution.most_frequent_substree_sum(one))
38
39
40
41
| 8 - refactor: too-few-public-methods
|
1 class Solution(object):
2 # this algorithm is called the Boyer-Moore majority voting algorithm
3 # https://stackoverflow.com/questions/4325200/find-the-majority-element-in-array
4
5 # the majority element appears more than all the other elements combined. Therefore, if we keep a
6 # counter and change the major every time the counter is 0, eventually, major will be the major element
7 def majority_element(self, numbers):
8 counter, major = 0, None
9
10 for num in numbers:
11 if counter == 0:
12 counter = 1
13 major = num
14 elif num == major:
15 counter += 1
16 else:
17 counter -= 1
18 # major is guaranteed to be the major element if it exists.
19 # otherwise, iterate over the array, and count the occurrences of major
20 #return major
21 counter = 0
22 for num in numbers:
23 if num == major:
24 counter += 1
25 if counter > len(numbers) / 2:
26 return major
27
28 return None
29
30 numbers = [2, 3, 5, 3, 5, 6, 5, 5, 5]
31 solution = Solution()
32 print(solution.majority_element(numbers)) | 1 - refactor: useless-object-inheritance
7 - warning: redefined-outer-name
1 - refactor: too-few-public-methods
|
1 class TreeNode:
2 def __init__(self, value = None, left = None, right = None):
3 self.value = value
4 self.left = left
5 self.right = right
6
7 def __repr__(self):
8 return self.trace(padding="")
9
10 def trace(self, padding=""):
11 string_representation = ''
12 if self.right:
13 string_representation += self.right.trace(padding + " ") + "\n"
14
15 string_representation += padding + str(self.value) + "\n"
16
17 if self.left:
18 string_representation += self.left.trace(padding + " ")
19
20 return string_representation
| Clean Code: No Issues Detected
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.