Skip to content
GitLab
Projects
Groups
Snippets
Help
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Open sidebar
Juan Manuel Perez
ply-ejemplos
Commits
537b283c
Commit
537b283c
authored
8 years ago
by
Juan Manuel Perez
Browse files
Options
Download
Email Patches
Plain Diff
Agrego paréntesis y menos
parent
97a22deb
Changes
3
Hide whitespace changes
Inline
Side-by-side
Showing
3 changed files
with
23 additions
and
0 deletions
+23
-0
examples/calculator_with_precedence/lexer.py
examples/calculator_with_precedence/lexer.py
+5
-0
examples/calculator_with_precedence/parser.py
examples/calculator_with_precedence/parser.py
+11
-0
examples/calculator_with_precedence/test.py
examples/calculator_with_precedence/test.py
+7
-0
No files found.
examples/calculator_with_precedence/lexer.py
View file @
537b283c
...
...
@@ -24,11 +24,16 @@ tokens = (
'PLUS'
,
'TIMES'
,
'MINUS'
,
'LEFT_PAR'
,
'RIGHT_PAR'
,
)
t_PLUS
=
r
'\+'
t_MINUS
=
r
'-'
t_TIMES
=
r
'\*'
t_LEFT_PAR
=
r
'\('
t_RIGHT_PAR
=
r
'\)'
"""Esta variable especial ignora estos caracteres"""
t_ignore
=
"
\t
"
...
...
This diff is collapsed.
Click to expand it.
examples/calculator_with_precedence/parser.py
View file @
537b283c
...
...
@@ -5,8 +5,10 @@ from lexer import tokens
precedence
=
(
(
'left'
,
'PLUS'
,
'MINUS'
),
(
'left'
,
'TIMES'
),
(
'right'
,
'UMINUS'
)
)
def
p_expression_plus
(
p
):
'expression : expression PLUS expression'
p
[
0
]
=
p
[
1
]
+
p
[
3
]
...
...
@@ -24,11 +26,20 @@ def p_expression_term(p):
'expression : NUMBER'
p
[
0
]
=
p
[
1
]
def
p_expression_parenthesis
(
p
):
'expression : LEFT_PAR expression RIGHT_PAR'
p
[
0
]
=
p
[
2
]
def
p_minus_expression
(
p
):
'expression : MINUS expression %prec UMINUS'
p
[
0
]
=
-
p
[
2
]
def
p_error
(
p
):
print
(
"Hubo un error en el parseo."
)
parser
.
restart
()
# Build the parser
parser
=
yacc
.
yacc
(
debug
=
True
)
...
...
This diff is collapsed.
Click to expand it.
examples/calculator_with_precedence/test.py
View file @
537b283c
...
...
@@ -20,5 +20,12 @@ class ParserTest(unittest.TestCase):
def
test_suma_y_multiplica
(
self
):
self
.
assertEqual
(
parse
(
"2 + 4 * 3"
),
14
)
def
test_resuelve_parentesis
(
self
):
self
.
assertEqual
(
parse
(
"(2 + 3) * 4"
),
20
)
def
test_resuelve_negacion
(
self
):
self
.
assertEqual
(
parse
(
"-2"
),
-
2
)
if
__name__
==
'__main__'
:
unittest
.
main
()
This diff is collapsed.
Click to expand it.
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment