Guest User

Untitled

a guest
Nov 20th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. def generate_AST(string):
  2.  
  3. # my implementation is currently supporting negative numbers and decimals,
  4. # but not exponentiation
  5.  
  6. number_symbols = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '-']
  7.  
  8. ind = 1
  9. arr_to_return = []
  10.  
  11. while ind < len(string):
  12. char = string[ind]
  13.  
  14. if char == "(":
  15. open_cnt = 1
  16. closed_cnt = 0
  17. sub_str = "("
  18. for c in string[ind + 1:]:
  19. if c == "(": open_cnt += 1
  20. if c == ")": closed_cnt += 1
  21. sub_str += c
  22. if open_cnt == closed_cnt: break
  23. arr_to_return.append(generate_AST(sub_str))
  24. ind += len(sub_str)
  25.  
  26. elif char == " " or char == ")":
  27. ind += 1
  28.  
  29. else:
  30. stop_ind = string.find(" ", ind)
  31. if stop_ind == -1:
  32. stop_ind = string.find(")", ind)
  33. s = string[ind:stop_ind]
  34. if all(x in number_symbols for x in list(s)):
  35. if s.find('-', 1) == -1:
  36. num = float(s)
  37. arr_to_return.append(num)
  38. else:
  39. arr_to_return.append(s)
  40. ind = stop_ind + 1
  41.  
  42. return arr_to_return
  43.  
  44. print(generate_AST("(first (list -1.5 (+ 2 3) 9))"))
Add Comment
Please, Sign In to add comment