From ff26a55e7855f24f065714253fdc5de1c0df9eab Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Wed, 28 Oct 2020 11:44:23 +0000 Subject: TST: f2py: Add a doctest for `getlincoef` --- numpy/f2py/crackfortran.py | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) (limited to 'numpy/f2py') diff --git a/numpy/f2py/crackfortran.py b/numpy/f2py/crackfortran.py index 3d2f97a56..1fe2ca037 100755 --- a/numpy/f2py/crackfortran.py +++ b/numpy/f2py/crackfortran.py @@ -2103,8 +2103,9 @@ def buildimplicitrules(block): def myeval(e, g=None, l=None): + """ Like `eval` but returns only integers and floats """ r = eval(e, g, l) - if type(r) in [type(0), type(0.0)]: + if type(r) in [int, float]: return r raise ValueError('r=%r' % (r)) @@ -2112,6 +2113,26 @@ getlincoef_re_1 = re.compile(r'\A\b\w+\b\Z', re.I) def getlincoef(e, xset): # e = a*x+b ; x in xset + """ + Obtain ``a`` and ``b`` when ``e == "a*x+b"``, where ``x`` is a symbol in + xset. + + >>> getlincoef('2*x + 1', {'x'}) + (2, 1, 'x') + >>> getlincoef('3*x + x*2 + 2 + 1', {'x'}) + (5, 3, 'x') + >>> getlincoef('0', {'x'}) + (0, 0, None) + >>> getlincoef('0*x', {'x'}) + (0, 0, 'x') + >>> getlincoef('x*x', {'x'}) + (None, None, None) + + This can be tricked by sufficiently complex expressions + + >>> getlincoef('(x - 0.5)*(x - 1.5)*(x - 1)*x + 2*x + 3', {'x'}) + (2.0, 3.0, 'x') + """ try: c = int(myeval(e, {}, {})) return 0, c, None -- cgit v1.2.1