Advertisement
ShrekOP

3AC-Python

Dec 16th, 2022
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.62 KB | None | 0 0
  1. input_expression = "a = b + c + d * e + f + g"
  2. print("\nInput Expression:-")
  3. print(input_expression)
  4. print()
  5.  
  6. arithmetic = ["*", "/", "+", "-", "^"]
  7. extra = ["if", "else","while"]
  8. assign = ["="]
  9. res = []
  10. id = 1
  11. temp1 = ""
  12. expression = input_expression
  13. if expression[0] not in extra:
  14. x = expression.split()
  15. temp0 = x[-2]
  16. x[-2] = "$"
  17. i = 2
  18. while x[i] != "$":
  19. if x[i] in arithmetic:
  20. if x[i + 1].startswith("-"):
  21. temp = "T" + str(id) + " = " + x[i + 1]
  22. res.append(temp)
  23. del x[i + 1]
  24. x.insert(i + 1, "T" + str(id))
  25. id += 1
  26. i += 1
  27. x[-2] = temp0
  28.  
  29. while len(x) > 3:
  30. if x[2].startswith("-"):
  31. temp = "T" + str(id) + " = " + x[2]
  32. res.append(temp)
  33. del x[2]
  34. x.insert(2, "T" + str(id))
  35. id += 1
  36.  
  37. elif '^' in x:
  38. oper = x.index('^')
  39. temp = "T" + str(id) + " = " + x[oper - 1] + " " + x[oper] + " " + x[oper + 1]
  40. res.append(temp)
  41. for i in range(3):
  42. del x[oper - 1]
  43. x.insert(oper - 1, "T" + str(id))
  44. id += 1
  45. elif '/' in x:
  46. oper = x.index('/')
  47. temp = "T" + str(id) + " = " + x[oper - 1] + " " + x[oper] + " " + x[oper + 1]
  48. res.append(temp)
  49. for i in range(3):
  50. del x[oper - 1]
  51. x.insert(oper - 1, "T" + str(id))
  52. id += 1
  53. elif '*' in x:
  54. oper = x.index('*')
  55. temp = "T" + str(id) + " = " + x[oper - 1] + " " + x[oper] + " " + x[oper + 1]
  56. res.append(temp)
  57. for i in range(3):
  58. del x[oper - 1]
  59. x.insert(oper - 1, "T" + str(id))
  60. id += 1
  61. elif '+' in x:
  62. oper = x.index('+')
  63. temp = "T" + str(id) + " = " + x[oper - 1] + " " + x[oper] + " " + x[oper + 1]
  64. res.append(temp)
  65. for i in range(3):
  66. del x[oper - 1]
  67. x.insert(oper - 1, "T" + str(id))
  68. id += 1
  69. elif '-' in x:
  70. oper = x.index('-')
  71. temp = "T" + str(id) + " = " + x[oper - 1] + " " + x[oper] + " " + x[oper + 1]
  72. res.append(temp)
  73. for i in range(3):
  74. del x[oper - 1]
  75. x.insert(oper - 1, "T" + str(id))
  76. id += 1
  77. for i in x:
  78. temp1 += str(i) + " "
  79.  
  80. res.append(temp1)
  81.  
  82. print("Generated Three Address Code:-")
  83. for i in res:
  84. print(i)
  85.  
  86. f = open("input1.txt", "w")
  87. f.write("\n".join(res))
  88. f.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement