def get_path(graph, from_s, from_t): """Traces the searchers to create and return a list of indices representing the shortest path from s to t. Assumes that the search is already complete and that a path has been found. Args: graph: A Graph instance. from_s, from_t: Searcher instances. Returns: A list of integers. """ path = [] # We first construct the path from s to the connection point. Using # a stack ensures that the order is correct. start_stack = Stack() while from_s.backtracer is not None: start_stack.push(from_s.backtracer) from_s.backtracer = graph[from_s.backtracer].backpointer while not start_stack.is_empty(): path.append(start_stack.pop()) # Then we extend the path from the connection point to t. while from_t.backtracer is not None: path.append(from_t.backtracer) from_t.backtracer = graph[from_t.backtracer].backpointer return path
class SetOfStacks: max_items = 3 def __init__(self): self.piles = Stack() self._create_new_stack() def _create_new_stack(self): self.piles.push(Stack()) def push(self, item): if self.piles.peek().size() == self.max_items: self._create_new_stack() self.push(item) else: self.piles.peek().push(item) def pop(self): return self.piles.peek().pop() def pop_stack(self): return Stack.pop(self.piles) def is_empty(self): return self.piles.is_empty() def _backfill(self, new, old): while new.size() > 0: old.push(new.pop()) def pop_at(self, index): if index > self.piles.size()-1: raise "Invalid index." temp_stack = Stack() for i in range(index, 0, -1): temp_stack.push(SetOfStacks.pop_stack(self)) item = self.piles.pop() self._backfill(temp_stack.reverse(), self.piles) return item.pop() def __str__(self): if not self.is_empty(): return Stack.__str__(self.piles) return "Stack is empty."
def f1(n): """Prints an English phrase that describes an input integer. Args: n: Any int with absolute value less than one nonillion (10^30). Raises: ValueError: n has absolute value greater than 10^30. """ if n == 0: print("Zero") return neg = True if n < 0 else False n = abs(n) output_stack = Stack() three_stack = Stack() group = -1 # Divide n into "groups" of three digits: the pre-thousands, then # thousands, then millions, billions, and so on. For each group, # generate a string such as "Two Hundred Twelve" and push onto a # stack s.t. groups with greater significance will be output first. while n > 0: for i in range(3): three_stack.push(n % 10) n //= 10 hundreds = three_stack.pop() tens = three_stack.pop() ones = three_stack.pop() output_stack.push(three_digit_string(hundreds, tens, ones)) group += 1 print_output(output_stack, neg, group)
def pop_stack(self): return Stack.pop(self.piles)