Pattern Matching Algorithm In Python