Skip to content

Commit

Permalink
Refactored solutions 262 - 270
Browse files Browse the repository at this point in the history
  • Loading branch information
WHAHA-HA committed Jan 31, 2021
1 parent bef24ca commit 596455e
Show file tree
Hide file tree
Showing 8 changed files with 38 additions and 41 deletions.
8 changes: 8 additions & 0 deletions Solutions/262.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,3 +81,11 @@ def get_bridges(graph: GraphUndirectedUnweighted) -> List[Tuple[int, int]]:
g3.add_edge(4, 5)
print("\nBridges in third graph:")
print(*get_bridges(g3))


"""
SPECS:
TIME COMPLEXITY: O(v + e)
SPACE COMPLEXITY: O(v)
"""
22 changes: 10 additions & 12 deletions Solutions/263.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,29 @@
Problem:
Create a basic sentence checker that takes in a stream of characters and determines
whether they form valid sentences. If a sentence is valid, the program should print
it out.
whether they form valid sentences. If a sentence is valid, the program should print it
out.
We can consider a sentence valid if it conforms to the following rules:
* The sentence must start with a capital letter, followed by a lowercase letter or a
space.
* All other characters must be lowercase letters, separators (,,;,:) or terminal marks
(.,?,!,‽).
* There must be a single space between each word.
* The sentence must end with a terminal mark immediately following a word.
The sentence must start with a capital letter, followed by a lowercase letter or a
space.
All other characters must be lowercase letters, separators (,,;,:) or terminal marks
(.,?,!,‽).
There must be a single space between each word.
The sentence must end with a terminal mark immediately following a word.
"""

# Terminals and separators as specified by the problem
TERMINALS = [".", "?", "!", "‽"]
SEPARATORS = [",", ";", ":"]


def check_sentence(sentence: str) -> None:
# checking the first rule
if len(sentence) < 2 or not sentence[0].isupper():
return
if not sentence[1].islower() and not sentence[1].isspace():
return
# checking for the other rules

space_flag = False
for char in sentence[1:-1]:
if char.isspace():
Expand All @@ -37,7 +35,7 @@ def check_sentence(sentence: str) -> None:
space_flag = False
if not char.islower() and char not in SEPARATORS:
return
# printing the sentence if none of the rules is violated

if sentence[-1] in TERMINALS:
print(sentence)

Expand Down
13 changes: 4 additions & 9 deletions Solutions/264.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@
from typing import List, Set


def combinations(characters: Set[str], size: int, accumulator: List[str]) -> None:
# function to generate all combination of length k with the given characters
def generate_all_combinations(
characters: Set[str], size: int, accumulator: List[str]
) -> None:
if not accumulator:
accumulator.extend(characters)
size -= 1
Expand All @@ -32,13 +33,9 @@ def combinations(characters: Set[str], size: int, accumulator: List[str]) -> Non
def get_de_bruijn_helper(
characters: Set[str], combinations_set: Set[str], k: int, context: str = ""
) -> Set[str]:
# helper function to genenrate all the De Bruijn sequences for the given
# combinations
# base case for recursion
if not combinations_set:
return set([context])

# generating the sequences
dseqs = set()
if not context:
# if context is empty, it is initized using a combination
Expand All @@ -60,10 +57,8 @@ def get_de_bruijn_helper(


def get_de_bruijn(characters: Set[str], k: int) -> Set[str]:
# generating the combinations and calling the helper function for computing the
# sequences
combinations_list = []
combinations(characters, k, combinations_list)
generate_all_combinations(characters, k, combinations_list)
combinations_set = set(combinations_list)
return get_de_bruijn_helper(characters, combinations_set, k)

Expand Down
3 changes: 1 addition & 2 deletions Solutions/265.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def get_bonus(arr: List[int]) -> List[int]:
return []
if length == 1:
return [1]
# generating a array with elements compared to the previous elements

comparison = [None for _ in range(length)]
for i in range(1, length):
if arr[i] > arr[i - 1]:
Expand All @@ -31,7 +31,6 @@ def get_bonus(arr: List[int]) -> List[int]:
else:
comparison[i] = "="

# generating the results
i = 0
comparison[0] = comparison[1]
result = [0 for _ in range(length)]
Expand Down
1 change: 0 additions & 1 deletion Solutions/267.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@


def is_attacking(board: List[List[str]]) -> bool:
# iterating over the board
for i in range(8):
for j in range(8):
# case pawn
Expand Down
3 changes: 2 additions & 1 deletion Solutions/268.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
than O(log N) time.
"""

# for details visit: https://stackoverflow.com/a/19611541/8650340


def is_power_of_4(num: int) -> bool:
# https://stackoverflow.com/a/19611541/8650340
return ((num & -num) & 0x55555554) == num


Expand Down
4 changes: 0 additions & 4 deletions Solutions/269.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@


def get_config_helper(dominos: List[str], length: int) -> List[str]:
# creating and updating the new copy of dominos
has_been_updated = False
updated_dominos = dominos.copy()
for i in range(length):
Expand All @@ -40,15 +39,12 @@ def get_config_helper(dominos: List[str], length: int) -> List[str]:
):
updated_dominos[i + 1] = "R"
has_been_updated = True
# if updation has been performed in the current iteration, the function is called
# recursively
if has_been_updated:
return get_config_helper(updated_dominos, length)
return dominos


def get_config(initial_state: str) -> str:
# breaking dominos into list as string is immutable
dominoes = list(initial_state)
return "".join(get_config_helper(dominoes, len(dominoes)))

Expand Down
25 changes: 13 additions & 12 deletions Solutions/270.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,26 +25,20 @@
"""

from sys import maxsize
from typing import Dict, Optional, Tuple
from typing import Dict, List, Optional, Tuple

# Local Import from the DataStructure module
from DataStructures.Graph import GraphDirectedWeighted
from DataStructures.PriorityQueue import MinPriorityQueue


def dijkstras_algo(
def dijkstra(
graph: GraphDirectedWeighted, start: int
) -> Tuple[Dict[int, int], Dict[int, Optional[int]]]:
"""
Dijkstras Single Source Shortest Path Algorithm
"""
# intialization
dist = {node: maxsize for node in graph.connections}
parent = {node: None for node in graph.connections}
dist[start] = 0
priority_queue = MinPriorityQueue()
[priority_queue.push(node, weight) for node, weight in dist.items()]
# distance updation
while not priority_queue.isEmpty():
node = priority_queue.extract_min()
for neighbour in graph.connections[node]:
Expand All @@ -55,13 +49,12 @@ def dijkstras_algo(
return dist, parent


def get_propagation_time(edges):
# graph generation from edges
def get_propagation_time(edges: List[Tuple[int, int, int]]) -> int:
graph = GraphDirectedWeighted()
for src, dest, wt in edges:
graph.add_edge(src, dest, wt)
# returning the greatest distance
time, _ = dijkstras_algo(graph, 0)

time, _ = dijkstra(graph, 0)
return max(time.values())


Expand All @@ -76,3 +69,11 @@ def get_propagation_time(edges):
(3, 4, 5),
]
print(get_propagation_time(edges))


"""
SPECS:
TIME COMPLEXITY: O(v + e x log(v))
SPACE COMPLEXITY: O(v)
"""

0 comments on commit 596455e

Please sign in to comment.