Genetic Turmit Evolver
python
c
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

turmit.py 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. from .rpnlib import *
  2. class Turmit(object):
  3. ''' @brief Represent a turmit that act given an RPN expression with an
  4. infinite looping stack with variable stack size.
  5. '''
  6. def __init__(self, stack_size=8):
  7. ## @brief List that represent a stack
  8. self._stack = [ 0 for _ in range(stack_size)]
  9. ## @brief Stack head index
  10. self._cur = stack_size - 1
  11. ## @brief Stores turmit direction
  12. self._dir = 0
  13. @property
  14. def shead(self):
  15. return self._stack[self._cur]
  16. def _pop(self):
  17. ''' @brief Pop a value from the stack
  18. If stack head is 0, set the stack head to len(self._stack) - 1
  19. @return poped value
  20. '''
  21. res = self._stack[self._cur]
  22. if self._cur == 0:
  23. self._cur = len(self._stack) - 1
  24. else:
  25. self._cur -= 1
  26. return res
  27. def _push(self, val):
  28. ''' @brief Push a value on the stack
  29. If no size left on the stack, the head is set to 0
  30. '''
  31. self._cur += 1
  32. if self._cur >= len(self._stack):
  33. self._cur = 0
  34. self._stack[self._cur] = val
  35. @RpnOp
  36. def mem_sz(self, new_sz):
  37. if new_sz < 2:
  38. raise ValueError('New size sould be >= 2')
  39. stksz = len(self._stack)
  40. if new_sz > stksz:
  41. self._stack += [ 0 for _ in range(new_sz - stksz) ]
  42. elif new_sz < stksz:
  43. self._stack = self._stack[0:new_sz]
  44. if self._cur >= new_sz:
  45. self._cur = 0
  46. @RpnOp
  47. def add(self, a, b):
  48. return a + b
  49. @RpnOp
  50. def sub(self, a, b):
  51. return a - b
  52. @RpnOp
  53. def bin_and(self, a, b):
  54. return a & b
  55. @RpnOp
  56. def dup(self, a):
  57. self._push(a)
  58. return a
  59. @RpnOp
  60. def lshift(self, a, b):
  61. return a << b