'Create loops in loops by own commands using recursion
I'm struggling a little with recursion. I have a .txt file with commands like this (< are comments):
< HEADER 1
< HEADER 2
DO STH HERE
LOOP lblA 2
DO STH
DO STH ELSE
END lblA
DO STH HERE
If there is a "LOOP lbl x" command, the tool have to repeat every command between this line and the "END lbl" x times. The output is saved temporarily before sending each line via TCP to a server:
< HEADER 1
< HEADER 2
DO STH HERE
< LOOP lblA 1 of 2
DO STH
DO STH ELSE
< LOOP lblA 2 of 2
DO STH
DO STH ELSE
< END LOOP lblA
DO STH HERE
That is easy. But now I want loops in loops like
< HEADER 1
< HEADER 2
DO STH HERE
LOOP lblA 2
DO STH
LOOP lblB 3
print("nope")
END lblB 3
DO STH ELSE
END lblA
DO STH HERE
The output must be
< HEADER 1
< HEADER 2
DO STH HERE
< LOOP lblA 1 of 2
DO STH
< LOOP lblB 1 of 3
print("nope")
< LOOP lblB 2 of 3
print("nope")
< LOOP lblB 3 of 3
print("nope")
< END LOOP lblB
DO STH ELSE
< LOOP lblA 2 of 2
DO STH
< LOOP lblB 1 of 3
print("nope")
< LOOP lblB 2 of 3
print("nope")
< LOOP lblB 3 of 3
print("nope")
< END LOOP lblB
DO STH ELSE
< END LOOP lblA
DO STH HERE
This is my code so far:
def comTester(self, testfile):
rawtext = Path(testfile).read_text()
txt = rawtext.split('\n')
for i in range (0, len(txt), 1):
loopArray = []
loopLineA = 0
loopLineB = 0
loopLbl = ''
loops = 0
j = 0
k = 1
if txt[i].startswith('<') == True:
testcommands.append(txt[i])
elif txt[i].startswith('LOOP') == True:
loopArray = txt[i].split(' ')
loopLineA = i + 1
loopLbl = loopArray[1]
loops = int(loopArray[2])
for j in range (loopLineA, len(txt), 1):
if txt[j].startswith('END ' + loopLbl) == True:
loopLineB = j
while k < loops:
l = 0
testcommands.append('< LOOP "' + loopLbl + str(k) + ' of ' + str(loops))
for l in range(loopLineA, loopLineB, 1):
testcommands.append(txt[l])
k = k + 1
testcommands.append('# END LOOP ' + loopLbl)
elif txt[i].startswith('END') == True:
continue
else:
testcommands.append(txt[i])
return
I need to start the "elif txt[i].startswith('LOOP') == True:" block recursive, but I don't know how. I have to create a new function and calling it itself. But with this given structure... no clue.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
