def evaluate(expression): # trivial cases if not expression: return 0 operands = { '+': (lambda x, y: x + y), '-': (lambda x, y: x - y), '*': (lambda x, y: x * y), '/': (lambda x, y: x // y) } stack = Stack() # convert the incoming string to an array exp = expression.split(',') # iterate through each exp for e in exp: if e in operands: # if operand, pop two numbers and calculate a b . p1 = stack.pop() p2 = stack.pop() res = operands[e](p2, p1) stack.push(res) else: # else push the number onto stack val = int(e) stack.push(val) final_res = stack.pop() return final_res
class TestStack(unittest.TestCase): def setUp(self): self.stack = Stack() def tearDown(self): del self.stack def test_push(self): self.stack.push('A') value = self.stack.get(0) self.assertEqual(value, 'A') def test_pop(self): self.stack.push('A') self.stack.push('B') value = self.stack.pop() self.assertEqual(value, 'B')
def shortest_equivalent_path(path): stack = Stack() # append '/' onto the stack stack.push('/') # split the path on the basis of '/' path_names = path.split('/') for name in path_names: if (len(name) != 0 and name != '.'): # ignore '.' and '' if (name == '..'): # pop from the stack if (stack.top() == '/' or stack.top() == '..'): # if there's no dir push .. onto the stack stack.push(name) else: dir_ = stack.pop() else: stack.push(name) new_path = '' val = stack.pop() while (val != '/'): new_path = val + '/' + new_path val = stack.pop() # if initial path starts with '/' then push that onto the new_path if (path[0] == '/'): return val + new_path[:-1] return new_path[:-1]
class Processor(object): def __init__(self): '''Creates the lists''' self.callahead = DoublyLinkedList() self.waiting = DoublyLinkedList() # self.waiting.debug_print() # self.waiting.add('a') # self.waiting.add('b') # self.waiting.add('c') # self.waiting.debug_print() self.appetizers = Queue() self.buzzers = Stack() self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.songs = CircularLinkedList() self.songs.add('Song 1') self.songs.add('Song 2') self.songs.add('Song 3') self.songs_iter = CircularLinkedListIterator(self.songs) def run(self, f): '''Processes the given file stream.''' for index, line in enumerate(f): line = line.rstrip() print('{}:{}'.format(index, line)) parts = line.split(',') # try: func = getattr(self, '{}'.format(parts[0].lower())) func(*parts[1:]) # except Exception as e: # print('Error: {}'.format(e)) # split and handle the commands here def debug(self, *args): self.callahead.debug_print() self.waiting.debug_print() self.appetizers.debug_print() self.buzzers.debug_print() self.songs.debug_print() def song(self, *args): print(self.songs_iter.next()) def appetizer(self, *args): try: print("{} >>> {}".format( self.appetizers.dequeue(), ', '.join([str(item) for item in self.waiting.getLastThree()]))) except Exception as e: print('Error:', e) def appetizer_ready(self, *args): self.appetizers.enqueue(args[0]) def seat(self, *args): self.buzzers.push('Buzzer') print(self.waiting.get(0)) self.waiting.delete(0) def call(self, *args): self.callahead.add(args[0]) def arrive(self, *args): if (self.callahead.deleteByValue(args[0]) == True): self.waiting.insert(self.getFiveIn(self.waiting.size), args[0]) else: sws = self.waiting.size self.waiting.insert(sws if sws >= 0 else 0, args[0]) self.buzzers.pop() def leave(self, *args): self.waiting.deleteByValue(args[0]) self.buzzers.push('Buzzer') def getFiveIn(self, size): return size - 4 if size - 4 >= 0 else 0
class Processor(object): def __init__(self): '''Creates the lists''' self.callahead = DoublyLinkedList() self.waiting = DoublyLinkedList() self.appetizers = Queue() self.buzzers = Stack() self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.songs = CircularLinkedList() self.songs.add('Song 1') self.songs.add('Song 2') self.songs.add('Song 3') self.songs_iter = CircularLinkedListIterator(self.songs) def run(self, f): '''Processes the given file stream.''' for line_i, line in enumerate(f): line = line.rstrip() # split and handle the commands here print('{}:{}'.format(line_i, line)) parts = line.split(',') try: func = getattr(self, 'cmd_{}'.format(parts[0].lower())) func(*parts[1:]) except Exception as e: print('Error: {}'.format(e)) def cmd_appetizer(self, *args): wait = [] r = self.waiting._get_node(self.waiting.size - 1) i = 0 try: if self.waiting.size > 3: i = self.waiting.size - 3 for x in range(self.waiting.size, i,-1): wait.append(str(r.value)) r = r.prev print('{} >>> {}'.format(self.appetizers.dequeue(), ', '.join(wait))) except: raise IndexError('The given index is not within the bounds of the current list.') def cmd_appetizer_ready(self, *args): self.appetizers.enqueue(args[0]) def cmd_call(self, *args): self.callahead.add(args[0]) def cmd_arrive(self, *args): if (self.callahead.check_value(args[0])): if self.waiting.size > 5: self.waiting.insert(self.waiting.size - 4, args[0]) index = self.callahead.check_index(args[0]) self.callahead.delete(index) else: self.waiting.insert(0, args[0]) index = self.callahead.check_index(args[0]) self.callahead.delete(index) else: self.waiting.add(args[0]) self.buzzers.pop() def cmd_leave(self, *args): self.buzzers.push('Buzzer') index = self.waiting.check_index(args[0]) self.waiting.delete(index) def cmd_seat(self, *args): if self.waiting.size != 0: self.buzzers.push('Buzzer') next_party = self.waiting._get_node(0) print(next_party.value) self.waiting.delete(0) else: raise IndexError('The given index is not within the bounds of the current list.') def cmd_debug(self, *args): self.callahead.debug_print() self.waiting.debug_print() self.appetizers.debug_print() self.buzzers.debug_print() self.songs.debug_print() def cmd_song(self, *args): val = self.songs_iter.next() print(val)
class Processor(object): def __init__(self): '''Creates the lists''' self.callahead = DoublyLinkedList() self.waiting = DoublyLinkedList() self.appetizers = Queue() self.buzzers = Stack() self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.songs = CircularLinkedList() self.songs.add('Song 1') self.songs.add('Song 2') self.songs.add('Song 3') self.songs_iter = CircularLinkedListIterator(self.songs) def run(self, f): '''Processes the given file stream.''' self.songs.debug_print() for line_i, line in enumerate(f): line = line.rstrip() comms = line.split(',') print('%d:%s' % (line_i, line)) if comms[0] == 'SEAT': print('SEAT >>>>', line) elif comms[0] == 'APPETIZER': wait_iter = DoublyLinkedListIterator(self.waiting) while wait_iter.has_next(): wait_iter.next() count = 0 person_array = [] try: food = self.appetizers.dequeue() except: print('error') while wait_iter.has_prev() and count < 3: person_array.append(wait_iter.node.value) count += 1 print('%s >>> %s' % (food, ', '.join(person_array))) elif comms[0] == 'SONG': self.songs_iter.next() print(self.songs_iter.node.value) elif comms[0] == 'LEAVE': self.waiting.delete(comms[1]) elif comms[0] == 'DEBUG': self.debug() elif comms[0] == 'ARRIVE': self.waiting.add(comms[1]) try: self.callahead.delete(comms[1]) except ValueError('error'): continue elif comms[0] == 'CALL': self.callahead.add(comms[1]) elif comms[0] == 'APPETIZER_READY': self.appetizers.enqueue(comms[1]) else: print("ERROR!!!!!", line) # split and handle the commands here def debug(self): '''print all objects''' self.callahead.debug_print() self.waiting.debug_print() self.appetizers.debug_print() self.buzzers.debug_print() self.songs.debug_print()
def test_stack_pop(self): s = Stack() s.push('a') s.push('b') s.push('c') self.assertEqual(s.pop(), 'c')
def test_stack_push(self): s = Stack() s.push('a') s.push('b') s.push('c') self.assertEqual(s.size, 3)
class Processor(object): def __init__(self): '''Creates the lists''' self.callahead = DoublyLinkedList() self.waiting = DoublyLinkedList() self.appetizers = Queue() self.buzzers = Stack() self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.buzzers.push('Buzzer') self.songs = CircularLinkedList() self.songs.add('Song 1') self.songs.add('Song 2') self.songs.add('Song 3') self.songs_iter = CircularLinkedListIterator(self.songs) def run(self, f): '''Processes the given file stream.''' for line_i, line in enumerate(f): line = line.rstrip() # split and handle the commands here print('{}:{}'.format(line_i, line)) parts = line.split(',') # call this command's function try: func = getattr(self, 'cmd_{}'.format(parts[0].lower())) func(*parts[1:]) except Exception as e: print('Error: {}'.format(e)) def cmd_debug(self, *args): self.callahead.debug_print() self.waiting.debug_print() self.appetizers.debug_print() self.buzzers.debug_print() self.songs.debug_print() def cmd_song(self, *args): print(self.songs_iter.next()) def cmd_appetizer(self, *args): app = self.appetizers.dequeue() i = self.waiting.size - 1 values = [] if self.waiting.size >= 3: while i >= self.waiting.size - 3: values.append(self.waiting.get(i)) i -= 1 elif self.waiting.size == 2: while i >= self.waiting.size - 2: values.append(self.waiting.get(i)) i -= 1 elif self.waiting.size == 1: while i >= self.waiting.size - 1: values.append(self.waiting.get(i)) i -= 1 else: values.append(self.waiting.get(i)) print('{} >>> {}'.format(app, ', '.join(values))) def cmd_appetizer_ready(self, *args): self.appetizers.enqueue(args[0]) def cmd_call(self, *args): self.callahead.add(args[0]) def cmd_arrive(self, *args): # check if they were on the callin list callaheadSize = self.callahead.size waitingSize = self.waiting.size callahead = False self.buzzers.pop() i = 0 while i < callaheadSize: if self.callahead.get(i) == args[0]: self.callahead.delete(i) callahead = True break i += 1 if callahead: if waitingSize <= 5: self.waiting.insert(0, args[0]) else: self.waiting.insert(waitingSize - 4, args[0]) else: self.waiting.add(args[0]) def cmd_seat(self, *args): try: print(self.waiting.get(0)) self.waiting.delete(0) self.buzzers.push('Buzzer') except: raise IndexError( 'The given index is not within the bounds of the current list.' ) def cmd_leave(self, *args): self.buzzers.push('Buzzer') waitingSize = self.waiting.size i = 0 while i < waitingSize: if self.waiting.get(i) == args[0]: self.waiting.delete(i) break i += 1