Skip to content
Advertisement

Dictionary making weird key:value pairs

I want to make a simple calculator, where you just type in something like “2+2*2” and it calculates the answer. First step was to find, and cut out the individual numbers, which I tried doing below.

JavaScript

But when I input:

JavaScript

I don’t get the expected output of:

JavaScript

But rather:

JavaScript

I’m still very new to python, so please also tell me if there’s anything I can do better. Thanks.

Advertisement

Answer

There are a lot of small changes to get the result you added to your question, so I will go through each one.

I’ve created an empty dictionary to store your sub equation in: subequation = {}

Your original for loop of for symbols in equation: would overwrite your list of symbols, I believe what you are trying to do is go through each of the symbols and check if they are in the equation, which you can do with a for loop and then an if statement as below:

JavaScript

As mentioned by Jhanzaib Humayun in the comments, you’re overwriting your subequation in each loop, rather than adding, so they have provided the code to add to a dict as below:

JavaScript

But equation[0:equation.find(symbols)] will always start from the begining of the equation and return everything up to (and not including the symbol), so would return:

JavaScript

Which is not what you want, so I changed this to:

JavaScript

Which will now only include the number and symbol, but as Titouan L commented, this won’t work for numbers with multiple digits, so I have come up with a last_symbol variable which will work backwards from the symbol it’s looking at to find the last one, and keep anything in between. I have done this as below:

JavaScript

This works backwards from the symbol to find the indexes of all previous symbols ([i for i in range(equation.find(symbol)-1, 0, -1) if equation[i] in symbols]) and finds the maximum of this (i.e. the most recent). I added [-1] to this list as for the first symbol, there will not be a previous symbol, and when adding to the dictionary, I have done equation[last_symbol+1:equation.find(symbol)+1], so for the first symbol, this will go from 0:equation.find(symbol)+1

The full code is:

JavaScript

Which returns the below as desired:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement