CONTEXT
I’m creating a calculator. I’m at the point where I want my calculator to do BODMAS (start calculations with the inner most bracket).
The user enters an expression, in this example it is: expression = (1+(1+1))
I have a function that splits up this function into ‘terms’ and saves the result in expression_list
.
expression_list = ['(', '1', '+', '(', '1', '+', '1', ')', ')']
I have a function that locates the indexes of all brackets in expression_list
and saves it in b_pairs
.
For the above expression the intended output for b_pairs
should be of the form:
b_pairs = [{'ob_1', 0}, {'ob_2', 3}, {'cb_1', 7}, {'cb_2', 8}]
Here is the function:
for term in expression_list:
if term == '(':
b_pairs.append({"ob_"+str(ob),index})
ob+=1
elif term == ')':
b_pairs.append({"cb_"+str(cb),index})
cb+=1
index+=1
Where 'ob'
represents an open bracket and 'oc'
represents a close bracket.
PROBLEM
The function works because it identifies the location of the open/close brackets and their respective locations correctly, but it mixes up the format. Here is the actual result:
b_pairs = [{0, 'ob_1'}, {'ob_2', 3}, {'cb_1', 7}, {8, 'cb_2'}]
Notice the order in (a) b_pairs[0]
and (b) b_pairs[1]
. I want the key to be the name of the bracket and the value to be the location of the bracket in expression_array, e.g. {‘ob_1,0}, not the other way around.
I’ve coded such that the format should be as in b_pairs[1]
, but for some strange reason it’s not always so.
I’ve debugged the code but I can’t see any logical reason for this happening. I know that a dictionary with multiple key/value pairs will not always be printed in order, but in this example the dictionary variables in expression_list
are single key/value and I code such that the key should be the name of the bracket, not the index of the bracket in expression_list
. Please help.
>Solution :
You’re creating Sets, not Dicts. See below:
a = {1, 2}
This is a set containing 1 and 2.
b = {1: 2}
This is a dict where 2 the value stored for the key 1.