Pages

Friday, April 4, 2014

Week 11: A2 Continued

Ok, looking back at fixing regex_match: as a review, the problem I was having was that my code did not account for valid string matches that were less than one character long for bar and dot trees.

This meant my code was fundamentally wrong, since I used range(0, len(string)), which would not execute at all where len(string) == 0.

The mistake was easily remedied by initializing the variables I was using outside of my range loop, so I would have some values to work with regardless of the length of the string:
        s1 = ''
        s2 = ''
        for i in range(0, len(s)):
            if regex_match(r.children[0], s1) and \
               regex_match(r.children[1], s2):
                return True
            s1 = s[0:i]
            s2 = s[i:]
Which made the code work out, thankfully. Come to think of it, this bugged me at first when I approached this function, but I forgot to account for it: this makes me realize another important aspect of coding, which is very similar to story writing: it cannot be 'edge of your seat' work, it must be planned before hand, and whenever you think of potential test cases, issues, or ways to throw off your protagonist, write them down!

Ok: the last issue with the code was this:
AssertionError: None is not true : Rejects valid match: (DotTree(Leaf('e'), Leaf('e')), '')
Which reminded me that the same problem I was trying to address previously had still not been solved.
With a little bit of thinking and a lot of redundancy, I came up with a working solution:
        s1 = ''
        s2 = ''
        if regex_match(r.children[0], s1) and \
               regex_match(r.children[1], s2):
                return True
        for i in range(0, len(s)):
            if regex_match(r.children[0], s1) and \
               regex_match(r.children[1], s2):
                return True
            s1 = s[0:i]
            s2 = s[i:]

No comments:

Post a Comment