0

My task is to code some functions to evaluate postfix, prefix and infix expressions. This is fine and dandy, and I've finished that portion of the task, however my problem arises when I take in the expression. If the user inputs a string lead by 'V', I have to assign the integers that come after 'V' to as many variables as needed. To try and be more clear, if the input was 'V 1 2 4 9', I would have to assign 1 to the letter A, 2 to the letter B, 4 to the letter C, and 9 to the letter D. I can do this if I assign each, variable by variable. But that is a long and arduous process, and I'm sure there's a better way to do it. The reason I need to assign the integer values to variables is because when the user wants to evaluate an expression, it has to be in the form '-+AB*CF', for example, if it was a prefix notation expression. Of course the form changes if the users wants infix or postfix, but the values to be evaluated are still in alphabet form, much like mathematics I guess.

My apologies if this question in unclear. Obviously this is homework, however I don't need code or people to do it for me, just some clarification about the best method would more than suffice. Thanks all.

1
  • Why the '..'? Do you always feel the need to belittle others? A list only allows me to refer to the values by index. AKA you're wrong. To everyone else, thanks for your time and answers. Commented Oct 3, 2012 at 20:37

1 Answer 1

4

Store the values in a dictionary instead:

import string

keys = string.ascii_uppercase
values = # make list of the values

variables = {keys[i]: val for i, val in enumerate(values)}

Now you can address the values in V 1 3 4 as variables['A'], variables['B'], etc.

Sign up to request clarification or add additional context in comments.

1 Comment

+1. Whenever you think "I need to assign to an open-ended, dynamically-determined set of variables", the answer is almost always "no, you need to use a dictionary". (In fact, even when you do really need separate variables, the answer is still to use a dictionary, it's just that globals() is the dictionary…)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.