Increasing the efficiency of this subgroup algorithm
I'm currently writing a library on python, and now I'm a little bit stuck on how to find a subgroup generated by a subset $S$ of the group $G$. In the case $S = \{a\}\subseteq G$ the problem's easy: just multiply $a$ by itself until you reach the module $e$, but the case $a,b$ I don't know how to handle the infinite combinations of $a, b, a^{-1}$ and $b^{-1}$. I could easily start considering them (and appending them to the subgroup), but when do I know when to stop? Any ideas?
The following algorithm will produce $H=\langle S\rangle$, provided $S$ is a subset of a finite group $G$.
- Push $1$ to a queue and let $H=\emptyset$.
- If the queue is empty, terminate
- Pop $x$ from the queue. If $x\in H$, go back to step 2
- Set $H=H\cup \{x\}$
- For each $s\in S$, push $x\cdot s$ to the queue
- Go back to step 2