Count of "a"s and "b"s must be equal. Did you get it computer?
Python 3, 32 bytes
eval(input().translate(")("*50))
Outputs via exit code: Error for false, no error for True.
The string is evaluated as Python code, replacing parens (
for a
and )
for b
. Only expressions of the form a^n b^n
become well-formed expressions of parentheses like ((()))
, evaluating to the tuple ()
.
Any mismatched parens give an error, as will multiple groups like (()())
, since there's no separator. The empty string also fails (it would succeed on exec
).
The conversion ( -> a
, ) -> b
is done using str.translate
, which replaces characters as indicated by a string that serves as a conversion table. Given the 100-length string ")("*50, the tables maps the first 100 ASCII values as
... Z[\]^_`abc
... )()()()()(
which takes ( -> a
, ) -> b
. In Python 2, conversions for all 256 ASCII values must be provided, requiring "ab"*128
, one byte longer; thanks to isaacg for pointing this out.
MATL, 5 4 bytes
tSP-
Prints a non-empty array of 1s if the string belongs to L, and an empty array or an array with 0s (both falsy) otherwise.
Thanks to @LuisMendo for golfing off 1 byte!
Try it online!
How it works
t Push a copy of the implicitly read input.
S Sort the copy.
P Reverse the sorted copy.
- Take the difference of the code point of the corresponding characters
of the sorted string and the original.
Retina, 12 bytes
Credits to FryAmTheEggman who found this solution independently.
+`a;?b
;
^;$
Prints 1
for valid input and 0
otherwise.
Try it online! (The first line enables a linefeed-separated test suite.)
Explanation
Balancing groups require expensive syntax, so instead I'm trying to reduce a valid input to a simple form.
Stage 1
+`a;?b
;
The +
tells Retina to repeat this stage in a loop until the output stops changing. It matches either ab
or a;b
and replaces it with ;
. Let's consider a few cases:
- If the
a
s and theb
s in the string aren't balanced in the same way that(
and)
normally need to be, somea
orb
will remain in the string, sinceba
, orb;a
can't be resolved and a singlea
orb
on its own can't either. To get rid of all thea
s and theb
s there has to be one correspondingb
to the right of eacha
. - If the
a
and theb
aren't all nested (e.g. if we have something likeabab
oraabaabbb
) then we'll end up with multiple;
(and potentially somea
s andb
s) because the first iteration will find multipleab
s to insert them and further iterations will preserve the number of;
in the string.
Hence, if and only if the input is of the form anbn
, we'll end up with a single ;
in the string.
Stage 2:
^;$
Check whether the resulting string contains nothing but a single semicolon. (When I say "check" I actually mean, "count the number of matches of the given regex, but since that regex can match at most once due to the anchors, this gives either 0
or 1
.)