I'm having a lot of trouble converting infix notation to postfix.
For instance, I want to convert this
test(a(b+c), d()) - 3
into this
b c + a , d test 3 -
I tried this solution,
def composition(s):
i = 0
rpnstack = []
stack = []
ret = []
count = 0
while i < len(s) :
if i + 1 < len(s) and s[i + 1] == "(":
stack.append([count, rpnstack, s[i]])
i += 2
count = 1
rpnstack = []
elif s[i] == "(":
count += 1
rpnstack.append(s[i])
i += 1
elif s[i] == ")":
count -= 1
if count == 0:
for a in rpn(rpnstack):
ret.append(a)
a = stack.pop()
count = a[0]
rpnstack = a[1]
ret.append(a[2])
else:
rpnstack.append(s[i])
i += 1
else:
rpnstack.append(s[i])
i += 1
for a in rpn(rpnstack):
ret.append(a)
return ret
where RPN is the standard algorithm for the reverse polish notation and is is the infix string splitted with this regex
(\+|\-|\*|\/|\>|\<|\(|\)|\,)
But it only works sometimes.
This is the full implementation of the rpn function
operator = -10
operand = -20
leftparentheses = -30
rightparentheses = -40
empty = -50
operands = ["+", "-", "*", "/", ">", "<", "=", ","]
def precedence(s):
if s is '(':
return 0
elif s is '+' or '-':
return 1
elif s is '*' or '/' or '%':
return 2
else:
return 99
def typeof(s):
if s is '(':
return leftparentheses
elif s is ')':
return rightparentheses
elif s in operands:
return operator
elif s is ' ':
return empty
else :
return operand
def rpn(infix):
postfix = []
temp = []
for i in infix :
type = typeof(i)
if type is leftparentheses :
temp.append(i)
elif type is rightparentheses :
next = temp.pop()
while next is not '(' or skip > 0:
postfix.append(next)
next = temp.pop()
elif type is operand:
postfix.append(i)
elif type is operator:
p = precedence(i)
while len(temp) is not 0 and p <= precedence(temp[-1]) :
postfix.append(temp.pop())
temp.append(i)
elif type is empty:
continue
while len(temp) > 0 :
postfix.append(temp.pop())
return postfix
if i try to use the code against this infix expression:
i < test.func()
i get:
[' test.func', 'i ', '<']
and against this
i < 10
i get:
['i ', ' 10', '<']
How can I fix this?
Related
I learn about Reverse Polish Notation (:RPN).
I want to calculate Numerical formula by using RPN.
I managed to write following Program.
At a glance, this code work properly.
But, when I submitted this code to Programming Contest Site, (
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0109
) I got Wrong Answer.
What is wrong with my code?
# coding: utf-8
# Convert String to List
def String2List(s):
L = []
flag = True
l = len(s)
for i in range(l):
if s[i].isdigit() and flag:
t = ""
j = 0
while s[i+j].isdigit():
t += s[i+j]
if i+j == l-1:
break
j += 1
L.append(t)
flag = False
elif not s[i].isdigit():
L.append(s[i])
flag = True
return L
# generate Reverse Polish Notation
def RPN_list(L):
S, L2 = [], []
table = {"*": 1, "/": 1, "+": 0, "-": 0, "(": -1, ")": -1}
for i in L:
if i.isdigit():
L2.append(i)
elif i == "(":
S.append(i)
elif i == ")":
while S[-1] != "(":
L2.append(S.pop())
S.pop()
else:
if len(S) != 0 and (table[S[-1]] >= table[i]):
L2.append(S.pop())
S.append(i)
while len(S) != 0:
L2.append(S.pop())
return L2
# calculate Reverse Polish Notation
def RPN_cul(L):
St = []
for i in L:
if i == '+':
St.append(int(St.pop()) + int(St.pop()))
elif i == '-':
St.append(-int(St.pop()) + int(St.pop()))
elif i == '*':
St.append(int(St.pop()) * int(St.pop()))
elif i == '/':
a = int(St.pop())
b = float(St.pop())
St.append(b/a)
else:
St.append(i)
return St[0]
N = int(raw_input())
for i in range(N):
s = raw_input()
L = String2List(s[:-1])
L = RPN_list(L)
print int(RPN_cul(L))
Result
$ python reverse_polish_notation.py
2
4-2*3=
-2
4*(8+4+3)=
60
when I fixed as follows, It was accepted. Thanks to help me.
Before:
def RPN_list(L):
...
if len(S) != 0 and (table[S[-1]] >= table[i]):
L2.append(S.pop())
S.append(i)
...
After:
def RPN_list(L):
...
while len(S) != 0 and (table[S[-1]] >= table[i]):
L2.append(S.pop())
S.append(i)
...
polish_str="123*+4-"
#scan from left to right once you got the operator make the operation save the result again perform the operation
#result=3
polish_list=[]
for i in polish_str:
polish_list.append(i)
print(polish_list)
####
temp=[]
operator=['*',"+","/","-"]
def operation(o,a,b):
if o=="+":
result=a+b
if o=="-":
result=a-b
if o=="*":
result=a*b
if o=="/":
result=a/b
return result
for i,v in enumerate(polish_list):
if v in operator:
print(temp)
leng=len(temp)
arg1=temp.pop()
print("arg1==>",arg1)
arg2=temp.pop()
print("arg2==>",arg2)
result=operation(v,arg1,arg2)
print("result==>",result)
temp.append(result)
print("temp in iteration==>",temp)
else:
temp.append(i)
print("***final temp***",temp)
I am trying to convert the code here http://www.geeksforgeeks.org/expression-evaluation/ to python. However, I am running into some trouble and can't figure out.
class evaluateString:
def evalString(self,expression):
valueStack = []
opStack = []
i=0
while(i<len(expression)):
if(expression[i] == ' '):
continue
if(expression[i]>='0' and expression[i] <= '9'):
charNumber = [] #for storing number
while(i<len(expression) and expression[i]>='0' and expression[i] <= '9'):
charNumber.append(expression[i])
i+=1
valueStack.append(int(''.join(charNumber)))
elif (expression[i]=='('):
opStack.append(expression[i])
elif (expression[i]==')'):
while(opStack[-1]!='('):
valueStack.append(self.applyOperation(opStack.pop(),valueStack.pop(),valueStack.pop()))
opStack.pop()
elif(expression[i]=='+'or expression[i]=='-'or expression[i]=='*'or expression[i]=='/'):
while( (len(opStack)!=0) and ( self.opPrecedence(expression[i],opStack[-1]) ) ):
valueStack.append(self.applyOperation(opStack.pop(),valueStack.pop(),valueStack.pop()))
opStack.append(expression[i])
i = i + 1
while(len(opStack)!=0):
valueStack.append(self.applyOperation(opStack.pop(),valueStack.pop(),valueStack.pop()))
return valueStack.pop()
def applyOperation(self,op,a,b):
if op=='+':
return a+b
elif op=='-':
return a-b
elif op=='*':
return a*b
elif op=='/':
return a/b
else:
return 0
def opPrecedence(self,op1,op2):
if (op2 == '(' or op2 == ')'):
return False
if ((op1 == '*' or op1 == '/') and (op2 == '+' or op2 == '-')):
return False
else:
return True
a = evaluateString()
print(a.evalString("(5+7)"))
I am able to get the right numbers in the valueStack. However, there seems to be problem in the last two elseif. Can someone point me in the right direction?
I have done some fixes and it works for some operations. But I haven't tested it for all cases. Also, operations are only integers, no floats (e.g. check last output below).
class evaluateString:
def evalString(self,expression):
valueStack = []
opStack = []
i=0
while(i<len(expression)):
if(expression[i] == ' '):
continue
if(expression[i]>='0' and expression[i] <= '9'):
charNumber = [] #for storing number
j = i
while(j<len(expression) and expression[j]>='0' and expression[j] <= '9'):
charNumber.append(expression[j])
j += 1
i = (j-1)
valueStack.append(int(''.join(charNumber)))
elif (expression[i]=='('):
opStack.append(expression[i])
elif (expression[i]==')'):
while(opStack[-1]!='('):
valueStack.append(self.applyOperation(opStack.pop(),valueStack.pop(),valueStack.pop()))
opStack.pop()
elif(expression[i]=='+'or expression[i]=='-'or expression[i]=='*'or expression[i]=='/'):
while( (len(opStack)!=0) and ( self.opPrecedence(expression[i],opStack[-1]) ) ):
valueStack.append(self.applyOperation(opStack.pop(),valueStack.pop(),valueStack.pop()))
opStack.append(expression[i])
i = i + 1
while(len(opStack)!=0):
valueStack.append(self.applyOperation(opStack.pop(),valueStack.pop(),valueStack.pop()))
return valueStack.pop()
def applyOperation(self,op,a,b):
if op=='+':
return a+b
elif op=='-':
return b-a
elif op=='*':
return a*b
elif op=='/':
return b/a
else:
return 0
def opPrecedence(self,op1,op2):
if (op2 == '(' or op2 == ')'):
return False
if ((op1 == '*' or op1 == '/') and (op2 == '+' or op2 == '-')):
return False
else:
return True
a = evaluateString()
print(a.evalString("8*12")) #prints 96
print(a.evalString("(122-434)")) #prints -312
print(a.evalString("(232+12)/2")) #print 122
print(a.evalString("232/12+2")) #prints 21
In python eval() will evaluate infix expressions
print(eval("(5+7)/2"))
it will print the evaluated infix expression value as 6.
If I have 2 numbers in binary form as a string, and I want to add them I will do it digit by digit, from the right most end. So 001 + 010 = 011
But suppose I have to do 001+001, how should I create a code to figure out how to take carry over responses?
bin and int are very useful here:
a = '001'
b = '011'
c = bin(int(a,2) + int(b,2))
# 0b100
int allows you to specify what base the first argument is in when converting from a string (in this case two), and bin converts a number back to a binary string.
This accepts an arbitrary number or arguments:
>>> def bin_add(*bin_nums: str) -> str:
... return bin(sum(int(x, 2) for x in bin_nums))[2:]
...
>>> x = bin_add('1', '10', '100')
>>> x
'111'
>>> int(x, base = 2)
7
Here's an easy to understand version
def binAdd(s1, s2):
if not s1 or not s2:
return ''
maxlen = max(len(s1), len(s2))
s1 = s1.zfill(maxlen)
s2 = s2.zfill(maxlen)
result = ''
carry = 0
i = maxlen - 1
while(i >= 0):
s = int(s1[i]) + int(s2[i])
if s == 2: #1+1
if carry == 0:
carry = 1
result = "%s%s" % (result, '0')
else:
result = "%s%s" % (result, '1')
elif s == 1: # 1+0
if carry == 1:
result = "%s%s" % (result, '0')
else:
result = "%s%s" % (result, '1')
else: # 0+0
if carry == 1:
result = "%s%s" % (result, '1')
carry = 0
else:
result = "%s%s" % (result, '0')
i = i - 1;
if carry>0:
result = "%s%s" % (result, '1')
return result[::-1]
Can be simple if you parse the strings by int (shown in the other answer). Here is a kindergarten-school-math way:
>>> def add(x,y):
maxlen = max(len(x), len(y))
#Normalize lengths
x = x.zfill(maxlen)
y = y.zfill(maxlen)
result = ''
carry = 0
for i in range(maxlen-1, -1, -1):
r = carry
r += 1 if x[i] == '1' else 0
r += 1 if y[i] == '1' else 0
# r can be 0,1,2,3 (carry + x[i] + y[i])
# and among these, for r==1 and r==3 you will have result bit = 1
# for r==2 and r==3 you will have carry = 1
result = ('1' if r % 2 == 1 else '0') + result
carry = 0 if r < 2 else 1
if carry !=0 : result = '1' + result
return result.zfill(maxlen)
>>> add('1','111')
'1000'
>>> add('111','111')
'1110'
>>> add('111','1000')
'1111'
It works both ways
# as strings
a = "0b001"
b = "0b010"
c = bin(int(a, 2) + int(b, 2))
# as binary numbers
a = 0b001
b = 0b010
c = bin(a + b)
you can use this function I did:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
#a = int('10110', 2) #(0*2** 0)+(1*2**1)+(1*2**2)+(0*2**3)+(1*2**4) = 22
#b = int('1011', 2) #(1*2** 0)+(1*2**1)+(0*2**2)+(1*2**3) = 11
sum = int(a, 2) + int(b, 2)
if sum == 0: return "0"
out = []
while sum > 0:
res = int(sum) % 2
out.insert(0, str(res))
sum = sum/2
return ''.join(out)
def addBinary(self, A, B):
min_len, res, carry, i, j = min(len(A), len(B)), '', 0, len(A) - 1, len(B) - 1
while i>=0 and j>=0:
r = carry
r += 1 if A[i] == '1' else 0
r += 1 if B[j] == '1' else 0
res = ('1' if r % 2 == 1 else '0') + res
carry = 0 if r < 2 else 1
i -= 1
j -= 1
while i>=0:
r = carry
r += 1 if A[i] == '1' else 0
res = ('1' if r % 2 == 1 else '0') + res
carry = 0 if r < 2 else 1
i -= 1
while j>=0:
r = carry
r += 1 if B[j] == '1' else 0
res = ('1' if r % 2 == 1 else '0') + res
carry = 0 if r < 2 else 1
j -= 1
if carry == 1:
return '1' + res
return res
#addition of two binary string without using 'bin' inbuilt function
numb1 = input('enter the 1st binary number')
numb2 = input("enter the 2nd binary number")
list1 = []
carry = '0'
maxlen = max(len(numb1), len(numb2))
x = numb1.zfill(maxlen)
y = numb2.zfill(maxlen)
for j in range(maxlen-1,-1,-1):
d1 = x[j]
d2 = y[j]
if d1 == '0' and d2 =='0' and carry =='0':
list1.append('0')
carry = '0'
elif d1 == '1' and d2 =='1' and carry =='1':
list1.append('1')
carry = '1'
elif (d1 == '1' and d2 =='0' and carry =='0') or (d1 == '0' and d2 =='1' and
carry =='0') or (d1 == '0' and d2 =='0' and carry =='1'):
list1.append('1')
carry = '0'
elif d1 == '1' and d2 =='1' and carry =='0':
list1.append('0')
carry = '1'
else:
list1.append('0')
if carry == '1':
list1.append('1')
addition = ''.join(list1[::-1])
print(addition)
Not an optimal solution but a working one without use of any inbuilt functions.
# two approaches
# first - binary to decimal conversion, add and then decimal to binary conversion
# second - binary addition normally
# binary addition - optimal approach
# rules
# 1 + 0 = 1
# 1 + 1 = 0 (carry - 1)
# 1 + 1 + 1(carry) = 1 (carry -1)
aa = a
bb = b
len_a = len(aa)
len_b = len(bb)
min_len = min(len_a, len_b)
carry = 0
arr = []
while min_len > 0:
last_digit_aa = int(aa[len(aa)-1])
last_digit_bb = int(bb[len(bb)-1])
add_digits = last_digit_aa + last_digit_bb + carry
carry = 0
if add_digits == 2:
add_digits = 0
carry = 1
if add_digits == 3:
add_digits = 1
carry = 1
arr.append(add_digits) # will rev this at the very end for output
aa = aa[:-1]
bb = bb[:-1]
min_len -= 1
a_len_after = len(aa)
b_len_after = len(bb)
if a_len_after > 0:
while a_len_after > 0:
while carry == 1:
if len(aa) > 0:
sum_digit = int(aa[len(aa) - 1]) + carry
if sum_digit == 2:
sum_digit = 0
carry = 1
arr.append(sum_digit)
aa = aa[:-1]
else:
carry = 0
arr.append(sum_digit)
aa = aa[:-1]
else:
arr.append(carry)
carry = 0
if carry == 0 and len(aa) > 0:
arr.append(aa[len(aa) - 1])
aa = aa[:-1]
a_len_after -= 1
if b_len_after > 0:
while b_len_after > 0:
while carry == 1:
if len(bb) > 0:
sum_digit = int(bb[len(bb) - 1]) + carry
if sum_digit == 2:
sum_digit = 0
carry = 1
arr.append(sum_digit)
bb = bb[:-1]
else:
carry = 0
arr.append(sum_digit)
bb = bb[:-1]
else:
arr.append(carry)
carry = 0
if carry == 0 and len(bb) > 0:
arr.append(bb[len(bb) - 1])
bb = bb[:-1]
b_len_after -= 1
if carry == 1:
arr.append(carry)
out_arr = reversed(arr)
out_str = "".join(str(x) for x in out_arr)
return out_str
I am making some practice code for a game similar to the board game, MasterMind-- and It keeps coming out with this error, and I can't figure out why it's doin it. Here's the code:
def Guess_Almost (Guess, Answer):
a = ''.join([str(v) for v in Answer])
g = str(Guess)
n = 0
am = 0
while n < 5:
if g[n] == a[0]:
am = am + 1
if g[n] == a[2]:
am = am + 1
if g[n] == a[3]:
am = am + 1
if g[n] == a[3]:
am = am + 1
n = n + 1
return(am)
Okay, the Guess is specified to be 4 integers, and the Answer is a list containing 4 numbers. They both have the same 'len' after the code, so i don't have a clue.
The point of this code is to turn the Answer into a string of 4 numbers, and see if any of those numbers match thoise of the guess, and return how many total matches there are.
See if this helps
def Guess_Almost (Guess, Answer):
a = ''.join([str(v) for v in Answer])
g = str(Guess)
n = 0
am = 0
if len(g) >= 5 and len(a) >=4:
while n < 5:
if g[n] == a[0]:
am = am + 1
if g[n] == a[2]:
am = am + 1
if g[n] == a[3]:
am = am + 1
if g[n] == a[3]:
am = am + 1
n = n + 1
return(am)
import string
# Strength of operations:
# -> [] (brackets)
# 6 -> ~ (negative)
# 5 -> #, $, & (average, maximum, minimum)
# 4 -> %, ! (modulo, factorial)
# 3 -> ^ (power)
# 2 -> *, / (multiplication, division)
# 1 -> +, - (addition, subtraction)
def BinaryOperation(exp, idx):
""" Gets an expression and an index of an operator and returns a tuple with (first_value, operator, second_value). """
first_value = 0
second_value = 0
#Get first value
idx2 = idx -1
if idx2 == 0:
first_value = exp[idx2:idx]
else:
while (idx2 > 0) and (exp[idx2] in string.digits):
idx2 -=1
if (exp[idx2] in ("-")) or (exp[idx2] in string.digits):#-5*3
first_value = exp[idx2:idx]
else:#%5*3
first_value = exp[idx2+1:idx]
#Get second value
idx2 = idx +1
if exp[idx+1] not in string.digits: #If there is something like 1*+5, second_sign will be +.
idx2 += 1 #idx2 will begin from the char after the sign.
while (idx2 < len(exp)) and (exp[idx2] in string.digits):
idx2 += 1
second_value = exp[idx+1:idx2]
return (first_value, exp[idx], second_value)
def UnaryOperation(exp, idx):
""" Gets an expression and an index of an operator and returns a tuple with (operator, value). """
#Get value
idx2 = idx+1
if exp[idx+1] not in string.digits: #If there is something like ~-5, second_sign will be -.
idx2 += 1 #idx2 will begin from the char after the sign.
while (idx2 < len(exp)) and (exp[idx2] in string.digits):
idx2 +=1
return (exp[idx], exp[idx+1:idx2])
def Brackets(exp):
idx = 0
while idx < len(exp):
if exp[idx] == "[":
#Brackets
close_bracket = exp.find("]")
if close_bracket == -1:
raise Exception("Missing closing bracket.")
exp_brackets = exp[idx+1:close_bracket]
value = str(solve(exp_brackets))
exp = exp.replace("[" + exp_brackets + "]", value)
idx = 0 #The len has been changed, scan again.
idx += 1
return Level6(exp)
def Level6(exp):
idx = 0
while idx < len(exp):
if exp[idx] in ("~"):
#Negative
sub_exp = UnaryOperation(exp, idx)
value = ~int(sub_exp[1])
value = str(value)
exp = exp.replace(''.join(sub_exp), value)
idx = 0 #The len has been changed, scan again.
idx += 1
return Level5(exp)
def Level5(exp):
idx = 0
while idx < len(exp):
if exp[idx] in ("#", "$", "&"):
#Average, Maximum and Minimum
sub_exp = BinaryOperation(exp, idx)
first_value = int(sub_exp[0])
second_value = int(sub_exp[2])
if sub_exp[1] == "#":
value = (first_value + second_value)/2
if sub_exp[1] == "$":
value = first_value if first_value > second_value else second_value
if sub_exp[1] == "&":
value = first_value if first_value < second_value else second_value
value = str(value)
exp = exp.replace(''.join(sub_exp), value)
idx = 0 #The len has been changed, scan again.
idx += 1
return Level4(exp)
def Level4(exp):
idx = 0
while idx < len(exp):
if exp[idx] in ("%","!"):
#Modulo and Factorial
if exp[idx] == "%":
sub_exp = BinaryOperation(exp, idx)
value = int(sub_exp[0]) % int(sub_exp[2])
if exp[idx] == "!":
sub_exp = UnaryOperation(exp, idx)
value = reduce(lambda x,y:x*y, range(1, int(sub_exp[1])+1))
value = str(value)
exp = exp.replace(''.join(sub_exp), value)
idx = 0 #The len has been changed, scan again.
idx += 1
return Level3(exp)
def Level3(exp):
idx = 0
while idx < len(exp):
if exp[idx] in ("^"):
#Power
sub_exp = BinaryOperation(exp, idx)
value = int(sub_exp[0]) ** int(sub_exp[2])
value = str(value)
exp = exp.replace(''.join(sub_exp), value)
idx = 0 #The len has been changed, scan again.
idx += 1
return Level2(exp)
def Level2(exp):
idx = 0
while idx < len(exp):
if exp[idx] in ("*", "/"):
#Multiplication and Division
sub_exp = BinaryOperation(exp, idx)
if sub_exp[1] == "*":
value = int(sub_exp[0]) * int(sub_exp[2])
if sub_exp[1] == "/":
value = int(sub_exp[0]) / int(sub_exp[2])
value = str(value)
exp = exp.replace(''.join(sub_exp), value)
idx = 0 #The len has been changed, scan again.
idx += 1
return Level1(exp)
def Level1(exp):
idx = 0
while idx < len(exp):
if (exp[idx] in ("+", "-")) and (idx != 0):
#Addition and Subtraction
sub_exp = BinaryOperation(exp, idx)
if sub_exp[1] == "+":
value = int(sub_exp[0]) + int(sub_exp[2])
if sub_exp[1] == "-":
value = int(sub_exp[0]) - int(sub_exp[2])
value = str(value)
exp = exp.replace(''.join(sub_exp), value)
idx = 0 #The len has been changed, scan again.
idx += 1
return exp
def solve(exp):
exp = Brackets(exp)
return float(exp) if "." in exp else int(exp)
def remove_whitespace(exp):
""" Gets a string and removes all whitespaces and tabs """
exp = exp.replace(" ", "")
exp = exp.replace("\t", "")
return exp
while True:
exp = raw_input("")
exp = remove_whitespace(exp)
print solve(exp)
I have written this program after a lot of effort, and I was wondering about the efficiency of that solution and if it's neat.
So my question is, how plain is this program and is there any better way to rewrite it?
just for the point.
>>> eval(raw_input("input calculation: "))
input calculation: 1+1
2
>>> eval(raw_input("input calculation: "))
input calculation: (6*4^2)
26
>>> eval(raw_input("input calculation: "))
input calculation: (3/2.3)*4
5.2173913043478262
for an innocent program, you can use eval
but you really shouldn't use it ever. its only real use is confusing people, and being a fun novelty if you write programs fro yourself and decide you want a calculator.
there are many ways to write a calculator function.
try some of these other answers:
Python creating a calculator
Basic calculator program in python
python calculator program
If you want to check out some custom class-based evaluation engines in Python, these might help you:
Expression Evaluator (version 1 with source)
Math Evaluator (version 2 with source)
again = True
answer = ""
while again is True:
try:
expression = raw_input("Enter your expression: ")
found = False
oper = -1
operator1 = 0
operator2 = 0
while found==False:
if (expression.find("+")>0 and expression.find("+")<len(expression)-1):
found = True
oper = expression.find("+")
operator1 = float(expression[:oper])
operator2 = float(expression[oper+1:])
print "{} + {} = {}".format(operator1,operator2,operator1+operator2)
elif(expression.find("-")>0 and expression.find("-")<len(expression)-1):
found = True
oper = expression.find("-")
operator1 = float(expression[:oper])
operator2 = float(expression[oper+1:])
print "{} - {} = {}".format(operator1,operator2,operator1-operator2)
elif(expression.find("*")>0 and expression.find("*")<len(expression)-1):
found = True
oper = expression.find("*")
operator1 = float(expression[:oper])
operator2 = float(expression[oper+1:])
print "{} * {} = {}".format(operator1,operator2,operator1*operator2)
elif(expression.find("/")>0 and expression.find("/")<len(expression)-1):
found = True
oper = expression.find("/")
operator1 = float(expression[:oper])
operator2 = float(expression[oper+1:])
print "{} / {} = {}".format(operator1,operator2,operator1/operator2)
else:
oper = -1
found = False
print "Incorrect expression, please try again"
break
again = False
answer = raw_input("Try again?: ")
if(answer == "y" or answer=="yes" or answer =="Y" or answer == "YES"):
again = True
else:
again = False
print "Thank you for playing! See you next time."
break
except:
print "Failed, check your expression and try again"