human
Complete this python program:
def add_with_port_collision_retry(client, unit_name, **kw):
assistant
#Here is the Python code you requested.

    """Add a container.  Try adding it repeatedly if it has ports defined and
    container startup fails with ``AddressInUse``.
    If ports in the container are defined with an external port number of ``0``
    a locally free port number will be assigned.  On each re-try attempt, these
    will be re-assigned to try to avoid the port collision.
    :param DockerClient client: The ``IDockerClient`` to use to try to add the
    container.
    :param unicode unit_name: The name of the container to add.  See the
    ``unit_name`` parameter of ``IDockerClient.add``.
    :param kw: Additional keyword arguments to pass on to
    ``IDockerClient.add``.
    :return: A ``Deferred`` which fires with a two-tuple.  The first element
    represents the container which has been added and started.  The second
    element is a ``list`` of ``PortMap`` instances describing the ports
    which were ultimately requested.
    """
    ultimate_ports = []
    def add():
        ultimate_ports[:] = tentative_ports = list(((port.set(external_port=find_free_port()[1]) if (port.external_port == 0) else port) for port in kw['ports']))
        tentative_kw = kw.copy()
        tentative_kw['ports'] = tentative_ports
        return client.add(unit_name, **tentative_kw)
    def cleanup():
        return client.remove(unit_name)
    if ('ports' in kw):
        trying = add()
        trying.addErrback(_retry_on_port_collision, add, cleanup)
        result = trying
    else:
        result = client.add(unit_name, **kw)
    result.addCallback((lambda app: (app, ultimate_ports)))
    return result