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$.

  1. Push $1$ to a queue and let $H=\emptyset$.
  2. If the queue is empty, terminate
  3. Pop $x$ from the queue. If $x\in H$, go back to step 2
  4. Set $H=H\cup \{x\}$
  5. For each $s\in S$, push $x\cdot s$ to the queue
  6. Go back to step 2