Mathematical Operations Parser and Evaluator

Slide Note
Embed
Share

This program reads a mathematical expression, tokenizes it, and evaluates it based on the order of operations. It demonstrates parsing infix to postfix notation and evaluating postfix expressions. The code contains functions for cleaning input, tokenizing expressions, and calculating results, along with handling errors related to operation order. Images and links to Reeborg's World are included for visual demonstrations.


Uploaded on Sep 11, 2024 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. s='123.4+ 12*3.1-34/3 +2 \ -7//2 +2**3+11=' def curatare(s): ss='' for c in s: if c not in '\t\ ': ss+=c return ss def tokenizer(s): lista=[] i,prec=0,0 while i<len(s): #fara = nu ne ataseaza ultimul numar if s[i] in '*/+-=': lista.append(s[prec:i]) if s[i]=='*' and s[i+1]=='*': lista.append('**') i+=1 elif s[i]=='/' and s[i+1]=='/': lista.append('//') i+=1 else: lista.append(s[i]) prec=i+1 i+=1 return lista print(s) s=curatare(s)#curata space, tab, \ print(s) dict={'**':lambda a, b : a ** b, '*': lambda a, b : a * b, '//':lambda a, b : a // b, '/': lambda a, b : a / b, '+': lambda a, b : a + b, '-': lambda a, b : a - b} #o singura lista pt. numere si operatori lista=tokenizer(s) print(lista) ['123.4', '+', '12', '*', '3.1', '-', '34', '/', '3', '+', '2', '-', '7', '//', '2', '+', '2', '**', '3', '+', '11', '=']

  2. def calcul(lista): i=0; lista0=[] while i < len(lista)-2: a, op, b = lista[i:i+3] print(a,op,b) if op in ['**','*','//','/']: lista0.append(dict[op](float(a), float(b)) ) i+=2 else: lista0.append(a) #a este numar,+ sau - print(lista0) i+=1 lista0.append(lista[len(lista)-2])#ultimul numar print(lista0) lista=lista0 suma=float(lista[0]) for i in range(1, len(lista), 2): op, b = lista[i:i+2] #op este + sau - suma=dict[op](suma, float(b) ) print(suma) return suma Erori ale programului Programul NU tine cont de ordinea operatiilor pentru **: Si calculeaza gresit de la stanga la dreapta 2**3**2=8**2=64 (Corect este 2**3**2=2**9=512 de la dreapta la stanga) suma=calcul(lista) print(suma)

  3. EVAL versiunea II def infix2postfix(s): prec = {'**':4,'*':3,'//':3,'/':3,'+':2,'-':2} s = s.split() stack = [] ss = [] dict={'**':lambda a, b : a ** b, '*': lambda a, b : a * b, '//':lambda a, b : a // b, '/': lambda a, b : a / b, '+': lambda a, b : a + b, '-': lambda a, b : a - b} for val in s: if val in dict.keys(): while len(stack)>0 and \ ss.append(stack.pop()) stack.append(val) else: ss.append(val) #print(val, stack, postfixList) for op in stack[::-1]: ss.append(op) return ' '.join(ss) def eval_postfix(s): s = s.split() stack = [] for val in s: if val in dict.keys(): op = dict[val] a,b = stack[-2:] stack[-2:] = [op(a,b)] else: stack.append(float(val)) #print(val, stack) return stack[-1] (prec[stack[-1]] >= prec[val]): s='123.4 + 12 * 3.1 - 34 / 3 + 2 - 7 // 2 + 2 ** 3 + 11' ss=infix2postfix(s) print(ss) print(eval_postfix(ss)) #print(eval_postfix('1 2 + 7 /'))

  4. http://reeborg.ca/ Home4 while not at_goal(): if front_is_clear(): move() else: if wall_on_right(): turn_left() else: turn_right() Tokens3 while not at_goal(): if object_here(): take() move() put('token') move() else: move() Tokens4 Tokens 5 while not at_goal(): if object_here(): take() move() else: while carries_object(): put('token') move()

  5. Around1-apple move() while not at_goal(): if front_is_clear(): if object_here(): take() else: move() else: turn_left() Around1-variable put('token') move() while not object_here(): if front_is_clear(): move() else: turn_left() Around2 put('token') move() while not object_here(): if wall_in_front(): turn_left() else: if wall_on_right(): move() else: turn_right() move() Around3 Insert turn_left() in Around2 Around4 Insert turn_left() turn_left() move() turn_right() in Around2

  6. Tokens6 Puzzle Aduna n tokens asezate aleator si le pune la n pasi de cel mai din dreapta token think(0) from random import randrange #World("Alone") n=15 RUR.set_world_size(n, 1) goal = n, 1 start = 1, 1 RUR.add_initial_position(*start) RUR.add_final_position("house", *goal) count = randrange(3,6) pos=0 maxim=0 for i in range(count): pos=randrange(1,n-count) print(i+1,pos) if maxim<pos: maxim=pos RUR.add_object( token , pos, 1) print(count,pos) RUR.add_object("token", maxim+count, 1, {"number": count, "goal": True})

  7. count=0 pos=1 pos_object=0 while front_is_clear(): if object_here(): while object_here(): take('token') count+=1 pos_object=pos print(pos_object) move() pos+=1 else: move() pos+=1 turn_left() turn_left() for i in range(pos-pos_object-count): move() turn_left() turn_left() while carries_object(): put('token') for i in range(pos-pos_object-count): move()

  8. from library import up, down, right, left think(0) up(3) right() #World("Alone") RUR.set_world_size(7, 7) a=[[1,1,1,1,1,1,1], [1,0,0,1,1,1,1], [1,0,0,1,0,0,1], [1,0,0,0,0,0,1], [1,1,0,0,0,0,1], [1,1,0,0,0,0,1], [1,1,1,1,1,1,1]] for r in range(7): for c in range(7): if a[r][c]==1: RUR.add_obstacle('bricks',c+1,r+1) RUR.add_pushable('box',3,4) RUR.add_pushable('box',5,4) RUR.add_pushable('box',3,2,{'goal':True}) RUR.add_pushable('box',2,4,{'goal':True})

  9. def up(n=1): RUR.CURRENT_WORLD.robots[0]._orientation = RUR.NORTH for i in range(n): move() #movebox() def down(n=1): RUR.CURRENT_WORLD.robots[0]._orientation = RUR.SOUTH for i in range(n): move() #movebox() def left(n=1): RUR.CURRENT_WORLD.robots[0]._orientation = RUR.WEST for i in range(n): move() #movebox() def movebox(): if object_here('box'): take("box") toss("box") def right(n=1): RUR.CURRENT_WORLD.robots[0]._orientation = RUR.EAST for i in range(n): move() #movebox()

  10. Think(300) right() up() right(3) down(2) left() up() left(2) right(3) up() left(2) up() left() down(3)

  11. from random import randrange def adaug(m): n=len(m) for i in range(n*n//2): x=randrange(n*n) r=x//n;c=x%n m[r][c]=1 return m def life(m): n=len(m) nextm=[[0]*n for i in range(n)] for r in range(n): for c in range(n): v=vecini(m,r,c) if v<2 or v>3: nextm[r][c]=0 elif v==3 and m[r][c]==0: nextm[r][c]=1 else: nextm[r][c]=m[r][c] return nextm def afis(m): n=len(m) for r in range(n): for c in range(n): if m[r][c]==1: RUR.add_colored_tile("blue",c+1,r+1) else: RUR.add_colored_tile("yellow",c+1,r+1) from library import adaug,afis,vecini,life think(0);set_max_nb_steps(3500) n=10; count=100 a=[[0]*n for i in range(n)] #a=adaug(a) a[3][1]=a[3][2]=a[3][3]=1 a[5][2]=a[5][3]=a[5][4]=1 while count>0: a=life(a) afis(a) count-=1 def vecini(m,i,j): suma=-m[i][j] for r in range(-1,2): for c in range(-1,2): suma+=m[(i+r)%len(m)][(j+c)%len(m)] return suma

Related


More Related Content