from .rpnlib import * class Turmit(object): ''' @brief Represent a turmit that act given an RPN expression with an infinite looping stack with variable stack size. ''' def __init__(self, stack_size=8): ## @brief List that represent a stack self._stack = [ 0 for _ in range(stack_size)] ## @brief Stack head index self._cur = stack_size - 1 ## @brief Stores turmit direction self._dir = 0 @property def shead(self): return self._stack[self._cur] def _pop(self): ''' @brief Pop a value from the stack If stack head is 0, set the stack head to len(self._stack) - 1 @return poped value ''' res = self._stack[self._cur] if self._cur == 0: self._cur = len(self._stack) - 1 else: self._cur -= 1 return res def _push(self, val): ''' @brief Push a value on the stack If no size left on the stack, the head is set to 0 ''' self._cur += 1 if self._cur >= len(self._stack): self._cur = 0 self._stack[self._cur] = val @RpnOp def mem_sz(self, new_sz): if new_sz < 2: raise ValueError('New size sould be >= 2') stksz = len(self._stack) if new_sz > stksz: self._stack += [ 0 for _ in range(new_sz - stksz) ] elif new_sz < stksz: self._stack = self._stack[0:new_sz] if self._cur >= new_sz: self._cur = 0 @RpnOp def add(self, a, b): return a + b @RpnOp def sub(self, a, b): return a - b @RpnOp def bin_and(self, a, b): return a & b @RpnOp def dup(self, a): self._push(a) return a @RpnOp def lshift(self, a, b): return a << b