from neo.constants import LEFT, RIGHT

def index_of_set(string, match_list, fromdir=LEFT):
    """Return the smallest or largest index of any item in match_list that can be found
    in string.  If fromdir is LEFT, return smallest index; if it is RIGHT, return largest."""
    from string import index, rindex
    match_list = [x for x in match_list]
    indexes = []
    for item in match_list:
        try:
            if fromdir == LEFT:
                indexes.append(index(string, item))
            else:
                indexes.append(rindex(string, item))
        except ValueError:
            pass
    try:
        if fromdir == LEFT:
            return min(indexes)
        else:
            return max(indexes)
    except ValueError:
        return -1

def set_cmp(string, set1, set2, fromdir=LEFT):
    """Return 1 if some string in set1 occurs before some string in set2.  If some string
    in set2 occurs before some string in set1, return -1.  If no strings from either set
    occur in the string, return 0."""
    set1_pos = index_of_set(string, set1, fromdir)
    set2_pos = index_of_set(string, set2, fromdir)
    if set1_pos == -1 and set2_pos == -1:
        return 0
    elif set1_pos == -1:
        return -1
    elif set2_pos == -1:
        return 1
    if fromdir == LEFT:
        if set1_pos < set2_pos:
            return 1
        elif set1_pos > set2_pos:
            return -1
        else:
            return 0
    else:
        if set1_pos > set2_pos:
            return 1
        elif set1_pos < set2_pos:
            return -1
        else:
            return 0

def regression_tests():
    from neo.common_testing import test_eq
    from neo.constants import TRUE, FALSE
    print "Testing neo.utilities..."
    print "    Testing set_cmp... ",
    sample = 'test("foo")'
    parens = '()'
    quotes = '\"\''
    star = '*'
    percent = '%'
    test_eq(set_cmp(sample, parens, quotes), 1, "failed set_cmp[1], both sets present!", last=FALSE)
    test_eq(set_cmp(sample, quotes, parens), -1, "failed set_cmp[2], both sets present!", last=FALSE)
    test_eq(set_cmp(sample, star, percent), 0, "failed set_cmp, neither set present!", last=FALSE)
    test_eq(set_cmp(sample, star, parens), -1, "failed set_cmp[1], one set present!", last=FALSE)
    test_eq(set_cmp(sample, parens, percent), 1, "failed set_cmp[2], one set present!")
    print "All tests passed!"

if __name__ == '__main__':
    regression_tests()


syntax highlighted by Code2HTML, v. 0.9.1