'Return an element of the preimage of `g`.
NOTE: If the codomain is an FpGroup, the inverse for equal
elements might not always be the same unless the FpGroup\'s
rewriting system is confluent. However, making a system
confluent can be time-consuming. If it\'s important, try
`self.codomain.make_confluent()` first.'

def invert(self, g):

    if isinstance(self.codomain, FpGroup):
        g = self.codomain.reduce(g)
    if (self._inverses is None):
        self._inverses = self._invs()
    image = self.image()
    w = self.domain.identity
    if isinstance(self.codomain, PermutationGroup):
        gens = image.generator_product(g)[::(-1)]
    else:
        gens = g
    for i in range(len(gens)):
        s = gens[i]
        if s.is_identity:
            continue
        if (s in self._inverses):
            w = (w * self._inverses[s])
        else:
            w = (w * (self._inverses[(s ** (-1))] ** (-1)))
    return w
