Created
December 30, 2014 02:08
-
-
Save rahul8590/c12c045b6024b170587f to your computer and use it in GitHub Desktop.
CodeEval Challenge 7 (prefex solving )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/python | |
from __future__ import division | |
import operator | |
class Slack: | |
def __init__(self): | |
self.items = [] | |
def isempty(self): | |
return self.items == [] | |
def push(self, item): | |
self.items.append(item) | |
def pop(self): | |
return self.items.pop() | |
def size(self): | |
return len(self.items) | |
def peek(self): | |
print self.items | |
d = {'+': operator.add, | |
'-': operator.sub, | |
'*': operator.mul, | |
'/': operator.truediv, | |
'%': operator.mod | |
} | |
if __name__ == '__main__': | |
op = Slack() | |
val = Slack() | |
s = '- + * 2 3 * 5 4 9' | |
s = s.strip(' \t\r\n') | |
l = [i for i in s.split(' ')] | |
l.reverse() | |
print l | |
sum = 0 | |
for i in l: | |
if not d.has_key(i): | |
val.push(int(i)) | |
print "pushed i =>", i | |
else: | |
op.push(str(i)) | |
if val.size() >= 2: | |
try: | |
opt = str(op.pop()) | |
print "opt is =>", opt | |
op1 = val.pop() | |
op2 = val.pop() | |
sum = d[opt](op1, op2) | |
except ZeroDivisionError: | |
sum = 0 | |
val.push(sum) | |
#print "sum is =>", sum | |
# print "current op is =>",op.peek() | |
# print "current val is =>",val.peek() | |
print "sum =>", sum |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The above code is not passing all the test cases. Need to fix something .. not sure what is it ?