Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- #-------------------------------------------------------------------------------
- # Name: phone
- # Purpose: A response to the easy python challenge - to parse telephone numbers and validate them.
- #
- # Author: luis
- #
- # Created: 02/18/12
- # Copyright: (c) luis 2012
- #-------------------------------------------------------------------------------
- type1 = [int,int,int,int,int,int,int,int,int,int] #10
- type2 = [int,int,int,str,int,int,int,str,int,int,int,int] #12
- type3 = [int,int,int,str,int,int,int,str,int,int,int,int] #12
- type4 = [str,int,int,int,str,int,int,int,str,int,int,int,int] #13
- type5 = [str,int,int,int,str,str,int,int,int,str,int,int,int,int] #14
- type6 = [int,int,int,str,int,int,int,int]
- def convert(pn):
- new = []
- for each in pn:
- try:
- int(each)
- new.append(int(each))
- except:
- new.append(each)
- return new
- def fits(lpn,typeid):
- for each in lpn:
- current = lpn.index(each)
- if type(each) != typeid[current]:
- return False
- return True
- def valid(pn):
- lpn = convert(pn)#list(pn)
- lenpn = len(pn)
- if lenpn <8 or lenpn > 14: #Invalidates anything out of the domain of possible phone number length before testing.
- return False
- if lenpn == 8:
- if fits(lpn,type6):
- return True
- if not fits(lpn,type6):
- return False
- if lenpn == 10: #Working
- try:
- pntype = [type(x) for x in lpn]
- except:
- return False
- return pntype == type1
- if lenpn == 12: #Working for both
- if fits(lpn,type2):
- acceptable = ["-","."]
- if lpn[3] in acceptable and lpn[7] in acceptable:
- return True
- return False
- if lenpn == 13: #Working
- if fits(lpn,type4):
- if lpn[0] == "(" and lpn[4] == ")" and lpn[8] == "-":
- return True
- return False
- if lenpn == 14:
- if fits(lpn,type5):
- return True
- return False
- def test():
- valid_phone_numbers = "1234567890,123-456-7890,123.456.7890,(123)456-7890,(123) 456-7890,456-7890".split(",")
- print "THESE SHOULD SUCCEED"
- for phone_number in valid_phone_numbers:
- assert valid(phone_number) == True
- print "Is %s validated?\t%r" % (str(phone_number),valid(phone_number))
- invalid_phone_numbers = "123-45-6789 123:4567890 123/456-7890".split()
- print "\nTHESE SHOULD FAIL:"
- for phone_number in invalid_phone_numbers:
- print "Is %s validated?\t%r" % (str(phone_number),valid(phone_number))
- if __name__ == '__main__':
- test()
- """
- valid telephone numbers: 1234567890, 123-456-7890, 123.456.7890, (123)456-7890, (123) 456-7890 (note the white space following the area code), and 456-7890.
- invalid telephone numbers: 123-45-6789, 123:4567890, and 123/456-7890.
- """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement