Skip to content

Commit

Permalink
Refactored solutions 272 - 284
Browse files Browse the repository at this point in the history
  • Loading branch information
WHAHA-HA committed Feb 1, 2021
1 parent 596455e commit 942cbe4
Show file tree
Hide file tree
Showing 12 changed files with 30 additions and 48 deletions.
1 change: 0 additions & 1 deletion Solutions/272.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@


def throw_dice(N: int, faces: int, total: int, accumulator: int = 0) -> int:
# base case for recursion
if N == 0 and total == 0:
return accumulator + 1
elif total < 0:
Expand Down
2 changes: 1 addition & 1 deletion Solutions/273.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def get_fixed_point(arr: List[int]) -> Union[int, False]:
# fixed point found
return value
elif value > index:
# since the array is sorted and has distinct elements once the value
# since the array is sorted and has distinct elements, once the value
# exceeds the index, the index can never be equal to the value at any
# position
break
Expand Down
13 changes: 6 additions & 7 deletions Solutions/274.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"""


def evaluate(expression: str) -> int:
def evaluate_expression(expression: str) -> int:
result = 0
add = True
sub_eval_string = ""
Expand All @@ -23,11 +23,10 @@ def evaluate(expression: str) -> int:
elif char == ")":
number_of_parentheses -= 1
if number_of_parentheses == 0:
# evaluating part within parentheses recursively
if add:
result += evaluate(sub_eval_string)
result += evaluate_expression(sub_eval_string)
else:
result -= evaluate(sub_eval_string)
result -= evaluate_expression(sub_eval_string)
sub_eval_string = ""
else:
sub_eval_string += char
Expand All @@ -47,9 +46,9 @@ def evaluate(expression: str) -> int:


if __name__ == "__main__":
print(evaluate("-1 + (2 + 3)"))
print(evaluate("-1 + (2 + 3) + (2 - 3)"))
print(evaluate("-1 + (2 + 3) + ((2 - 3) + 1)"))
print(evaluate_expression("-1 + (2 + 3)"))
print(evaluate_expression("-1 + (2 + 3) + (2 - 3)"))
print(evaluate_expression("-1 + (2 + 3) + ((2 - 3) + 1)"))


"""
Expand Down
2 changes: 1 addition & 1 deletion Solutions/275.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def generate_look_and_say_term(num: str) -> str:
return result


# cache is unnecessary for such a small size, but in case of large value of n, it
# cache is unnecessary for small sizes, but in case of large value of n, it drastically
# speeds up the process using memorization
@lru_cache(maxsize=5)
def get_look_and_say_term(n: int) -> str:
Expand Down
2 changes: 0 additions & 2 deletions Solutions/276.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@

def kmp_search(text: str, pattern: str) -> Union[int, bool]:
# modified kmp search to return the first match only
# result is 0 based index
len_pattern = len(pattern)
len_text = len(text)
lps = compute_lps(pattern, len_pattern)
Expand All @@ -27,7 +26,6 @@ def kmp_search(text: str, pattern: str) -> Union[int, bool]:
i += 1
j += 1
if j == len_pattern:
# match
return i - j
elif i < len_text and pattern[j] != text[i]:
if j != 0:
Expand Down
17 changes: 7 additions & 10 deletions Solutions/278.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,24 @@
from functools import lru_cache
from typing import List

from DataStructures.Stack import Stack
from DataStructures.Tree import BinaryTree, Node


# memorized fibonacci function
@lru_cache(maxsize=128)
def fib(n: int) -> int:
# memorized fibonacci function
if n in (1, 2):
return 1
return fib(n - 1) + fib(n - 2)


# Tree generator functions
def generate_tree_helper(i: int, arr: List[BinaryTree], nodes: int) -> BinaryTree:
tree = arr[i]
stack = [tree.root]
stack = Stack()
stack.push(tree.root)

while stack:
while not stack.is_empty():
# generating the new tree with 1 new node
node = stack.pop()
if not node.left:
Expand All @@ -36,7 +37,7 @@ def generate_tree_helper(i: int, arr: List[BinaryTree], nodes: int) -> BinaryTre
else:
return tree
else:
stack.append(node.left)
stack.push(node.left)
if not node.right:
node.right = Node(0)
for j in range(nodes):
Expand All @@ -46,20 +47,17 @@ def generate_tree_helper(i: int, arr: List[BinaryTree], nodes: int) -> BinaryTre
else:
return tree
else:
stack.append(node.right)
stack.push(node.right)


def generate_tree(tree: BinaryTree) -> List[BinaryTree]:
# generating a list of trees to update with a new node and calling the helper
# function
nodes = sum([fib(i) for i in range(1, len(tree) + 2)])
arr = [deepcopy(tree) for _ in range(nodes)]
for i in range(nodes):
arr[i] = generate_tree_helper(i, arr, nodes)
return arr


# Tree generation initialization
def create_trees_helper(tree_arr: List[BinaryTree], n: int) -> None:
if n == 0:
return
Expand All @@ -74,7 +72,6 @@ def create_trees_helper(tree_arr: List[BinaryTree], n: int) -> None:


def create_trees(n: int) -> List[BinaryTree]:
# function to create all binary trees containing n nodes
tree_arr = []
if n == 0:
return tree_arr
Expand Down
14 changes: 5 additions & 9 deletions Solutions/279.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,32 +28,28 @@
from DataStructures.Graph import GraphUndirectedUnweighted


# graph functions
def dfs_components_helper(
def get_components_dfs_helper(
graph: GraphUndirectedUnweighted, node: int, component: Set[int], visited: Set[int]
) -> None:
# function to get all nodes in a component using dfs
visited.add(node)
component.add(node)
for neighbour in graph.connections[node]:
if neighbour not in visited:
dfs_components_helper(graph, neighbour, component, visited)
get_components_dfs_helper(graph, neighbour, component, visited)


def get_components(graph: GraphUndirectedUnweighted) -> List[Set[int]]:
# function to generate the components
components = []
visited = set()
for node in graph.connections:
if node not in visited:
component = set()
dfs_components_helper(graph, node, component, visited)
get_components_dfs_helper(graph, node, component, visited)
components.append(component)
return components


# function to generate the transitive closure
def friendship_transitive_closure(
def get_friendship_transitive_closure(
friendship_list: Dict[int, List[int]],
) -> List[Set[int]]:
graph = GraphUndirectedUnweighted()
Expand All @@ -66,7 +62,7 @@ def friendship_transitive_closure(

if __name__ == "__main__":
print(
friendship_transitive_closure(
get_friendship_transitive_closure(
{0: [1, 2], 1: [0, 5], 2: [0], 3: [6], 4: [], 5: [1], 6: [3]}
)
)
Expand Down
7 changes: 3 additions & 4 deletions Solutions/280.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from DataStructures.Graph import GraphUndirectedUnweighted


def dfs_components_helper(
def get_components_helper(
graph: GraphUndirectedUnweighted,
node: int,
component: Set[int],
Expand All @@ -23,7 +23,7 @@ def dfs_components_helper(
for neighbour in graph.connections[node]:
degree += 1
if neighbour not in visited:
degree += dfs_components_helper(graph, neighbour, component, visited)
degree += get_components_helper(graph, neighbour, component, visited)
return degree


Expand All @@ -32,8 +32,7 @@ def is_cyclic(graph: GraphUndirectedUnweighted) -> bool:
for node in graph.connections:
if node not in visited:
component = set()
component_degree = dfs_components_helper(graph, node, component, visited)
# condition for a acyclic graph (tree)
component_degree = get_components_helper(graph, node, component, visited)
if component_degree > 2 * (len(component) - 1):
return False
return True
Expand Down
1 change: 0 additions & 1 deletion Solutions/281.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@

def get_min_cut_position(wall: List[List[int]]) -> int:
rows = len(wall)
# base case 1 row in the wall
if rows == 1:
cols = len(wall[0])
if cols > 1:
Expand Down
2 changes: 1 addition & 1 deletion Solutions/282.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def get_pythogorean_triplet(
# generating the set of squared values for O(1) access
squared_arr = [elem * elem for elem in arr]
value_set = set(squared_arr)
# checking for Pythagorian triplet

for i in range(length - 1):
for j in range(i + 1, length):
if squared_arr[i] + squared_arr[j] in value_set:
Expand Down
5 changes: 2 additions & 3 deletions Solutions/283.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@


def get_prime_factors(num: int) -> Set[int]:
# function to generate the prime factors of the input number
factors = set()
curr = 2
while num > 1:
Expand All @@ -34,12 +33,12 @@ def get_regular_numbers(N: int) -> List[int]:
result = []
count = 0
factors = set([2, 3, 5])
# finding the required numbers

for factor in factors:
for i in range(factor, total_range, factor):
if not SoE[i] and not (get_prime_factors(i) - factors):
SoE[i] = True
# generating results

for index, value in enumerate(SoE):
if value:
result.append(index)
Expand Down
12 changes: 4 additions & 8 deletions Solutions/284.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,19 @@
from DataStructures.Tree import BinaryTree, Node


# Node functions
def dfs_get_depth_helper(
def get_depth_dfs_helper(
node: Node, search_node_val: int, depth: int, parent_val: Optional[int] = None
) -> Optional[int]:
# function to get the depth and parent of the target node
if node.val == search_node_val:
return depth, parent_val
if node.left:
left_depth, parent = dfs_get_depth_helper(
left_depth, parent = get_depth_dfs_helper(
node.left, search_node_val, depth + 1, node
)
if left_depth:
return left_depth, parent
if node.right:
right_depth, parent = dfs_get_depth_helper(
right_depth, parent = get_depth_dfs_helper(
node.right, search_node_val, depth + 1, node
)
if right_depth:
Expand Down Expand Up @@ -80,13 +78,11 @@ def get_node_by_depth(
)


# Tree functions
def dfs_get_depth(tree: BinaryTree, search_node_val: int):
return dfs_get_depth_helper(tree.root, search_node_val, 0)
return get_depth_dfs_helper(tree.root, search_node_val, 0)


def get_cousins(tree: BinaryTree, node_val: int) -> List[int]:
# function to generate all the cousins of a node
depth, parent = dfs_get_depth(tree, node_val)
if depth is None:
raise ValueError("Node not present in Tree")
Expand Down

0 comments on commit 942cbe4

Please sign in to comment.