In this HackerRank Validating Email Addresses With a Filter problem solution You are given an integer N followed by N email addresses. Your task is to print a list containing only valid email addresses in lexicographical order.

HackerRank Validating Email Addresses With a Filter in python problem solution

HackerRank Validating Email Addresses With a Filter in python problem solution

import re
def cmp_to_key(mycmp):
    'Convert a cmp= function into a key= function'
    class K(object):
        def __init__(self, obj, *args):
            self.obj = obj
        def __lt__(self, other):
            return mycmp(self.obj, other.obj) < 0
        def __gt__(self, other):
            return mycmp(self.obj, other.obj) > 0
        def __eq__(self, other):
            return mycmp(self.obj, other.obj) == 0
        def __le__(self, other):
            return mycmp(self.obj, other.obj) <= 0
        def __ge__(self, other):
            return mycmp(self.obj, other.obj) >= 0
        def __ne__(self, other):
            return mycmp(self.obj, other.obj) != 0
    return K

def CmpNumbers(x,y):
    l1=len(x)
    l2=len(y)
    if l1<l2:
        ml=l1
    else:
        ml=l2
    for i in range(ml):
        if x[i]<y[i]:
            return(-1)
        if x[i]>y[i]:
            return(1)
    if l1<l2:
        return(-1)
    elif l1>l2:
        return(1)
    else:
        return(0)

def IsValid(x):
    if re.search('^[a-zA-Z0-9-_]+\@([a-zA-Z]|\d)+\.[a-zA-Z0-9]{1,3}$',x):
        return(True)
    return(False)
n=int(input())
emails=[input() for i in range(0,n)]
emails=list(filter(lambda x: IsValid(x),emails))
emails.sort(key=cmp_to_key(CmpNumbers))
print(emails)