Advertisement
Guest User

Untitled

a guest
Nov 18th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.02 KB | None | 0 0
  1.  
  2. input = "0043-00334+5000"
  3.  
  4. digits={"1","2","3","4","5","6","7","8","9","0"}
  5. operators={"+", "-"}
  6.  
  7. def parse(input):
  8.  
  9.   currentInt = ""
  10.   tokens = []
  11.  
  12.   for i in range(0, len(input)):
  13.    
  14.     char = input[i]
  15.    
  16.     if char in digits:
  17.       currentInt += char
  18.    
  19.     if char in operators:
  20.       tokens.append(currentInt)
  21.       tokens.append(char)
  22.       currentInt = ""
  23.  
  24.     if(i == len(input)-1): #take care of the last digits since there's no operator after it
  25.         tokens.append(currentInt)
  26.  
  27.   return tokens
  28.          
  29. def popFirst(results):
  30.     token = results[0]
  31.     del results[0]
  32.     return token
  33.  
  34. def execute(results):
  35.  
  36.     total = int(popFirst(results))
  37.     while(len(results) > 0):
  38.  
  39.         operator = popFirst(results)
  40.         nextInt = int(popFirst(results))
  41.  
  42.         if operator == "+":
  43.             total += nextInt
  44.         if operator == "-":
  45.             total -= nextInt
  46.  
  47.     return total
  48.  
  49.  
  50. print(input)
  51. result = parse(input)
  52. print(result)
  53. print(execute(result))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement