Advertisement
Merxlc

bf.py

May 25th, 2021
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. import sys
  2. import msvcrt
  3.  
  4. def execute(filename):
  5. f = open(filename, "r")
  6. evaluate(f.read())
  7. f.close()
  8.  
  9.  
  10. def evaluate(code):
  11. code = cleanup(list(code))
  12. bracemap = buildbracemap(code)
  13.  
  14. cells, codeptr, cellptr = [0], 0, 0
  15.  
  16. while codeptr < len(code):
  17. command = code[codeptr]
  18.  
  19. if command == ">":
  20. cellptr += 1
  21. if cellptr == len(cells): cells.append(0)
  22.  
  23. if command == "<":
  24. cellptr = 0 if cellptr <= 0 else cellptr - 1
  25.  
  26. if command == "+":
  27. cells[cellptr] = cells[cellptr] + 1 if cells[cellptr] < 255 else 0
  28.  
  29. if command == "-":
  30. cells[cellptr] = cells[cellptr] - 1 if cells[cellptr] > 0 else 255
  31.  
  32. if command == "[" and cells[cellptr] == 0: codeptr = bracemap[codeptr]
  33. if command == "]" and cells[cellptr] != 0: codeptr = bracemap[codeptr]
  34. if command == ".": sys.stdout.write(chr(cells[cellptr]))
  35. if command == ",": cells[cellptr] = ord(msvcrt.getch())
  36.  
  37. codeptr += 1
  38.  
  39.  
  40. def cleanup(code):
  41. return ''.join(filter(lambda x: x in ['.', ',', '[', ']', '<', '>', '+', '-'], code))
  42.  
  43.  
  44. def buildbracemap(code):
  45. temp_bracestack, bracemap = [], {}
  46.  
  47. for position, command in enumerate(code):
  48. if command == "[": temp_bracestack.append(position)
  49. if command == "]":
  50. start = temp_bracestack.pop()
  51. bracemap[start] = position
  52. bracemap[position] = start
  53. return bracemap
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement