validate string is valid maths

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Jan 28 13:30:34 EST 2008


impor tOn 28 ene, 14:31, Matthew_WAR... at bnpparibas.com wrote:

> What would be the 'sensible' way of transforming the string, for example
> changing '3++++++8' into 3+8
> or '3++--*-9' into '3+-9' such that  eval(string) will always return a
> number?

'3++++++8' is already a valid expresion, like '3++---9'

> in cases where multiple symbols conflict in meaning (as '3++--*-9' the
> earliest valid symbols in the sequence should be preserved
>
> so for example,
>
> '3++*/-9'         =     3+-9
> '45--/**/+7'      =     45-+7
> '55/-**+-6**'     =     55/-6

Why not 3++-9, 45--+7? Does it have to be two operators? Why not 3++9
instead? they're the two earliest valid symbols. Can't repeat yourself
then? (I'm trying to understand the rules...)

This approach uses regular expressions. It doesn't follow all your
rules, and tries to get the longest valid expression:

import re

def repl_middle(match):
  g = match.group()
  if g[0] in '*/':
    g0 = g[0]
    g = g[1:]
  else: g0 = ''
  return g0 + g.replace('*','').replace('/','')

def repl_start(match):
  g = match.group()
  return g.replace('*','').replace('/','')

def dropinvalid(s):
  s = re.sub(r'(?<=\d)[+*/-]+(?=\d)', repl_middle, s)
  s = re.sub(r'^[+*/-]+', repl_start, s)
  s = re.sub(r'[+*/-]+$', '', s)
  return s

cases = [
  ('3++++++8', '3+8'),
  ('3++--*-9', '3+-9'),
  ('3++*/-9', '3+-9'),
  ('45--/**/+70', '45-+70'),
  ('55/-**+-6**', '55/-6'),
  ('55/**6**', '55/6'),
  ]

for expr, matthew in cases:
  print expr, dropinvalid(expr), matthew

> I've tried testing, but I'm not certain wether repeated iterations over a
> dict return different sequences of key,value pairs or wether I'll be
> getting the same (but arbitrary) sequence each time even though they are
> unordered, etc

If the dictionary hasn't changed, you'll get the same sequence each
time (see note (3) in http://docs.python.org/lib/typesmapping.html )

> So for testing, what could I do to guarantee the next iteration over the
> dict will give keys/pairs in a different sequence to last time?

items = dict.items()
random.shuffle(items)
for key,value in items:
  ...

(Ok, no guarantee, there is only a certain probability that it will be
different each time...)

--
Gabriel Genellina



More information about the Python-list mailing list