Guest User

Untitled

a guest
May 24th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. class Stack:
  2.  
  3. def __init__(self):
  4. self.items = []
  5.  
  6. def isEmpty(self):
  7. return self.items == []
  8.  
  9. def size(self):
  10. return len(self.items)
  11.  
  12. def push(self,item):
  13. self.items.append(item)
  14.  
  15. def pop(self):
  16. return self.items.pop()
  17.  
  18. def peek(self):
  19. return self.items[len(self.items)-1]
  20.  
  21.  
  22. # same as infix to postfix
  23. # reverse the for loop
  24. # consider ( as ) and ) as (
  25. # reverse the result in the end
  26. def infixToPrefix(str):
  27.  
  28. prec = "-+*/"
  29. s = Stack()
  30. postfix = ""
  31. for x in reversed(str):
  32. if(x in prec):
  33. print(f"in symbol {x}")
  34. if(s.isEmpty()):
  35. s.push(x)
  36. else:
  37. while(True):
  38. if(s.peek() == ")"):
  39. s.push(x)
  40. break
  41. if(prec.index(s.peek()) > prec.index(x)):
  42. postfix += s.pop()
  43. s.push(x)
  44. break
  45. else:
  46. s.push(x)
  47. break
  48. elif x == ")":
  49. s.push(x)
  50. elif x == "(":
  51. while(True):
  52. pop = s.pop()
  53. if(pop == ")"):
  54. break
  55. else:
  56. postfix += pop
  57. else:
  58. print(f"in else {x}")
  59. postfix += x
  60.  
  61. print(f"stack {s.items}")
  62. print(f"postfix {postfix}")
  63.  
  64. while not s.isEmpty():
  65. postfix += s.pop()
  66.  
  67. print(f"before reverse = {postfix}")
  68. result = ""
  69. for z in reversed(postfix):
  70. result = result +z
  71. print(f"after reverse result = {result}")
  72.  
  73.  
  74.  
  75. infixToPrefix("A+B*C")
  76. infixToPrefix("A*B+C/D")
  77. infixToPrefix("(A-B/C)*(A/K-L)")
Add Comment
Please, Sign In to add comment