# DMC Prac

```python

**********************************Practical 1**********************************
Aim: Write a program to validate decision making statement (validation of if else)
CODE 1:
import re
str1 = input("enter: ")
if re.match("if\(.*\){.*}else{.*}",str1):
    print("correct")
else:
    print("not correct")

OUTPUT: enter: if(x>3){y=1;}else{y=0;}
        ->correct
        
         enter: if(x>3){y=1;}else(x<2){y=0;}
        ->not correct
 
CODE 2:
def validate_if_else_syntax(code):
    stack=[]
    for char in code:
        if char=='{':
            stack.append('{')
        elif char=='}':
            if stack:
                stack.pop()
            else:
                print("Error: Unmatched braces")
                return # Terminate the function if an error is detected
    if not stack:
        print("Syntax validation successful")
    else:
        print("Error: Unmatched braces")

def check_else_syntax(code):
    if 'else' in code and 'if' not in code:
        print("Error:'else' without matching 'if'")
    else:
        print("Syntax validation successful")

code_example_1 = """
if condition:
    statement1
else:
    statement2
"""

validate_if_else_syntax(code_example_1)
check_else_syntax(code_example_1)
OUTPUT for example 1:
->Syntax validation successful
->Syntax validation successful 

code_example_2 = """
if condition:
    statement1
else:
    statement2
"""

validate_if_else_syntax(code_example_2 + "}")
check_else_syntax(code_example_2)

OUTPUT for example 2:
->Error: Unmatched braces
->Syntax validation successful 

code_example_3 = """
else:
    statement
"""

validate_if_else_syntax(code_example_3)
check_else_syntax(code_example_3)

OUTPUT for example 3:
->Error:'else' without matching 'if'
->Syntax validation successful

********************************Practical 2************************************
Aim: Write a program to validate looping statement (validation of for, while, do...while)
CODE:
import re
str1 = input("enter: ")
if (re.match("for\(.*;.*;.*\){.*}", str1)):
    print("correct")
else:
    print("not correct")
OUTPUT:
->enter:Invoker
->not correct 
->enter: for(i=0;i>3;i++){x++}
->correct
->enter: for(i=0;i>3;i++)
->not correct

CODE:
import re
str1 = input("enter: ")
if (re.match("while\(.*\){.*\}", str1)):
    print("correct")
else:
    print("not correct")
OUTPUT:
->enter: while(x<4) {print('1')}
->correct
->enter: while(x=0){y)
->not correct 

CODE:
import re
str1 = input("enter: ")
if (re.match("do\{.*\}while\(.*\);", str1)):
    print("correct")
else:
    print("not correct")
OUTPUT:
->enter: do {x=y} while(z);
->correct
->enter: do {} while;
->not correct

*********************************Practical 4***********************************
Aim: Write a program to implement 3- Address Code
CODE:
l=[] #list will be used as a stack to store operands and intermediate results.

def push(a):
    l.append(a)  #(takes an argument a and appends it to the list l, adding it to the top of the stack.)

def pop():  #Removes and returns the top elements of the stack.
    p=l[-1]
    del l[-1]
    return p

def is_empty():  #Checks ifn the stack is empty.
    if len(l)==0:
        return True
    else:
        return False

def three_add_code(expr):  #Takes a postfix expression as input, processes it, and prints the corresponding three-address code.
    ts=[]
    op=[]
    arg1=[]
    arg2=[]
    i=0
    for t1 in expr:  #Iterates through each character (t1) in the input postfix expression(expr)
        if (t1 in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"):  #Checks if t1 is an uppercase letter(an operand). If true, calls the push function to add it to the stack.
            push(t1)
        else:
            arg2.append(pop())
            arg1.append(pop())
            op.append(t1)
            s="t"+str(i)
            push(s)
            ts.append(s)  #Pushes the temporary variable onto the stack and appends it to the ts list.
            i=i+1
    for a in range(0,i):  #Iterates through the range of temporary variables(t0 to t{i-1}).
        print(ts[a],"=", arg1[a]," ", op[a]," ", arg2[a])
e=input("Enter Postfix Expression:")
three_add_code(e)

OUTPUT:
->Enter Postfix Expression:IN+VO-KE*R+

*******************************Practical 5*************************************
Aim: Write a program to implement Triple.
CODE:
l=[] #list will be used as a stack to store operands and intermediate results
def push(a):
    l.append(a)#takes an argument a and appends it to the end of the list l ,adding it to the top of the stack)
def pop(): #removes and returns the top element of the stack 
    p=l[-1]
    del l[-1]
    return p
def is_empty():
    if len(l)==0:
        return True
    else:
        return False
def triple(expr):#takes a postfix expression as input,processes it and prints the corressponding three address code 
    ts=[]
    op=[]
    arg1=[]
    arg2=[]
    i=0
    for t1 in expr:#iterates through each character (t1) in the input postfix expression(expr)
        if(t1 in "ABCDEFGHIJKLMNOPQRSTUVWXTZ"):#checks if t1 is an uppercase letter(an operand) if true calls the push function to add it to the stack
            push(t1)
        else:
            arg2.append(pop())
            arg1.append(pop())
            op.append(t1)
            s="("+str(i)+")"
            push(s)
            ts.append(s)#pushes the temporary variable onto the stack and appends it to the list
            i=i+1
    print("\t\t arg1\t\t op\t\t arg2")#prints the header for a quadruple table 
    for a in range (0,i):#iterates through the range of temporary variables from (t0 to t(i-1))
        print(ts[a],"\t",arg1[a],"\t\t",op[a],"\t\t",arg2[a])#prints the quadruple table with columns representing arg1,operator,arg2 and result
e=input("Enter PostFix Expression:")
triple(e)

OUTPUT:
->Enter PostFix Expression:AB+CD*EF-

******************************Practical 6*************************************
Aim: Write a program to implement Quadruple.
CODE:
l=[] 
def push(a):
    l.append(a)
def pop():
    p=l[-1]
    del l[-1]
    return p
def is_empty():
    if len(1)==0:
        return True
    else:
        return False

def quadruple(expr):
    ts=[]
    op=[]
    arg1=[]
    arg2=[]
    i=0
 for t1 in expr:
        if(t1 in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
            push(t1)
        else:
            arg2.append(pop())
            arg1.append(pop())
            op.append(t1)
            s="t"+str(i)
            push(s)
            ts.append(s)
            i=i+1
    print("arg\t op\t arg2\t result")
    for a in range(0,i):
        print(arg1[a],"\t",op[a],"\t",arg2[a],"\t",ts[a])
e=input("enter postfix expression:")
quadruple(e)
OUTPUT:
->enter postfix expression:A+CD*+

**********************************Practical 7**********************************
Aim: Write a program to implement Infix to Postfix.
CODE:
l=[]

def push(a):
    l.append(a)

def pop():
    p=l[-1]
    del l[-1]
    return p

def is_empty():
    if len(l)==0:
        return True
    else:
        return False
def peek():
    s=l[-1]
    return s
    
def in_to_post(expr):
    prec={}
    prec["*"]=3
    prec["/"]=3
    prec["+"]=2
    prec["-"]=2
    prec["("]=1
    postfix=[]
    for t1 in expr:
        if (t1 in "ABCDEFGHIJKLMNOPQRSTUVWXYZ") or (t1 in "0123456789"):
            postfix.append(t1)
        elif t1=="(":
            push(t1)
        elif t1==")":
            top=pop()
            while top!="(":
                postfix.append(top)
                top=pop()
        else:
            while((not is_empty())and(prec[peek()]>=prec[t1])):
                postfix.append(pop())
            push(t1)
    while not is_empty():
                postfix.append(pop())
    return " ".join(postfix)

e=input("Enter infix expression:")
print(in_to_post(e))
OUTPUT:
->Enter infix expression:a+b*c-d

******************************Practical 8*************************************
Aim: Write a program to implement Postfix to Infix.
CODE:
l=[]

def push(a):
    l.append(a)

def pop():
    p=l[-1]
    del l[-1]
    return p

def is_empty():
    if len(l)==0:
        return True
    else:
        return False

def post_to_in(expr):
    postfix = []
    for t1 in expr:
        if (t1 in "ABCDEFGHIJKLMNOPQRSTUVWXYZ") or (t1 in "0123456789"):
            push(t1)
        else:
            a=pop()
            b=pop()
            s=str(b)+t1+str(a)
            push(s)
    postfix=pop()
    return postfix

e=input("Enter postfix expression: ")
print(post_to_in(e))
OUTPUT:
->Enter postfix expression:ABC/+D-

******************************Practical 10*************************************
Aim: Generation of machine code.
CODE:
expns=["T=a+b","T=T*c","T=T/d"]
for a in expns:
 print(a) 
print("*"*50)
def cd(op,x,y): 
 if op=='+':
 print("MOV REG, "+x+"\nADD REG, "+y) 
 print("MOV REG, "+x+"\nMUL REG, "+y)
 if op=='/':
 print("MOV REG, "+x+"\nDIV REG, "+y)
 print("ST T,REG") 
for i in range(0,len(expns)):
 s=expns[i].split('=') # t,a+b
 exp=s[1] #a+b
 op=exp[1] #+
 x=exp[0] #a
 y=exp[2] #b
 cd(op,x,y)
OUTPUT:

 
```
