I am having the following problem. My code works, but it seems like it can improve a lot. I am fairly new to python and can't seem to get this block any better. The logic behind it goes like this.
I have a dictionary that acts like a tree, it looks like this:
SampleTree[10000000] = ['ACC','ARRAY']
SampleTree[10010000] = ['ACC_ABO','ABO']
SampleTree[10020000] = ['ACC_CHILDLOCK','OPTION']
SampleTree[10030000] = ['ACC_RECO','ARRAY']
SampleTree[10030100] = ['ACC_RECO_ACTIVATE']
SampleTree[10030200] = ['ACC_RECO_ACTIVATE']
SampleTree[10030201] = ['ACC_RECO_ACTIVATE']
SampleTree[10030202] = ['ACC_RECO_ACTIVATE']
SampleTree[10040000] = ['ACC_ADDUSER','OPTION']
SampleTree[10050000] = ['ACC_SETTINGS','ARRAY']
Where the dict key acts like a unique key, which I use to recognize in my program. I use a for loop to iterate over the full dict like this:
KEYLIST = SampleTree.keys()
KEYLIST.sort()
for KEY in KEYLIST :
if (KEY % 1000000) == 0 :
BACKS = 0
elif (KEY % 1000000) == 10000 and (LAST % 1000000) == 0 :
BACKS = 1
elif (KEY % 10000) == 0 and (LAST % 1000000) == 10000 :
BACKS = 2
elif (KEY % 10000) == 100 and (LAST % 10000) == 0 :
BACKS = 1
elif (KEY % 10000) == 0 and (LAST % 10000) == 0 :
BACKS = 2
elif (KEY % 10000) == 0 and ((LAST % 10000) % 100) == 0 :
BACKS = 3
elif (KEY % 10000) == 0 and (LAST % 100) != 0 :
BACKS = 4
elif (KEY % 100) == 1 and ((LAST % 10000) % 100) == 0 :
BACKS = 1
elif (KEY % 100) == 0 and (LAST % 100) == 0 :
BACKS = 2
elif (KEY % 100) == 0 and (LAST % 100) != 0 :
BACKS = 3
elif (KEY % 100) != 0 and (LAST % 100) != 0 :
BACKS = 2
LAST=KEY
As you can see in the code, it uses a bunch of if elif tests to see in which branch the Key currently is. And accordingly it sets the BACKS variable how it should be. After this code there are a bunch of operation based on the KEY value and on the BACKS variable.
The BACKS variable depends on the transition of each KEY. Some examples:
from : 10 00 00 00 00 to : 10 01 00 00 00 you need to go BACK 1 time
from : 10 01 00 00 00 to : 10 01 01 00 00 you need to go BACK 1 time
from : 10 01 01 00 00 to : 10 01 02 00 00 you need to go BACK 2 times
from : 10 01 02 00 00 to : 10 02 00 00 00 you need to go BACK 3 times
So what I am trying to say is that there doesn't seem to be a particular logic behind all this. Can you please help me?
My whole problem with the code is that it is so ugly and look like it can improve a lot. But I just can't see a better way. Another big issue is expansion. If I for example add another layer to the tree (add two more zeros to the KEY), the whole logic falls apart.
BACK
is calculated, can you elaborate a bit? \$\endgroup\$