validate string is valid maths

marek.rocki at wp.pl marek.rocki at wp.pl
Mon Jan 28 12:43:43 EST 2008


I decided to play with it a little bit, but take a different approach
than Steven. This seems actually one of the problems where regexp
might be a good solution.

import re

re_signednumber = r'([-+]?\d+)'
re_expression = '%s(?:([-+/*])[-+/*]*?%s)*' % (re_signednumber,
re_signednumber)
for test_case in ('3++++++8', '3++--*-9', '3++*/-9', '45--/**/+7',
'55/-**+-6**'):
	print re.match(re_expression, test_case).groups()

Now you have two problems ;-)

One question: you write "in cases where multiple symbols conflict in
meaning (as '3++--*-9' the earliest valid symbols in the sequence
should be preserved". Aren't '++' the earliest valid symbols
(operation and sign)? It seems, instead, that in your test cases the
sign is always immediately preceding the number. My regexp
accommodates for that.

Regards,
Marek



More information about the Python-list mailing list