def cycles2perm(n, g):
    """
    Idempotent function for converting a list of disjoint cycles
    into a permutation.
    """
    if len(g) == 0:
        return tuple(range(n))
    elif hasattr(g[0], '__iter__'):
        perm = list(range(n))
        for cyc in g:
            for i in range(len(cyc)):
                perm[cyc[i - 1]] = cyc[i]
        return tuple(perm)
    elif set(g) == set(range(n)):
        return tuple(g)
    else:
        raise ValueError('%s is not in S_%d' % (g, n))
