Best Python code snippet using slash
18-pattern-matching.py
Source:18-pattern-matching.py
1# Determine whether the given string matches the given pattern of a's and b's.2def matches_pattern(string, pattern):3 if len(pattern) == 0:4 return len(string) == 05 if len(string) == 0:6 return True7 pattern = normalize(pattern)8 a_count, b_count = 0, 09 for letter in pattern:10 if letter == 'a':11 a_count += 112 else:13 b_count += 114 for a_len in xrange(1, len(string) / a_count + 1):15 letters_left = len(string) - a_count * a_len16 if b_count and letters_left % b_count == 0:17 a_val = string[:a_len]18 b_len = (len(string) - a_count * a_len) / b_count19 if b_len == 0:20 break21 matches = try_pattern(string, pattern, a_val, b_len)22 if matches:23 return True24 elif letters_left == 0:25 return try_pattern(string, pattern, string[:a_len], 0)26 return False27def try_pattern(string, pattern, a_val, b_len):28 a_len, b_val = len(a_val), None29 ix = len(a_val)30 for letter in pattern[1:]:31 if letter == 'a':32 if string[ix : ix + a_len] == a_val:33 ix += a_len34 else:35 return False36 elif b_val is None:37 b_val = string[ix : ix + b_len]38 ix += b_len39 elif string[ix : ix + b_len] == b_val:40 ix += b_len41 else:42 return False43 return True44def normalize(pattern):45 if pattern[0] == "a":46 return pattern47 inverted = []48 for letter in pattern:49 if letter == "a":50 inverted.append("b")51 else:52 inverted.append("a")53 return "".join(inverted)54import unittest55class Test(unittest.TestCase):56 def test_matches_pattern(self):57 self.assertTrue(matches_pattern("dogdogturtledog", "aaba"))58 self.assertTrue(matches_pattern("dogdogturtledog", "bbab"))59 self.assertTrue(matches_pattern("dogdogturtledogdog", "aabaa"))60 self.assertTrue(matches_pattern("dogdogturtledogdog", "aba"))61 self.assertTrue(matches_pattern("dogdogturtledogdo", "aba"))62 self.assertFalse(matches_pattern("dogdogturtledogdg", "aba"))63 self.assertTrue(matches_pattern("catcatbirdbird", "aabb"))64 self.assertFalse(matches_pattern("catcatcatbirdbird", "aabb"))65 self.assertTrue(matches_pattern("buffalobuffalobuffalobuffalo", "aaaa"))66 self.assertFalse(matches_pattern("buffalobuffalouffalobuffalo", "aaaa"))67if __name__ == "__main__":...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!