Advertisement
Guest User

Calculette Python by Yarflam

a guest
Feb 14th, 2013
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.44 KB | None | 0 0
  1. #!/usr/bin/python
  2. # Calculette v1.0 by Yarflam
  3.  
  4. def calc(exp):
  5.  r=''
  6.  i=0
  7.  while i < len(exp):
  8.   if exp[i]=='P' and exp[(i+1)]=='I':
  9.    r="3.1415926535897932384626433832795"
  10.   if exp[i] in '0123456789.':
  11.    r=r+exp[i]
  12.   if exp[i]=='+':
  13.    r=str(float(r)+calc(exp[(i+1):len(exp)]))
  14.    break
  15.   if exp[i]=='-':
  16.    r=str(float(r)-calc(exp[(i+1):len(exp)]))
  17.    break
  18.   if exp[i]=='*':
  19.    endx=exp.find('+',i) if (not exp.find('+',i) == -1) else len(exp)
  20.    endx=exp.find('-',i) if (not exp.find('-',i) == -1) and (exp.find('-',i) < endx) else endx
  21.    endx=calc_prio(exp) if (exp[(i+1)] == '(') else endx
  22.    i=i+1 if (exp[(i+1)] == '(') else i
  23.    r=str(float(r)*calc(exp[(i+1):endx]))
  24.    i=(endx-1)
  25.   if exp[i]=='/':
  26.    endx=exp.find('+',i) if (not exp.find('+',i) == -1) else len(exp)
  27.    endx=exp.find('-',i) if (not exp.find('-',i) == -1) and (exp.find('-',i) < endx) else endx
  28.    endx=calc_prio(exp) if (exp[(i+1)] == '(') else endx
  29.    i=i+1 if (exp[(i+1)] == '(') else i
  30.    r=str(float(r)/calc(exp[(i+1):endx]))
  31.    i=(endx-1)
  32.   if exp[i]=='(':
  33.    r=str(calc(exp[(i+1):calc_prio(exp)]))
  34.    exp=exp[calc_prio(exp)+1:len(exp)]
  35.    i=-1
  36.   i=i+1
  37.  return float(r)
  38.  
  39. def calc_prio(exp):
  40.  cmpp=exp.count('(',0)
  41.  l=-1
  42.  mx=-1
  43.  i=0
  44.  while i < len(exp) and (l >= 0 or mx < 0):
  45.   l=l+1 if exp[i]=='(' else l
  46.   l=l-1 if exp[i]==')' else l
  47.   mx=l if l > mx else mx
  48.   i=i+1
  49.  return (i-1)
  50.  
  51. c=raw_input('CALC: ')
  52. print "= ",calc(c)
  53. raw_input()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement