Skip to content

Commit

Permalink
Refactored solutions 321 - 334
Browse files Browse the repository at this point in the history
  • Loading branch information
WHAHA-HA committed Feb 2, 2021
1 parent 6f0eae5 commit 1236508
Show file tree
Hide file tree
Showing 12 changed files with 39 additions and 48 deletions.
17 changes: 9 additions & 8 deletions Solutions/321.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@
"""


def get_closest_factors(num):
from typing import Tuple


def get_closest_factors(num: int) -> Tuple[int, int]:
a, b = 1, num
factor_1, factor_2 = 1, 1
while b > a:
Expand All @@ -23,20 +26,18 @@ def get_closest_factors(num):
return (factor_1, factor_2)


def get_step_size(num, steps=0):
def get_step_size(num: int, steps: int = 0) -> int:
if num < 1:
raise ValueError(f"Cannot reach 1 from {num}")
# base case
if num == 1:
return steps
# generating the sequence to get the least number of steps
largest_factor = max(get_closest_factors(num))
if largest_factor == num:
return get_step_size(num - 1, steps + 1)
else:
return min(
get_step_size(num - 1, steps + 1), get_step_size(largest_factor, steps + 1)
)
return min(
get_step_size(num - 1, steps + 1), get_step_size(largest_factor, steps + 1)
)


if __name__ == "__main__":
Expand All @@ -48,5 +49,5 @@ def get_step_size(num, steps=0):
SPECS:
TIME COMPLEXITY: O(n x log(n))
Sfactor_1CE COMPLEXITY: O(n) [considering call-stack]
SPACE COMPLEXITY: O(n) [considering call-stack]
"""
14 changes: 6 additions & 8 deletions Solutions/322.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,16 @@
"""


def get_sum(x):
# Utitlity function to calculate sum of numbers from 1 to x
return (x * (x + 1)) // 2
def get_sum_till_n(n: int) -> int:
return (n * (n + 1)) // 2


def count_jumps(n):
# getting the absolute value, answer will be same either it is positive or negative
def count_jumps(n: int) -> int:
# answer will be same either it is positive or negative
n = abs(n)
ans = 0
# Continue till number is lesser or not in same parity
while get_sum(ans) < n or (get_sum(ans) - n) & 1:
# continue till number is lesser or not in same parity
while get_sum_till_n(ans) < n or (get_sum_till_n(ans) - n) & 1:
ans += 1
return ans

Expand All @@ -43,4 +42,3 @@ def count_jumps(n):
TIME COMPLEXITY: O(n)
SPACE COMPLEXITY: O(1)
"""

3 changes: 1 addition & 2 deletions Solutions/324.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,10 @@


def get_max_mouse_dist(mouse_position: List[int], hole_position: List[int]) -> int:
# sorting the mice and holes to match them up
mouse_position.sort()
hole_position.sort()
max_distance = 0
# calculating the max distance

for mouse, hole in zip(mouse_position, hole_position):
max_distance = max(max_distance, abs(mouse - hole))
return max_distance
Expand Down
6 changes: 3 additions & 3 deletions Solutions/325.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def __init__(self) -> None:
def add_unit(
self, new_unit: str, available_unit: str, value: Union[int, float]
) -> None:
# function to add a new unit with respect to an unit already present
# add a new unit with respect to an unit already present
if available_unit not in self.metrics:
raise ValueError(f"Unit not found: {available_unit}")
self.metrics[new_unit] = self.metrics[available_unit] * value
Expand All @@ -38,8 +38,8 @@ def convert(
value: Union[int, float],
precision: int = 4,
) -> float:
# function to convert one metric to another, rounds off the result to required
# decimal places
# convert one metric to another, rounds off the result to required decimal
# places
if source_unit not in self.metrics:
raise ValueError(f"Unit not found: {source_unit}")
if result_unit not in self.metrics:
Expand Down
11 changes: 5 additions & 6 deletions Solutions/326.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,28 +22,27 @@
from DataStructures.Tree import Node, BinaryTree


def generategenerate_cartesian_tree_helper(
def generate_cartesian_tree_helper(
arr: List[int], last: Optional[Node] = None, root: Optional[Node] = None
) -> Node:
if not arr:
return root

# Cartesian tree generation
node = Node(arr[0])
if not last:
# root of the tree
return generategenerate_cartesian_tree_helper(arr[1:], node, node)
return generate_cartesian_tree_helper(arr[1:], node, node)
if last.val > node.val:
# property of Cartesian tree
node.left = last
return generategenerate_cartesian_tree_helper(arr[1:], node, node)
return generate_cartesian_tree_helper(arr[1:], node, node)
last.right = node
return generategenerate_cartesian_tree_helper(arr[1:], last, last)
return generate_cartesian_tree_helper(arr[1:], last, last)


def generate_cartesian_tree(sequence: List[int]) -> BinaryTree:
tree = BinaryTree()
tree.root = generategenerate_cartesian_tree_helper(sequence)
tree.root = generate_cartesian_tree_helper(sequence)
return tree


Expand Down
5 changes: 2 additions & 3 deletions Solutions/327.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,20 +59,19 @@ def merge_trees(tree1: BinaryTree, tree2: BinaryTree) -> BinaryTree:


if __name__ == "__main__":
# tree1 creation
tree1 = BinaryTree()
tree1.root = Node(1)
tree1.root.left = Node(2)
tree1.root.right = Node(3)
tree1.root.left.right = Node(4)
print(tree1)
# tree2 creation

tree2 = BinaryTree()
tree2.root = Node(2)
tree2.root.right = Node(-3)
tree2.root.right.right = Node(10)
print(tree2)
# merged tree generation

print(merge_trees(tree1, tree2))


Expand Down
2 changes: 0 additions & 2 deletions Solutions/328.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,10 @@
Implement this system.
"""

from sys import maxsize
from typing import Optional


class EloRating:
# class variables
INITIAL_POINTS = 1400
MEAN_SCORE_CHANGE = 30

Expand Down
4 changes: 2 additions & 2 deletions Solutions/329.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def stable_marriage(
woman_partners = {woman: None for woman in gal_preferences}
man_free = {man: True for man in guy_preferences}
free_count = len(guy_preferences)
# forming partners

while free_count > 0:
# random single man selection
curr = None
Expand All @@ -55,7 +55,7 @@ def stable_marriage(
for woman in guy_preferences[curr]:
if not man_free[curr]:
break
# engaged the current man if a single woman is encountered
# engaging the current man if a single woman is encountered
if not woman_partners[woman]:
woman_partners[woman] = curr
man_free[curr] = False
Expand Down
2 changes: 1 addition & 1 deletion Solutions/330.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@


def generate_combinations(num: int) -> List[List[bool]]:
# function to generate all boolean combinations for num variables
# generate all boolean combinations for the given number of variables
numbers = [num for num in range(pow(2, num))]
combinations = []
for number in numbers:
Expand Down
2 changes: 1 addition & 1 deletion Solutions/332.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def get_count(M: int, N: int) -> int:
count = 0
for i in range(1, M):
# (a, b) and (b, a) are considered different entities.
# To consider them once, use range(1, M // 2)
# To consider them only once, use range(1, M // 2)
if i ^ (M - i) == N:
count += 1
return count
Expand Down
19 changes: 9 additions & 10 deletions Solutions/333.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,8 @@ def knows(self, a: str, b: str) -> bool:
return b in self.people[a]

def get_celebrity(self) -> str:
# function to get the celebrity of the party
# [runs in O(v + e) time & space (e = the maximum people a person knows,
# v = number of people)]
# runs in O(v + e) time & space (e = the maximum people a person knows,
# v = number of people)
celebrity_candidates = {}
for person in self.people:
if celebrity_candidates == {}:
Expand All @@ -34,12 +33,12 @@ def get_celebrity(self) -> str:
for person2 in self.people[person]:
if not self.knows(person2, person):
celebrity_candidates[person2] = 1
else:
# checking for the person known by most people in case there is other
# popular people
for potential_celebrity in celebrity_candidates:
if potential_celebrity in self.people[person]:
celebrity_candidates[potential_celebrity] += 1
continue
# checking for the person known by most people in case there is other
# popular people
for potential_celebrity in celebrity_candidates:
if potential_celebrity in self.people[person]:
celebrity_candidates[potential_celebrity] += 1
return max(
celebrity_candidates.keys(),
key=lambda candidate: celebrity_candidates[candidate],
Expand All @@ -48,7 +47,7 @@ def get_celebrity(self) -> str:

if __name__ == "__main__":
people = {
"a": {"b"}, # popular person
"a": {"b"}, # popular person (but not the celebrity)
"b": set(), # celebrity
"c": {"a", "b", "d"},
"d": {"a", "b"},
Expand Down
2 changes: 0 additions & 2 deletions Solutions/334.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,10 @@

from typing import List

# set of supported operations
OPERATORS = set(["+", "-", "*", "/"])


def game_24(arr: List[int]) -> bool:
# base case
if len(arr) == 1:
return arr[0] == 24
# checking if 24 can be reached
Expand Down

0 comments on commit 1236508

Please sign in to comment.