import math


def approximate_sum(*pairs):
    """
    Sum estimates from the U.S. Census Bureau and approximate the combined margin of error.

    Follows the U.S. Census Bureau's `official guidelines`_ for how to calculate a new margin of error
    when totaling multiple values. Useful for aggregating census categories and geographies.

    Args:
        *pairs (list): An open-ended set of paired lists, each expected to provide an
            estimate followed by its margin of error.

    Returns:
        A two-item tuple with the summed total followed by the approximated margin of error.

        (19866960, 5437.757350231803)

    Examples:
        Combining the under-five male population with under-five female population
        to calculate a grand total of children under five.

        >>> males_under_5, males_under_5_moe = 10154024, 3778
        >>> females_under_5, females_under_5_moe = 9712936, 3911
        >>> approximate_sum(
            (males_under_5, males_under_5_moe),
            (females_under_5, females_under_5_moe)
        )
        19866960, 5437.757350231803

    .. _official guidelines:
        https://www.documentcloud.org/documents/6162551-20180418-MOE.html
    """
    # According to the Census Bureau, when approximating a sum use only the largest zero estimate margin of error, once
    # https://www.documentcloud.org/documents/6162551-20180418-MOE.html#document/p52
    zeros = [p for p in pairs if p[0] == 0]
    # So if there are zeros...
    if len(zeros) > 1:
        # ... weed them out
        max_zero_margin = max([p[1] for p in zeros])
        not_zero_margins = [p[1] for p in pairs if p[0] != 0]
        margins = [max_zero_margin] + not_zero_margins
    # If not, just keep all the input margins
    else:
        margins = [p[1] for p in pairs]

    # Calculate the margin using the bureau's official formula
    margin_of_error = math.sqrt(sum([m**2 for m in margins]))

    # Calculate the total
    total = sum([p[0] for p in pairs])

    # Return the results
    return total, margin_of_error