How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument?

Peter J. Holzer hjp-python at hjp.at
Sun Jan 22 10:45:56 EST 2023


On 2023-01-22 00:30:07 -0500, Thomas Passin wrote:
> On 1/21/2023 10:11 PM, Jach Feng wrote:
> > e:\Works\Python>py infix2postfix.py "-4^2+5.3*abs(-2-1)/2"
> > usage: infix2postfix.py [-h] [infix]
> > infix2postfix.py: error: unrecognized arguments: -4^2+5.3*abs(-2-1)/2
[...]
> > > > > import argparse
> > > > > parser = argparse.ArgumentParser(description='Convert infix notation to postfix')
> > > > > parser.parse_args("-4^2+5.3*abs(-2-1)/2")
> > usage: [-h]
> > : error: unrecognized arguments: - 4 ^ 2 + 5 . 3 * a b s ( - 2 - 1 ) / 2
> > 
> > Just can't figure out where is wrong!?
> 
> It just doesn't work like that.
[...]
> If you substitute your expression, the result is
> 
> abs1-2-*2/3.5+2^4-
> 
> This may or may not be correct. I'm not sure but I think it's as intended
> except for reversing "3.5".  But maybe that's right, I'm not too sure.

It depends on the intended meaning. But I'm pretty sure that "5.3" is
supposed to be a floating point number and not (5 operatordot 3), so
it's wrong to split that apart. (Also it seems that the code treats
digits as operators, not operands?)

Also "abs(...)" is almost certainly intended to be a function call, so
it should be invoked after its parameters.

I think the correct output (using newlines as delimiters) would be:

-4
2
^
5.3
-2
1
-
abs
*
2
/
+

> Notice that this file is in its first release, version 0.0.1 - the metadata
> that says it's 'Development Status :: 5 - Production/Stable' seems to be
> bogus.  So it may very well be buggy.

It is at least too incomplete to be useful. It handles only single
letters as operands and treats everything else (except parentheses) as an operator, handling
only +, -, *, / and ^ correctly (actually, ^ is typically right
associative, so that's arguably wrong, too).

        hp

-- 
   _  | Peter J. Holzer    | Story must make more sense than reality.
|_|_) |                    |
| |   | hjp at hjp.at         |    -- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |       challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://mail.python.org/pipermail/python-list/attachments/20230122/8c0cc934/attachment.sig>


More information about the Python-list mailing list