Skip to content

Commit

Permalink
fix some bugs of infix_to_postfix
Browse files Browse the repository at this point in the history
  • Loading branch information
mahdihaghverdi committed Dec 12, 2022
1 parent c3dc398 commit 5edcc32
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
18 changes: 11 additions & 7 deletions plumacalc/parser.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import ast
from shlex import shlex
from typing import NoReturn
from typing import Any, List, NoReturn

import black

Expand Down Expand Up @@ -47,7 +47,7 @@ def _concat_dotted_numbers(expression: str) -> list[str]:
return stack


def _make_num(postfix):
def _make_num(postfix: list[str]) -> list[str | int | float]:
"""Make numbers int | float and return the postfix list"""
new_list = []
num_or_op: str | int | float
Expand All @@ -63,21 +63,25 @@ def _make_num(postfix):
return new_list


def _concat_unary_minus(postfix):
def _concat_unary_minus(postfix: list[str]) -> list[str | int | float]:
"""Apply unary minus to numbers
e.g.
make all [..., NUMBER, '-', ...] to this: [..., -NUMBER, ...]
"""
postfix = _make_num(postfix) # type: ignore
stack = []
stack: list[int | float | str] = []
for item in postfix:
if isinstance(item, int):
if isinstance(item, (int, float)):
stack.append(item)
elif item == "-":
if isinstance(stack[-1], int):
if isinstance(stack[-1], (int, float)):
last = stack.pop()
stack.append(int("-" + str(last)))
if not stack:
stack.append(_make_num(["-" + str(last)])[0])
else:
stack.append(last)
stack.append(item)
else:
stack.append(item)
else:
Expand Down
15 changes: 15 additions & 0 deletions tests/test_parser/test_infix_to_postfix.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,18 @@ def test_infix_to_postfix():
"/",
"-",
]
assert infix_to_postfix("3 * 6 - 9 + 2 ** 2 / 8 * 7") == [
3,
6,
"*",
9,
"-",
2,
2,
"^",
8,
"/",
7,
"*",
"+",
]

0 comments on commit 5edcc32

Please sign in to comment.