Fix issue causing exponential explosion

There was a generator expression there which caused exponential explosion with growing number of nested groups. I rewrote that part to avoid it.