def check_ip_in_lists(ip, db_connection, penalties):
    """
    Does an optimized ip lookup with the db_connection. Applies only the maximum penalty.

    Args:
        ip (str): ip string
        db_connection (DBconnector obj)
        penalties (dict): Contains tor_penalty, vpn_penalty, blacklist_penalty keys with integer values

    Returns:
        :int: penalty_added
    """

    penalties = {'tor': int(penalties['tor_penalty']), 'vpn': int(penalties['vpn_penalty']), 'blacklist': int(penalties['ip_blacklist_penalty'])}

    penalties = sorted(penalties.items(), key=lambda x: x[1])
    # sort by penalty value to check in that order and perform early stopping

    penalty_added = 0

    for penalty_type, penalty_value in penalties:

        if penalty_value == 0:
            continue

        if penalty_type == 'tor':
            if db_connection.set_exists('tor_ips', ip):
                penalty_added = penalty_value

        elif penalty_type == 'blacklist':
            if db_connection.set_exists('blacklist_ips', ip):
                penalty_added = penalty_value
            elif db_connection.set_exists('blacklist_ips', '.'.join(ip.split('.')[:3])):
                penalty_added = penalty_value
            elif db_connection.set_exists('blacklist_ips', '.'.join(ip.split('.')[:2])):
                penalty_added = penalty_value

        elif penalty_type == 'vpn':
            if db_connection.set_exists('vpn_ips', ip):
                penalty_added = penalty_value
            elif db_connection.set_exists('vpn_ips', '.'.join(ip.split('.')[:3])):
                penalty_added = penalty_value
            elif db_connection.set_exists('vpn_ips', '.'.join(ip.split('.')[:2])):
                penalty_added = penalty_value

        if penalty_added > 0:
            break

    return penalty_added