Answer to Question #240475 in Java | JSP | JSF for Zia

Question #240475

given Java code within the link, figure out how it works. 

The code is already written. You need to fix the code so it accepts *,/ and ^ operations

need to add multiplication, addition, and power


https://drive.google.com/file/d/1NoVc1HNT9kPNJhnFg0x2V44tak9C0x4c/view?usp=sharing


Modify the code following grammar. 

<expr> -> <te rm> { <add op> <exPr>} 

<te rm> -> <factor> { mult opp> <Term> } 

<factor> -> <primary> <factor> I <primary> 

<primary> -> .(. <expr> .) ' ) <factor> I identifier I number 

<add op>  -> '+' I ' - '

<mult op>  -> ' * ' I ' / ' I %

Make sure your solution works correctly for exponents (and left associativity) for example: 

4^2 = 16 and 2^3^2 = 512 



1
Expert's answer
2021-09-22T06:28:45-0400

Here is the solution to the same problem using python with library ply. There exist a library ANTLR in java. You can use it.

import ply.lex as lex
import ply.yacc as yacc

tokens = [
    'LEFT',
    'NOT',
    'OR',
    'AND',
    'IMPL',
    'VAR',
    'RIGHT'
]

t_LEFT = r'\('
t_NOT = r'\!'
t_OR = r'\|'
t_AND = r'\&'
t_IMPL = r'[-][>]'
t_VAR = r'[A-Z0-9\'][A-Z0-9\']*'
t_RIGHT = r'\)'

t_ignore = ' \t\r'


def t_error(t):
    print("Illegal character '%s'" % t.value[0])
    t.lexer.skip(1)


lexer = lex.lex()


def p_expression(p):
    """
    expression : or
               | or IMPL expression
    """
    p[0] = p[1] if (len(p) == 2) else '(' + p[2] + ',' + p[1] + ',' + p[3] + ')'


def p_or(p):
    """
    or : and
       | or OR and
    """
    p[0] = p[1] if (len(p) == 2) else '(' + p[2] + ',' + p[1] + ',' + p[3] + ')'


def p_and(p):
    """
    and : not
        | and AND not
    """
    p[0] = p[1] if (len(p) == 2) else '(' + p[2] + ',' + p[1] + ',' + p[3] + ')'


def p_not(p):
    """
    not : NOT not
        | VAR
        | LEFT expression RIGHT
    """
    ln = len(p)
    p[0] = p[ln // 2] if (ln != 3) else '(' + p[1] + p[2] + ')'


parser = yacc.yacc()

_input = input()
print(parser.parse(_input))

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS