Hi, I am trying to build a calculator, no parentheses required, supporting negative figures.
And I have written some codes and use visualize Python several times.
It seems my loop stop function once it has been executed.
Could anyone please kindly tell me why and how can i fix the bug?
Thank you very much.
=---------------------------------------
And I have written some codes and use visualize Python several times.
It seems my loop stop function once it has been executed.
Could anyone please kindly tell me why and how can i fix the bug?
Thank you very much.
=---------------------------------------
def Calculator(s): s=list(s.replace(" ","")) operator=["+", "-", "*", "/"] ### create series from 0~9 num=map(str,(range(10))) ###calculate extra space number count= len([i for i in s if i in operator]) if s[0]=='+' or s[0]=='-': count -= 1 for i in range(len(s)): if (s[i] in operator)and(s[i+1] in operator) : count -= 1 ###seperate operators and figures with space for i in range(1,len(s)+count*2): if (s[i] in operator)and(s[i+1] in operator) : s.insert(i+1," ") s.insert(i," ") elif (s[i] in operator)and(s[i-1] in num): s.insert(i+1," ") s.insert(i," ") s= ''.join(s) s=s.split() ### * / first a=0 for i in s: if i=="*" or i=="/": a+=1 for i in range(a): for i in s: if i =="*": v=str(float(s[s.index(i)-1])*float(s[s.index(i)+1])) s.pop(s.index(i)+1) s.pop(s.index(i)-1) s.insert(s.index(i),v) s.pop(s.index(i)) break elif i =="/": p=str(float(s[s.index(i)-1])/float(s[s.index(i)+1])) s.pop(s.index(i)+1) s.pop(s.index(i)-1) s.insert(s.index(i),p) s.pop(s.index(i)) break ### then + - b=0 for i in s: if i=="+" or i=="-": b+=1 for i in range(b): for i in s: if i =="+": v=str(float(s[s.index(i)-1])+float(s[s.index(i)+1])) s.pop(s.index(i)+1) s.pop(s.index(i)-1) s.insert(s.index(i),v) s.pop(s.index(i)) break elif i =="-": p=str(float(s[s.index(i)-1])-float(s[s.index(i)+1])) s.pop(s.index(i)+1) s.pop(s.index(i)-1) s.insert(s.index(i),p) s.pop(s.index(i)) break your_ans=float(s[0]) return your_ans s='-7.3 +-2 * -8 /1.6' Calculator(s)