Nested conditional transformation
<p>I am trying to write a small parser that converts nested conditional statements into one-liners conditionals. A basic example would be:</p>

<pre><code>if age &gt; 15:
    if size == 3:
        test = 1
    if size == 4:
        test = 2
</code></pre>

<p><strong>translates to:</strong></p>

<pre><code>'if age &gt; 15 and size == 3: test=1'
'if age &gt; 15 and size == 4: test=2'
</code></pre>

<p>I first tried using the python <code>ast</code> module but traversing a tree is probable not a good idea in this case. I am thinking that it's perhaps a good idea to use regular expressions. I am trying to get some help about a strategy to solve this problem.</p>

<p>Try using a stack:
(This program doesn't do any error checking, it assumes you code in the same way you did above, and tabs must be used, not 4 spaces)</p>

<pre><code>mystack=[]
toprint=[]
ins=input('Next line: ')
while ins!='':
    level=0
    while ins[0]=='\t':
        ins=ins[1:]
        level+=1
    if ins[0:2]=='if':
        if len(mystack)==level:
            mystack.append(ins[3:-1])
        else:
            mystack=mystack[:level]
            mystack.append(ins[3:-1])
    else:
        if level!=len(mystack):
            mystack=mystack[:level]
        toprint.append('if ')
        for i in mystack:
            toprint[-1]+=i
            toprint[-1]+=' and '
        toprint[-1]=toprint[-1][:-5]+': '
        toprint[-1]+=ins
    ins=input('Next line: ')
print()
for i in toprint:
    print(i)
</code></pre>

python