dailylog 03-01-21

less than 1 minute read

Successfully Handling Non-Nested Parens

import unittest

def check_if_valid(left, right):
    if left == "(" and right == ")":
        return True

def check_parens(test):
    max_count = 0
    count = 0
    i = 1
    while i < len(test):
        print(test[i-1], test[i])

        if check_if_valid(test[i-1], test[i]):
            count += 1

            i += 2
        else:
            if count > max_count:
                max_count = count
            count = 0
            i += 1

    return count * 2


class Test(unittest.TestCase):
    '''Test Cases'''
    data = [
        ("(()", 2),
        (")()())", 4)
    ]
    def test_paren_strings(self):
        for [paren_string, expected] in self.data:
            actual = check_parens(paren_string)
            self.assertEqual(actual, expected)

unittest.main(argv=[''], verbosity=2, exit=False)


Recursive Attempt at Handling this?

def remove_valid_parens(test, incrementor, count):
    print(test, count)
    i = incrementor

    try:
        if check_if_valid(test[i-1], test[i]):
            count += 2
            front = test[:i-1]
            back = test[i+1:]
            remove_valid_parens(front+back, i, count)
        else:
            incrementor += 1
            remove_valid_parens(test, incrementor, count)
    except:
        pass

#     print(count)
    return count
remove_valid_parens(test, 1, 0)