You can cut out the wasted work by changing the following:
if i=='a':
par+=1
if i=='b':
par-=1
to
oldpar = par
if i=='a':
par+=1
if i=='b':
par-=1
# there are n-h-1 characters left to place
# and we need to place at least abs(par) characters to reach par=0
if abs(par)>n-h-1:
par = oldpar
continue