Parser.py
python
posted: Jun, 6th 2012 | jump to bottom
#!/usr/bin/env python def findNextNumber(): floatnum = 0 return floatnum def parsing(string): container = [] stacking = [] numparse = "" for item in string: if item.isalnum() or item == "." : numparse += item else: if numparse != "": container.append(numparse) numparse = "" stackOperation(item, stacking, container) if numparse: container.append(numparse) stackOperation("~", stacking, container) return container def stackOperation(item , stacking, container): if stacking == [] : stacking.append(item) else: if item == ")": while 1: if stacking[-1] == "(" : stacking.pop() break elif not stacking: break else: container.append(stacking.pop()) elif item == "~": while 1: if not stacking: break elif stacking[-1] == "(" : stacking.pop() else: container.append(stacking.pop()) elif priority(stacking[-1] ) == 4: stacking.append(item); elif priority(item) > priority(stacking[-1]) : stacking.append(item) elif priority(item) < priority(stacking[-1]) : while 1: if not stacking: break elif stacking[-1] == "(" : break else: container.append(stacking.pop()) stacking.append(item) return def calculate(postfix): while 1: area2BModified = [] i = 0 for item in postfix: #print postfix[i][0].isalnum() if not item[0].isalnum(): if postfix[i-1][0].isalnum() and postfix[i-2][0].isalnum(): area2BModified.append(i) i = i + 1 #for item in area2BModified: # print item #print len(postfix) #for item in postfix: # print item #print "\n" if len(postfix) == 1: break count = 0 for item in area2BModified: #print item item = item - count #print float(postfix[item - 1]) #print postfix[item] #print float(postfix[item - 2]) temp = operationPart(postfix[item - 2], postfix[item - 1], postfix[item]) postfix.pop(item ) postfix.pop(item - 1) postfix.pop(item - 2) postfix.insert(item - 2, repr(temp)) count = count + 2 del area2BModified[:] return postfix def operationPart(num1, num2, operand): if operand == "-" : return float(num1) - float(num2) elif operand == "+" : return float(num1) + float(num2) elif operand == "*" : return float(num1) * float(num2) elif operand == "/" : return float(num1) / float(num2) return def priority(item): if item == "-" : return 1 elif item == "+" : return 2 elif item == "*" : return 3 elif item == "/" : return 4 elif item == "(" : return 5 return a = "2.5+3*(59-23)+4/2" postfix = parsing(a) #for item in postfix: # print item #print float(postfix[2]) result = calculate(postfix) print result[0] #print a[1].isalnum() #lalalulu = [3,4,5,6] #print lalalulu[-1]
26 views




