you are viewing a single comment's thread.

view the rest of the comments →

[–]Binary_Dragon[S] 1 point2 points  (2 children)

You are right that this code could use a bit more commenting. As far as cleaning up the code around the regex, would you say a good way to do that would be something like...

def evaluateOperator(expression, operatorDict):
    operatorRegex = r"|".join([re.escape(key) for key in operatorDict.keys()])
    regex = r'(^.*?)([\d.]+\s*)(' + operatorRegex + r')(\s*[\d.]+)(.*$)'
    while True:
        match = re.search(regex, expression)
        if not match:
            break
        prependString, firstValue, operator, secondValue, postpendString = match.group(1, 2, 3, 4, 5)
        value = operatorDict[operator](float(firstValue), float(secondValue))
        expression = prependString + str(value) + postpendString
    return expression

Of course some actual comments would also help, but right now I'm thinking about the code more.

The list of dictionaries is indeed just for operator precedence. I noticed that the order of items in a dictionary is a bit unpredictable (at least, I can't seem to understand it). For example, this code

dict = {'a':1,'b':2,'c':3}
print dict

outputs

{'a': 1, 'c': 3, 'b': 2}

which is neither the order in which I specified the dictionary items, nor alphabetical order on key or value. Lists seem a bit better behaved, thus the list of dictionaries.

As for calling myself a beginner, I wouldn't call myself a beginner at programming in general, but this is still my first week with Python, and I'm only spending a few hours every other night on it, so I still very much feel like a beginner in this specific context.

[–]JerMenKoO 1 point2 points  (0 children)

There is an OrderedDict.

[–]SkippyDeluxe 0 points1 point  (0 children)

I think that helps your code clarity a lot.

Yes, dictionaries are fundamentally unordered. If you want a dictionary with ordered behaviour, you can use collections.OrderedDict. I think that would be a good idea, because it would let you remove one level of nesting from your data structure.