# PythonAnalyze One Line Expression - Recursive Function for Nested Tokens

#### slimyslime777

##### New Coder
I'm on the verge of a looping confusion. My goal is to create a python recursive function that can analyze nested tokens (in any pattern). The function can point out the wrong token index and displays the expected rules. If there's no error, it will display the structure (dictionary type) and the calculated answer of the expression.

Sample Input: Expected Structure: Rules:
By using this list. Where: PS:
I am very inefficient in implementing algorithms for recursion. This is what I've made so far but I already reached the confusion stage of my code. Different approach or optimization of the code below would be greatly appreciated.

Code:

rules = {} rules['i'] = [] rules['ADD'] = ['i|ADD|SUB|MUL|DIV', 'i|ADD|SUB|MUL|DIV'] rules['SUB'] = ['i|ADD|SUB|MUL|DIV', 'i|ADD|SUB|MUL|DIV'] rules['MUL'] = ['i|ADD|SUB|MUL|DIV', 'i|ADD|SUB|MUL|DIV'] rules['DIV'] = ['i|ADD|SUB|MUL|DIV', 'i|ADD|SUB|MUL|DIV'] subject = ['ADD','1','1'] for_branching = {} # subject with parent-child indexes branches = {} token_index = -1 depth = -1 solved_indexes = [] success = True queue = {} for s_x in range(0, len(subject)): s = subject[s_x] s_is_int = True if s.isnumeric() else False token_symbol = 'i' if s_is_int is True else s rule_found = True if token_symbol in rules else False if rule_found is True: r = rules[s] if s_x+len(r) <= len(subject): r_x = -1 for x1 in range(s_x+1, s_x+len(r)+1): r_x += 1 s_is_int2 = True if subject[x1].isnumeric() else False token_symbol2 = 'i' if s_is_int2 is True else subject[x1] if token_symbol2 in r[r_x]: if token_symbol2 in rules: queue[x1] = rules[token_symbol] else: success = False else: success = False print('ERROR: token # '+str(x1)+' expects \''+r[r_x]+'\'') break if success is False: break else: print('the token expects '+str(len(r))+' token/s') break if success is False: break:
``````rules = {}
rules['i'] = []

for_branching = {}  # subject with parent-child indexes
branches = {}
token_index = -1
depth = -1
solved_indexes = []
success = True queue = {}

for s_x in range(0, len(subject)):
s = subject[s_x]
s_is_int = True if s.isnumeric() else False
token_symbol = 'i' if s_is_int is True else s
rule_found = True if token_symbol in rules else False
if rule_found is True:
r = rules[s]
if s_x+len(r) <= len(subject):
r_x = -1
for x1 in range(s_x+1, s_x+len(r)+1):
r_x += 1
s_is_int2 = True if subject[x1].isnumeric() else False
token_symbol2 = 'i' if s_is_int2 is True else subject[x1]
if token_symbol2 in r[r_x]:
if token_symbol2 in rules:
queue[x1] = rules[token_symbol]
else:
success = False
else:
success = False
print('ERROR: token # '+str(x1)+' expects \''+r[r_x]+'\'')
break

if success is False:
break
else:
print('the token expects '+str(len(r))+' token/s')
break

if success is False:
break``````