"""
Some small tools needed to manipulate lists of rational numbers

AUTHORS:

- Serge Torres: first operations set (2013-04) 
"""

def denominators(rationalList = None):
    """
    Compute the list of the denominators of a rational numbers list.
    """
    # No argument.
    if rationalList is None:
        raise TypeError('numerators takes a list of rationals.')
    try:
        listLength = len(rationalList)
    except Exception:
        print "denominators:", rationalList, \
                "does not understand the len() function."
        return([])
    if listLength == 0:
        return([])
    if listLength == 1:
        try:
            return([QQ(rationalList[0]).denominator()])
        except Exception:
            print "denominators:", rationalList[0], \
                    "has no \"denominator()\" member." 
            return([])
    denominatorsList = []    
    for i in xrange(listLength):
        try:
            denominatorsList.append(QQ(rationalList[i]).denominator())
        except Exception:
            print "denominators:", rationalList[i], \
                    "has no \"denominator()\" member." 
            return([])
    return(denominatorsList)

def lcmm(rationalList = None):
    """ 
    Compute the lcm of an sequence (list, tuple) of rational numbers.
    """
    # No argument.
    if rationalList is None:
        raise TypeError('lcmm takes a list of rationals')
    # Try the len function.
    try:
        listLength = len(rationalList)
    except Exception:
        print "lcmm:", rationalList, "does not understand the len() function."
        return(0)
    # An empty list: return 0
    if listLength == 0:
        return(0)
    # Only one element, return it, wahtever it is.
    if listLength == 1:
        return(rationalList[0])
    try:
        return(reduce(lcm, rationalList))
    except Exception:
        print "Exception raised in lcmm!"
        return(0)
    
def numerators(rationalList = None):
    """
    Compute the list of the numerators of a rational numbers list.
    """
    # No argument.
    if rationalList is None:
        raise TypeError('numerators takes a list of rationals.')
    try:
        listLength = len(rationalList)
    except Exception:
        print "numerators:", rationalList, \
                "does not understand the len() function."
        return([])
    if listLength == 0:
        return([])
    if listLength == 1:
        try:
            return(QQ(rationalList[0]).numerator())
        except Exception:
            print "denominators:", rationalList[0], \
                    "has no \"numerator()\" member." 
            return([])
    numeratorsList = []    
    for i in xrange(listLength):
        try:
            numeratorsList.append(QQ(rationalList[i]).numerator())
        except Exception:
            print "numerators:", rationalList[i], \
                    "has no \"numerator()\" member." 
            return([])
    return(numeratorsList)