Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. # Grammar rules for a multi-digit decimal number
  2. # <expr> ::= +<num> | -<num> | <num>
  3. # <num> ::= <num><digits> | <digits>
  4. # <digits> ::= <digit> | <digit>.<digit>
  5. # <digit> ::= 0|1|2|3|4|5|6|7|8|9
  6. # Terminate every input string with ‘$’.
  7.  
  8. # P ---> E
  9. # E ---> +N | -N | N
  10. # N ---> DD | D.D
  11. # D ---> 0|1|2|3|4|5|6|7|8|9
  12. import sys
  13. import string
  14.  
  15. current = None
  16. st = ""
  17. ptr = 0
  18. hasDecimal = False
  19. hasPrefix = False
  20. numArr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
  21.  
  22.  
  23. def reset():
  24. global ptr
  25. global hasDecimal
  26. global hasPrefix
  27. hasDecimal = False
  28. hasPrefix = False
  29. ptr = 0
  30.  
  31.  
  32. def P():
  33. reset()
  34. global st
  35. st = input('Enter equation: ')
  36. st = st.translate(str.maketrans('', '', string.whitespace))
  37. if '$' not in st:
  38. print('Invalid')
  39. sys.exit(1)
  40. move()
  41. if current == '$':
  42. # P()
  43. sys.exit(1)
  44. E()
  45. if current == '$':
  46. print('Valid')
  47. else:
  48. print('Invalid')
  49. sys.exit(1)
  50.  
  51.  
  52. def E():
  53. print('<expr>')
  54. N()
  55. return
  56.  
  57.  
  58. def N():
  59. global hasDecimal
  60. print('<number>')
  61. D()
  62. if (not hasDecimal) and current == '.':
  63. hasDecimal = True
  64. move()
  65. N()
  66. elif hasDecimal and current == '.':
  67. print('Invalid')
  68. sys.exit(1)
  69. elif current in numArr:
  70. N()
  71. return
  72.  
  73.  
  74. def D():
  75. global numArr
  76. global hasPrefix
  77. print('<digit>')
  78. if current in numArr:
  79. move()
  80. # N()
  81. return
  82. elif (not hasPrefix) and current == '.' and ptr == 1:
  83. hasPrefix = True
  84. move()
  85. return
  86. elif (not hasPrefix) and (not hasDecimal) and current in ['+', '-'] and ptr != 0:
  87. if not lookahead():
  88. print('Invalid')
  89. sys.exit(1)
  90. hasPrefix = True
  91. E()
  92. else:
  93. print('Invalid')
  94. sys.exit(1)
  95.  
  96.  
  97. def move():
  98. global current
  99. global ptr
  100. current = st[ptr]
  101. print('current: ', current)
  102. ptr += 1
  103. return
  104.  
  105.  
  106. def lookahead():
  107. global ptr
  108. # if ptr <= len(st) - 2:
  109. # if st[ptr] == '.':
  110. # print(ptr, 'ohno')
  111. # return False
  112. if ptr == len(st):
  113. print('ohnoes')
  114. return False
  115. move()
  116. return True
  117.  
  118.  
  119. while True:
  120. P()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement