Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

How to specify a pyparsing expression that has two parts, the length of each may varies but their sum is fixed?

$
0
0

I need to specify an expression that is defined as ambn, such that:

  • m+n = t; t is fixed
  • 0 <= m<= t - 1
  • 1 <= n<= t

Here's how the current code looks like, simplified:

from pyparsing import Char, Combinedef ab(t):  first = Char('a')[0, t - 1]  second = Char('b')[1, t]  expression = first + second  expression.add_condition(    lambda result: len(result) == t,    message = f'Total length must be {t}'  )  return Combine(expression)

The expression, however, consumes all it could find and calls the condition function on that result without backtracking. For example:

grammar = (ab(4) | Char('b'))[1, ...].set_name('grammar')grammar.parse_string('abbbb', parse_all = True)
ParseException: Expected grammar, found 'abbbb'  (at char 0), (line:1, col:1)

The result I want is ['abbb', 'b'], which would be achieved if the expression in question was specified as:

expression = Or([  Char('a')[m] + Char('b')[t - m]  for m in range(0, t)])

...but that looks unnecessarily verbose.

Is there a better way?


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>