Skip to content
Advertisement

Validate Postal Code?

I’m doing some tutorials online…and I’m stuck at an exercise:Define a function postalValidate(S) which first checks if S represents a postal code which is valid. Note: I’m supposed to solve it with strings, lists, if statements, loops, and other basic constructs like variables and functions.

first, delete all spaces; the remainder must be of the form L#L#L# where L are letters (in either lower or upper case) and # are numbers.

If S is not a valid postal code, return the boolean False. If S is valid, return a version of the same postal code in the nice format L#L#L# where each L is capital.

I’ve created a code for these exercise, but the grader said that is wrong, however I will post it too.

def postalValidate(S):
   while " " in S:
     S.remove(" ")
   for i in range(1,6,2):
     S.isdigit(S[i])
   for j in range(0,5,2):
     S.upper(S[j]
     S.isalpha(S[j])
   return True

Advertisement

Answer

This is clearly a job for regular expressions, although I don’t know if you’re supposed to use them in the exercise…

I’m posting this as an answer just in case you can. Otherwise, let us know…

#/usr/bin/evn python

import re
zipCode = re.compile(r"s*(wds*){3}s*")

if __name__ == "__main__":
    samples = [
        "           44F 4 F", #Invalid
        "  L0L0L0    ", #Valid
        "  L0  L0  L0    ", #Valid
    ]

    for sample in samples:
        if zipCode.match(sample):
            print "The string %s is a valid zipCode (nice and clean: %s)" % (sample, sample.replace(" ", "").upper())
        else:
            print "The string %s is NOT a valid zipCode" % sample

Edit:

Since you can not use regular expressions, I’d recommend you change the way of thinking… Instead of checking if the characters belong to a valid postal code, I’d recommend you do the opposite: check if they DON’T belong in a valid postal code, returning False as soon as you detect a misplaced (or wrong) character:

def postalValidate(S):
    S = S.upper().replace(" ", "")
    if len(S) == 6:
        for i in range(len(S)):
            if i % 2 == 0:
                #Even index (0, 2, 4, 6...) , has to be 'letter'
                if not(S[i].isalpha()):
                    return False 
            else:
                #Odd index (1, 3, 5, 7...), must be 'number'
                if not(S[i].isdigit()):
                    return False

    else:
        #You can save some cpu ticks here... at this point, the string has to be of length 6 or you know it's not a zip
        return False
    return S

The return statement stops the execution of the current function so as soon as you realize that there’s something “wrong” with the string to check, you can return False (there’s no point on keeping checking once you know it’s not valid, right?)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement