Guest User

Z calculator

a guest
Feb 4th, 2015
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.88 KB | None | 0 0
  1. def filter(equ):
  2.     equ = "".join(equ.split()).lower()
  3.     replace = (('||','|'),('{','('),('[','('),('}',')'),(']',')'),('i','j'))
  4.     for i,j in replace:
  5.         equ = equ.replace(i,j)
  6.     return equ
  7.  
  8. def rightscope(equ, start):
  9.     count = 0
  10.     count_change = False
  11.     for i in range(start+1, len(equ), 1):
  12.         if equ[i] == '(':
  13.             count += 1
  14.             count_change = True
  15.         elif equ[i] == ')':
  16.             count -= 1
  17.             count_change = True
  18.         elif equ[i] == '|' and count == 0:
  19.             return i-1
  20.         if count_change:
  21.             if count < 0:
  22.                 return i-1
  23.     return len(equ)-1
  24.  
  25. def leftscope(equ, start):
  26.     count = 0
  27.     count_change = False
  28.     for i in range(start-1, -1, -1):
  29.         if equ[i] == '(':
  30.             count += 1
  31.             count_change = True
  32.         elif equ[i] == ')':
  33.             count -= 1
  34.             count_change = True
  35.         elif equ[i] == '|' and count == 0:
  36.             return i+1
  37.         if count_change:
  38.             if count > 0:
  39.                 return i+1
  40.     return 0
  41.  
  42.  
  43. def parallel(zlist):
  44.     zsum = 0
  45.     for z in zlist:
  46.         zsum += 1/z
  47.     return 1/zsum
  48.  
  49. def zcalc(equ):
  50.     equ = filter(equ)
  51.     pos = equ.find('|')
  52.     while pos != -1:
  53.         parallel = []
  54.         temp_pos = pos
  55.         while True: #gather all scopes to the left into list
  56.             lpos = leftscope(equ, temp_pos)
  57.             parallel.insert(0, equ[lpos:temp_pos])
  58.             if (lpos == 0): break
  59.             elif (equ[lpos-1] != "|"): break
  60.             temp_pos = lpos-1
  61.         temp_pos = pos
  62.         while True: #gather all scope to the right into list
  63.             rpos = rightscope(equ, temp_pos)
  64.             parallel.append(equ[temp_pos+1:rpos+1])
  65.             if (rpos == len(equ)-1) or (equ[rpos+1] != "|"): break
  66.             temp_pos = rpos+1
  67.         new_equ = "parallel(["
  68.         for i in parallel:  #create string for paralleled function
  69.             new_equ = new_equ + i + ","
  70.         equ = equ[0:lpos] + new_equ[:len(new_equ)-1] + "])" + equ[rpos+1:]  #replace parallelized part of string with parallel string
  71.         pos = equ.find("|")
  72.     return equ
  73.     #return eval(equ)
  74.  
  75. test = "5j|5+(4+5j)|(4+(5j|-6j))"
  76. print(eval(zcalc(test)))
  77. #print(zcalc(test))
Advertisement
Add Comment
Please, Sign In to add comment