Wite the code in python to solve the quest acc. To...
Created on: July 31, 2025
Created on: July 31, 2025
pythondef balanced(s): return (s.count('a')+s.count('c'))%2==0 and (s.count('b')+s.count('d'))%2==0 regex = re.compile(r'^(?=(?:[^ac]*[ac][^ac]*[ac])*[^ac]*$)(?=(?:[^bd]*[bd][^bd]*[bd])*[^bd]*$)[abcd]*$') test = ["", "a", "ac", "ab", "abcd", "abc", "cdba", "aaccbbdd", "acdbdbbbbbaaaac", "aacccb", "cdcdaabb"] for t in test: print(t, balanced(t), bool(regex.fullmatch(t)))
pythonimport random def randomstr(n=20): return ''.join(random.choice('abcd') for _ in range(n)) for _ in range(1000): s = randomstr(random.randint(0,10)) if regex.fullmatch(s) != balanced(s): print("Mismatch", s, balanced(s)) break
pythonregex.fullmatch("d"), balanced("d") (None, False)
pythonfor s in ["d","b","dd","bb","bd"]: print(s, balanced(s), bool(regex.fullmatch(s)))
Here’s a drop-in replacement that keeps every line after the import
exactly as is:
python# fill in the pattern (leave the leading r!) Regex_Pattern = r'^(?=(?:[^ac]*[ac][^ac]*[ac])*[^ac]*$)(?=(?:[^bd]*[bd][^bd]*[bd])*[^bd]*$)[abcd]+$' # Do not delete 'r'. import re print(str(bool(re.search(Regex_Pattern, input()))).lower())
(?=(?:[^ac]*[ac][^ac]*[ac])*[^ac]*$)
ensures an even total of a
+ c
.(?=(?:[^bd]*[bd][^bd]*[bd])*[^bd]*$)
ensures an even total of b
+ d
.[abcd]+$
accepts any non-empty string consisting solely of the allowed letters.Drop it in and run the tests — each sample case should now pass. 🎉