We need to read blocks until a line that is just "." and then after last block there is another ".".
For each block: first line is the correct expression; subsequent lines until a "." are student answers. For each student answer output "yes" if expression is mathematically equivalent to the correct expression, else "no". After each block output a line with a single "."
Important: We need to compare algebraic expressions. The expressions are multi-variable polynomials with variables a..z, integer coefficients. They may have spaces, parentheses, exponentiation (^ with a non-zero digit after it, maybe with spaces? But specification: "a variable symbol (one of the lowercase letters a' to z'), possibly followed by a symbol ^' and a non-zero digit, which represents the power of that variable". Note: it says non-zero digit, but might be more than one digit? Typically in such problems exponent is a positive integer maybe multi-digit? But the spec: "a non-zero digit", but later says "any expression, having its -'s replaced with +'s, if any, would have no variable raised to its 10th power, nor coefficient more than a billion, even if it is fully expanded". That suggests exponent can be up to 9? Actually "no variable raised to its 10th power" means max exponent < 10. But could be multiple digits but less than 10. However they say "non-zero digit" singular, but typical problems allow exponent as a positive integer possibly multi-digit? Since limit 9, it's fine to treat as a number. But we need to parse exponents: they say "possibly followed by a symbol ^' and a non-zero digit". Could be multiple digits? They didn't say exactly, but "digit" is singular. But then they mention "no variable raised to its 10th power", implying maximum exponent 9, so indeed a single digit. So we can treat exponent as a digit (1-9). However also they might allow exponent 0? They said "non-zero digit", so exponent cannot be 0. Variables with no exponent implicitly have exponent 1.
Coefficients: integers (non-negative decimal). Negative numbers are not explicitly allowed as coefficients; negative signs appear as subtraction operators; so coefficients are non-negative integers. However after combining signs, coefficients can become negative in the polynomial sense.
We need to compare two expressions for equivalence over integers. Equivalent if they represent the same polynomial (i.e., after expanding and combining like terms). We can fully expand both expressions into a canonical polynomial representation: a sum of monomials each with a coefficient (integer) and a product of variables with exponents. The monomials can be represented as a mapping from variable exponent vector to coefficient. Since variables are letters a..z (26 possible). But exponents are small (<10). The polynomial may have many terms, but maximum size limited by line length <= 80 characters, so after expansion, the number of terms is limited. However expansion could produce many terms if parentheses multiply. But since max length 80, the depth is limited; even if we multiply, the number of terms is bounded. For example (a+b+c+d+e+f+g+h+i+j)^2? That would be 10 variables, but each variable is a letter, and expression length is limited, so parentheses can't contain that many variables because the string length is 80. So we can safely expand.
We can parse the expression into an AST then evaluate to polynomial. Steps:
- Remove all spaces from the input line before parsing? Not entirely, because spaces are allowed but can be ignored. However careful: they may put spaces before an integer if it immediately follows another integer or a digit following ^. But that's just readability, so we can strip spaces completely; the grammar doesn't rely on spaces to separate tokens except where numbers and variables juxtapose? In algebraic expressions, juxtaposition means multiplication. If we remove spaces, then "2 2 3 3 3 a" becomes "22333a"? That would be problematic: the intended expression is "2 * 2 * 3 * 3 * 3 * a" but with spaces between numbers and numbers. Actually the spec says: "He says that he will put one or more space characters before an integer if it immediately follows another integer or a digit following the symbol
^'." So there are spaces used to separate numbers that are multiplied implicitly. For example, "2 2 3 3 3 a" means the product of integers 2,2,3,3,3 and variable a. If we remove all spaces, it becomes "22333a", which would be parsed as integer 22333 times a, which is wrong. So we cannot simply remove all spaces; spaces are part of the syntax: they serve as separators between tokens that are otherwise ambiguous? Actually in the grammar, a term is a juxtaposition of multiplicands. Multiplicands can be integers, variables (possibly with exponent), or parenthesized expressions. The juxtaposition means they are written next to each other. But if you have spaces between them, that would break juxtaposition? Usually in mathematical notation, spaces are ignored and do not affect multiplication: "2 2" is ambiguous. But the spec explicitly says: "He says that he will put one or more space characters before an integer if it immediately follows another integer or a digit following the symbol ^'." That means he uses spaces deliberately to separate integers that are to be multiplied. So the spaces are not ignorable; they are part of the multiplication syntax. Actually the grammar says: a term is a juxtaposition of multiplicands, representing their product; and a multiplicand is either ... So normally, if you write "2a", it's product of 2 and a. If you write "2 a", it's also product of 2 and a? In typical math, spaces are just separators and do not change meaning. The spec clarifies that he may put spaces for readability, but he also says that he will put spaces before an integer if it immediately follows another integer or a digit following ^. That suggests that in the absence of spaces, "22a" would be ambiguous: it could be integer 22 times a? But the grammar says integer is a digit sequence in decimal, so "22" is a valid integer. So if he writes "2 2 a", he intends the product of 2, 2, and a. But if we remove spaces, we get "22a", which is integer 22 times a, which is different. So the spaces are necessary to distinguish between concatenated digits and separate numbers. Therefore we cannot just delete spaces. Instead, we need to tokenize the string while respecting that spaces are separators; but also we need to treat juxtaposition (implicit multiplication) when tokens are adjacent or separated by spaces? The spec says "a term is a juxtaposition of multiplicands, representing their product". Juxtaposition means they are placed next to each other. Spaces are inserted for readability, so I think spaces between multiplicands do not affect the fact that they are multiplied. In standard math, "2 a" means 2 * a, so spaces don't break multiplication. However the issue is that "22" as a number is two digits, while "2 2" would be two separate numbers if spaces are considered as separators. So if we treat spaces as token delimiters, then "2 2" becomes two tokens: integer 2 and integer 2, and since they are in a term (juxtaposed), they multiply. If we ignore spaces, then "2 2" would become "22", which is a single number. So we need a tokenizer that splits the string into tokens based on delimiters including operators, parentheses, and possibly spaces? Typically for such problems, you first remove all spaces, because spaces are irrelevant. But then you lose the distinction between "2 2" and "22". However the spec says the teacher will put spaces before an integer if it immediately follows another integer or a digit following ^. That implies that if you see "2 2", it should be interpreted as two separate numbers 2 and 2, not as 22. So we cannot just remove spaces; we need to keep them as separators.
We need to define proper tokenization. The grammar: expression is a sequence of terms separated by additive operators '+' and '-'. Term is a juxtaposition of multiplicands. Multiplicand can be integer, variable (possibly with ^ digit), or parenthesized expression. So essentially the expression is like: [term] ([+-] term). Term: multiplicand [multiplicand] (implicit multiplication). Multiplicand: integer (digit sequence), variable (letter) optionally followed by "^" digit, or '(' expression ')'. So the tokens are: integers (digits), letters, '^', digits after '^' (but these digits are part of exponent and should be attached to the variable token), parentheses, and operators + and -. Spaces are allowed anywhere, but they should separate tokens where otherwise ambiguous? They say "He says that he will put one or more space characters before an integer if it immediately follows another integer or a digit following the symbol ^'." So spaces are used to separate integers from following integers, and also to separate exponent digit from following integer? Actually "before an integer if it immediately follows another integer or a digit following the symbol ^'." Means: If an integer appears right after another integer (i.e., without any operator or parentheses), he will put a space before it to separate them. So "22" would never appear; he will write "2 2" instead. Similarly, after a digit that is part of an exponent (like a^2), if the next token is an integer, he will put a space. So "a^22" would not occur; instead if he meant a^2 * 2, he'd write "a^2 2". Therefore, we can treat spaces as token separators. That is, we can tokenize by splitting on whitespace and also on operators and parentheses? But then we need to also parse tokens like "a^2". That contains no spaces, and '^' is an operator, but it's part of a variable's exponent. We need to parse it as a variable with exponent. So overall, we need a lexer that reads characters, skipping spaces, and produces tokens: integers, variables (just letter, and then optionally a ^ and a digit), operators + and -, parentheses. The key is that when we see a letter, we read it, then if next character is '^', we consume it and then read a digit (maybe multiple digits? but spec says digit). But there could be spaces? Probably no spaces between variable and ^, nor between ^ and digit; but spec didn't explicitly forbid spaces, but likely they are not inserted because that would break the token. They said he may put spaces here and there, but I think he wouldn't put spaces inside a variable^digit token. But to be safe, we could skip spaces after '^' before digit? But that might cause ambiguity if a space is inserted: "a ^ 2". That could be interpreted as variable a, then operator ^ (exponentiation), then integer 2. But spec says "possibly followed by a symbol ^ and a non-zero digit" - likely no spaces, but they might allow spaces? However typical expression: they said he may put spaces to make it readable, but he promises that he will put spaces before an integer if it immediately follows another integer or a digit following ^. That suggests that after ^ there might be a digit without space; but could there be space? Possibly yes, but then it would be interpreted as separate token? I'd better treat ^ as an operator that binds variable with exponent; we need to parse it as part of variable token. If there is a space, then it's ambiguous: "a ^ 2" would be tokenized as identifier a, then ^ operator, then integer 2. That could be considered as multiplication? Actually exponentiation is not a binary operator in the polynomial sense? They only define ^ as part of variable exponent, not as general exponentiation. So they expect that ^ appears only immediately after a variable letter, with no spaces, and then a digit. But they also say he may put spaces here and there. I think we can safely assume that there are no spaces between variable and ^, and between ^ and digit, because otherwise it would not match the grammar. The grammar says "a variable symbol (one of the lowercase letters z'), possibly followed by a symbol ^` suggests that after a ^ digit, there could be an integer following; he will put a space before that integer to separate. So in "a^2 3", it's a variable a^2 times 3. That's allowed.
Thus lexer: scan characters. When we see a space, skip. When we see a digit, collect consecutive digits to form an integer token. When we see a letter, collect the letter (just one letter) as variable name; then look ahead: if next char (skipping spaces? No, we should not skip spaces because if there is space, then it's not part of exponent) Actually after reading a letter, we need to check if next character is '^'. If it is, then consume '^' and then read a digit (or digits) for exponent. But note: there could be spaces after '^'? The spec says "digit following the symbol `^'." So likely no spaces. We'll treat it as: after letter, if next char (ignoring spaces?) but better to not skip spaces: if there is a space, then it's not an exponent. So we treat variable as just the letter; if immediately after (no spaces) we encounter '^', then it's exponent; else it's just variable with exponent 1. But we need to handle case like "a ^ 2". That would be letter a, then space, then '^', etc. According to grammar, that's not a valid variable with exponent; it would be variable a, then maybe a multiplicative operator? Actually exponentiation is not a binary operator; '^' is only used in variable^digit. So "a ^ 2" is not allowed. So we can assume no spaces.
Thus we can treat token types: INTEGER, VARIABLE (with exponent maybe), PLUS, MINUS, LPAREN, RPAREN. However the variable token may carry exponent (default 1). But also variables may appear without exponent. So when we parse the term, we treat variable as a multiplicand that is essentially a monomial with coefficient 1 and that variable to some exponent. Or we can parse into a polynomial step by step.
Alternative approach: We can fully expand expression to a polynomial representation by building an expression tree and then expanding. Since the expression is small, we could also compute the polynomial by evaluating for random assignments? That might be risky because we need exact equivalence over integers. But we could expand symbolically.
Better to parse into a tree, then define a function that converts the tree to a polynomial represented as a dictionary mapping tuple of exponents to integer coefficient.
Define variables as indices 0-25 for a-z.
Polynomial: sum of terms, each term: coefficient (int) * product of variables with exponents.
We need to support addition, subtraction, multiplication.
We also have unary minus? Actually the grammar: expression is terms separated by + and -. So the first term can have leading sign? The spec says: "Note that the operator +' or -' appears only as a binary operator and not as a unary operator to specify the sign of its operand." So no unary plus/minus. That means expression starts with a term (which could be just a multiplicand). So we don't need to handle unary signs. However subtraction is binary: term1 - term2.
But there is also negation possibly through subtraction? For example "a - (b - c)" is fine.
Implementation:
We'll write a parser for each expression string.
First, preprocess: we need to handle spaces properly. Since spaces are used as separators between multiplicands, we need to tokenize such that spaces act as implicit multiplication? Actually the grammar: "a term is a juxtaposition of multiplicands, representing their product". Juxtaposition means they are placed next to each other. If there are spaces between them, that still counts as juxtaposition? In math, "2 a" means 2*a, so yes, spaces are ignored as they are just for readability. However the critical distinction is that "22" vs "2 2". If we treat spaces as ignorable, then "2 2" becomes "22". But the spec says the teacher will use spaces to separate integers that would otherwise be concatenated. So if we ignore spaces, we would misinterpret "2 2" as 22, which is wrong. Therefore we must not ignore spaces; spaces are significant as separators between tokens that would otherwise be fused. Essentially, the grammar with spaces means that tokens are separated by spaces or operators/parentheses. So we can define tokenization where we split the string into tokens based on delimiters: operators (+,-), parentheses, spaces, and also the caret? Caret is part of variable exponent and should be treated as part of a variable token. But we can simply implement a lexer that scans character by character.
Lexer approach:
We'll iterate over the string with an index. We'll skip spaces (they just separate tokens, but we treat them as whitespace that ends a token). Actually we can treat spaces as token separators but not as tokens themselves. So when we encounter a space, we just advance. However we need to know when one token ends and next begins: for example, after reading an integer, if next character is a space, that space ends the integer token. Then after spaces, the next character could be a letter, which starts a new token. In the context of a term, multiple multiplicands are juxtaposed: they are placed one after another. If they are separated by spaces, that's still juxtaposition, so the parser should treat them as multiplication. So the lexer just returns tokens; the parser will then interpret a sequence of multiplicands (INTEGER, VARIABLE, LPAREN) as multiplied together, until it sees an operator or end-of-line.
Thus we can lex: skip spaces; then based on next char:
-
If digit: read consecutive digits (until non-digit). That forms an INTEGER token.
-
If letter: read the letter (just one letter) -> that's a VARIABLE token. But we need to check if immediately after (without spaces) there is a '^' and then a digit. However if we have spaces after the letter, then the '^' might not be immediate. According to grammar, exponent is part of variable token; so there should be no spaces. So after reading the letter, we look at the next character (without skipping spaces) - if it is '^', then we consume '^', and then if the next is a digit (maybe multiple digits? But we'll read digits), we read exponent digits. Then the token is VARIABLE with exponent (the exponent value). If after the letter there is no '^' (or there is space), then it's just variable with exponent 1. But careful: after reading letter, if we skip spaces, we might treat '^' after space as separate? That would break. So we need to check without skipping spaces. That is, we examine the character at current position. Since we have just read the letter and advanced index, the next character is at index i. If it's '^', then we treat as exponent; else, variable token ends. So we don't skip spaces before checking for '^'. That means if there is a space, then the next char is space, which is not '^', so variable token ends; then the space is skipped later, and next token might be '^'? That would be invalid as per grammar, but if present, it would be a parsing error. But input is guaranteed to be valid per grammar? Likely yes.
-
If char is '+' -> PLUS token.
-
If char is '-' -> MINUS token.
-
If char is '(' -> LPAREN token.
-
If char is ')' -> RPAREN token.
-
If char is '^' -> Should only appear as part of variable exponent, so encountering it alone would be an error; but we can handle as maybe a token for exponent? But better to treat as invalid; but according to grammar, it only appears after variable, so we can assume it's handled in variable case. So we may not expect standalone '^'.
But there is also possibility: after a variable, we might have '^' and then maybe a number like 10? But spec says exponent is a non-zero digit, so 10 would be two digits. However they also say "no variable raised to its 10th power" meaning exponent could be 9 maximum? But 10 would be not allowed. So exponent can be 1-9? Could be 10? "no variable raised to its 10th power" means exponent <10, so max 9. So exponent at most 9. So one digit is sufficient. But they say "digit" singular. So we'll read one digit.
Thus lexer returns tokens with types and values.
Now parsing:
We need to parse an expression (sum of terms). Grammar:
expression ::= term ( ('+' | '-') term )*
term ::= factor ( factor )* // multiplication, implicit
But careful: factor is multiplicand: could be integer, variable (with exponent), or '(' expression ')'. But note: a term can have multiple multiplicands multiplied. And there is no explicit '*' operator; just juxtaposition.
Thus we can parse as:
Parse expression:
left = parse_term()
while token is PLUS or MINUS:
op = token
advance
right = parse_term()
if op == PLUS: left = Add(left, right)
else: left = Subtract(left, right)
return left
Parse_term:
// parse one or more factors multiplied
factors = []
while next token is one of: INTEGER, VARIABLE, LPAREN:
factor = parse_factor()
factors.append(factor)
// If no factor found? Should not happen.
// Combine factors by multiplication: left = first factor; for each next, left = Multiply(left, next)
result = factors[0]
for f in factors[1:]:
result = Multiply(result, f)
return result
But careful: what about signs? The term itself does not have a sign; signs are outside. However subtraction uses binary minus. In expression, the first term may be positive; there is no unary plus/minus. So that's fine.
Now parse_factor:
if token is INTEGER:
val = integer value
advance
return Constant(val)
if token is VARIABLE:
var = letter, exponent = exponent (default 1)
advance
return Variable(var, exponent)
if token is LPAREN:
advance
expr = parse_expression()
expect RPAREN
advance
return expr
else error.
But note: a term can be empty? No.
Now we have an AST node types: Constant (int), Variable (char, exponent), Add, Subtract, Multiply.
Now we need to convert this AST into a polynomial representation. For constants, it's just coefficient with all exponents 0. For variable, it's monomial: coefficient 1 and exponent for that variable.
We need to handle subtraction: a - b is a + (-1 * b). So we can convert Subtract to Add with negation.
Multiplication: multiply two polynomials.
We need to fully expand and combine like terms.
Implementation: Represent polynomial as a dict mapping exponent tuple (26-element tuple) to integer coefficient. But we can compress: since variables are a..z, but the expression uses only some variables; we can map variable name to index (0-25). Use tuple of length 26? That might be heavy but number of terms is small. Alternatively, we can represent monomial as a tuple of pairs (var_index, exponent) sorted, and use that as key. That might be simpler and more efficient. Since max variables maybe 26, but typical small.
Better: represent monomial as a frozenset? But we need to combine like terms: same set of variables with same exponents. So we can use a tuple of 26 exponents, but we can compress with a dictionary from variable to exponent, then convert to a sorted tuple of (var_idx, exponent) to use as key.
Given that total number of distinct monomials after expansion is limited (maybe up to a few hundred), we can do that.
Simplify: For each node, compute its polynomial representation.
Define Polynomial as a dictionary: keys are monomial representation (e.g., tuple of 26 ints), values are int coefficients.
But to generate a 26-length tuple for each monomial, we need to know all variable indices. We can just use a dict mapping from variable name to exponent, but we need to be able to combine like terms. We could use a string representation like "a2b1" sorted, but that's more work.
Simpler: Since there are at most 26 variables, we can use a 26-element tuple. We'll maintain a global variable list. When we encounter a variable letter, we map 'a'->0,...,'z'->25.
When we multiply polynomials, we need to combine exponents by adding exponent vectors.
Implementation details:
Let poly be a dict where key is a tuple of 26 ints (exponents) and value is integer coefficient.
Constant (c): { (0,...,0): c }
Variable (v, exp): create vector with all zeros, set at index v_idx to exp. { vec: 1 }
Add two polynomials: combine by summing coefficients.
Subtract: similar to Add but with second polynomial's coefficients negated.
Multiply: For each term in p1, for each term in p2, multiply coefficients and add exponent vectors, accumulate.
We need to be careful with integer overflow? Coefficients can be up to a billion, and multiplications may cause larger, but still within Python's arbitrary integers.
Now after parsing both correct expression and student expression, we expand to polynomials, then compare if they are equal.
But there is nuance: The polynomial representation must be canonical, i.e., after combining like terms. Also we need to treat subtraction as per the expression.
Potential issues: The input may have leading/trailing spaces; we need to handle.
Also note: The parser must handle that there might be multiple terms without any operator? Actually terms are separated by '+' or '-'. However there is also implicit multiplication inside a term. So expression "a b" is a term consisting of two multiplicands a and b, which is product. That's fine.
Now about minus: In expression "a - (b - c)", the parser will parse term for a, then MINUS, then parse term for (b - c). The term for (b - c) will parse as a factor which is a parenthesized expression. Inside parentheses, it's an expression (b - c). So that yields a polynomial: b - c. Then subtraction will compute a - (b - c). That will become a + (-1)*(b - c) = a - b + c. That's correct.
Now about negative constants? There is no unary minus, so constants are non-negative. However after subtraction, coefficients can become negative. That's fine.
Now about exponent: variable may have exponent >1. Also note that multiplication of same variable adds exponents.
Now we need to handle zero coefficients: after addition/subtraction, we may get zero coefficients; we should remove those terms to keep polynomial simplified.
Now the comparisons: Two polynomials are equal if they have same non-zero terms.
Now about the representation: The order of monomials doesn't matter.
Now edge cases: The expression could be empty? No.
Now about spaces: In the lexer, we skip spaces, but we need to treat spaces as token separators. However, what about cases like "2a"? That is two multiplicands: integer 2 and variable a, no space. Our lexer would treat "2a" as digit 2 followed by letter 'a'? That is two separate tokens: integer 2 (since when we read digits we stop at non-digit, which is 'a', so we get integer token 2, then next token is letter 'a'. That's correct: juxtaposition is achieved by having consecutive tokens. So parser for term will parse factor (integer 2), then next token is VARIABLE, so it will parse factor (variable a) and multiply them. So "2a" works.
Now "2 2a"? That would be: integer 2, then spaces, then integer 2? Actually "2 2a": after skipping space, we see '2', so integer 2, then space, then '2' then 'a'? Let's simulate: Input "2 2a". Lexer: skip spaces? Starting at first char '2', it's digit, read digits until non-digit: we get "2". Next char is space; after returning token, we advance and skip spaces. Then we see '2', digit, read digits until non-digit: we get "2" then next char is 'a', which is not digit, so integer token 2. Then we have 'a' letter, token variable a. So tokens: INTEGER(2), INTEGER(2), VARIABLE(a). The parser: term: factors: INTEGER, INTEGER, VARIABLE. That's product 22a = 4a. So that matches the intention: "2 2 a" is product. So fine.
Now what about "22a"? That is digits '2','2','a'. Lexer: digits until non-digit, so integer 22, then variable a. So product 22 * a. So that's distinct from "2 2a". So spaces make a difference, as intended.
Now what about "a^2"? Lexer: letter 'a', then check next char is '^', so consume '^' and read digit(s). Suppose "a^2". After reading 'a', index points to '^'. Since it's '^', we consume it, then read digit '2' to get exponent=2. Then token is VARIABLE with exponent 2. The '^' and digit are consumed as part of the variable token. So token sequence: VARIABLE(a,2). That's correct.
Now "a ^2"? There is a space. Lexer: letter 'a', after reading 'a', index points to space, which is not '^', so variable token ends with exponent 1. Then later we skip spaces, then see '^', but '^' alone is not recognized as a token? It would be an unexpected character, but maybe according to grammar this shouldn't happen. But we can handle by error? Probably input won't contain such. We'll assume correct.
Now "a^ 2"? Similarly not allowed.
Now "a^10"? exponent digit(s) could be 10, but they said non-zero digit (singular), but might be two digits? "10" is two digits, which includes a '0', but they said non-zero digit, so first digit is non-zero, but could be followed by digits? They said "a non-zero digit". That suggests exactly one digit. But later they say "no variable raised to its 10th power", which implies exponent 10 is not allowed, but exponent 9 is allowed. So exponent may be 9 (single digit). I'll assume exponent is a single digit (1-9). If there are multiple digits, I could still parse as integer until non-digit, but that would be against spec. However for safety, we can parse any number of digits after '^' (but must be non-zero) and then treat as exponent. But the spec says "a non-zero digit". I'll parse exactly one digit. But I'll still parse multiple digits to be safe? The input lines are short; there might be "a^12"? But they said no variable raised to its 10th power, so exponent could be up to 9, but 12 > 9, so not allowed. So likely only single digit.
Now about parentheses: "(" expression ")". We'll handle recursively.
Now about precedence: In term, factors are multiplied together. So "a + b c" means a + (b*c). That's fine.
Now about order: The parser as described uses left recursion? We'll implement iterative.
Now about minus: There's also negative constants? They say no unary minus, so constants are non-negative.
Now after building polynomial for each expression, we compare.
Now consider the expansion: When we multiply polynomials, we might create many intermediate terms, but it's manageable.
Now about simplification: Could there be cancellation? Yes. So we must combine like terms.
Now about variable ordering: Our exponent vector is fixed order a..z. That is fine.
Now about the possibility of large coefficient: up to a billion. Multiplication might yield up to 10^18? That's fine in Python.
Now we must output "yes" or "no" for each student answer, and then a "." after each block.
Now the input: It is a sequence of blocks. Each block starts with an expression (the correct one), then zero or more student expressions, terminated by a line containing only ".". Then after the last block, there is an extra line containing ".". So we read lines until we encounter a line that is exactly "."; but that might be the end of a block or the final termination. We need to handle accordingly.
Algorithm for input reading:
- While True:
- Read first line of block. If it is "." then break (that's the final termination line after last block). But note: there could be empty blocks? Unlikely.
- This line is the correct expression.
- Then read subsequent lines. For each line:
- If line.strip() == ".": end of block. Output a line "." and break out to read next block (continue outer loop). But careful: The terminating line could have spaces? It says "a line solely consisting of a period symbol." So we can check if line.strip() == ".".
- Otherwise, it's a student expression. Process it and output "yes" or "no".
- After finishing block (i.e., after encountering "."), we need to output a line with ".". According to example, after each block's answers, we output a line with a single period. So after processing all student answers for a block, we output ".".
But note: After the final block, there is an extra "." line. That line signals end of input; we should not output an extra "." after that? Actually the sample output shows for each block they output a period after the answers. For the final block, after the last answer lines, they output a period line. And there is no extra period after that. The input has two terminating lines: one to end the block and one after the last block. Actually reading the sample input:
a+b+c
(a+b)+c
a- (b-c)+2
.
4ab
(a - b) (0-b+a) - 1a ^ 2 - b ^ 2
2 b 2 a
.
108 a
2 2 3 3 3 a
4 a^1 27
.
.
The first block: three lines: correct, answer1, answer2, then "." line. Next block: correct, answer1, answer2, then "." line. Next block: correct, answer1, answer2, then "." line. Then there is an extra "." line at the end. So there are three blocks. After reading each block, we output answers and then a line ".". The extra "." at the end is just to mark end of input; we don't output anything for it.
So our loop: while True:
line = read line (strip newline). If line is None (EOF) break? But there is always a final ".".
If line.strip() == ".": break (since this would be the final termination line if we have no more blocks? But we need to differentiate between block-terminating "." and final ".". The pattern: After a block, there is a line with ".". Then the next line could be another expression (next block) or another "." (final). So when we read a line that is ".", we need to check if it is the start of a block? Actually the first line of a block is never "." because that would be an empty block. So if we read a line and it is ".", that indicates either the end of the current block (if we are within a block and have read at least one expression?) or the final termination if we are expecting a new block. In our algorithm, we can read blocks as:
while True:
# read the correct expression line
line = read_line()
if line is None: break
if line.strip() == ".": # this is the final terminator if we have just finished a block, but we might be at start of a new block? Actually if we finished a block, we would have consumed the terminating "." already. So after finishing a block, we go back to start of loop to read the next correct expression. If we then read a line that is ".", that means there is no more block; it's the final line.
break
correct_expr = line
answers = []
while True:
line = read_line()
if line is None: break (error)
if line.strip() == ".":
# end of this block
break
answers.append(line)
# process block: for each answer, compare with correct_expr and output yes/no
# after processing, output a line "."
# then continue to next block
So the final "." will be read at the start of the outer while loop, causing break. That's correct.
Now we need to implement the polynomial expansion.
Implementation plan:
Define class Polynomial:
terms: dict where key is tuple of 26 ints, value int coefficient.
But we can also use a more efficient representation: a dict from frozenset? Not.
We'll have a helper function to convert a variable name to index: ord(ch) - ord('a').
We'll also define a function to normalize polynomial: remove zero coefficients.
Operations:
add(poly1, poly2): returns new polynomial sum.
subtract(poly1, poly2): sum with negation.
multiply(poly1, poly2): product.
from_constant(c): polynomial with single term all zeros.
from_variable(var_index, exp=1): vector zeros with exponent at var_index.
We'll also need to handle negative coefficients.
Now parse tree to polynomial:
We'll build AST nodes but we can directly compute polynomial recursively using functions that return Polynomial objects. That might be simpler: while parsing, we can compute polynomial on the fly. However note that multiplication may be nested; we can compute bottom-up.
Thus in the parser, when we parse a factor, we return a Polynomial. For integer, return constant polynomial. For variable, return variable polynomial. For parentheses, parse expression and return its polynomial. For term: we need to multiply the polynomials of factors in sequence. For expression: we need to add/subtract polynomials.
But careful: In term, we have factors that are multiplied; but these factors themselves may be sums (if they are parenthesized expressions). So we need to multiply polynomials correctly. So we must compute polynomial for each factor (which could be sum), then multiply them in order.
Thus our parser functions can return Polynomial objects.
Implementation details for parser: Use recursive descent with a token list and index.
Define token types: we can use a class Token with type and value. Types: INTEGER, VARIABLE, PLUS, MINUS, LPAREN, RPAREN, EOF.
We'll lex the whole input line into tokens.
Lexer details:
We'll define a function tokenize(expr_str) -> list of tokens.
Initialize pos=0, tokens=[].
While pos < len(expr_str):
char = expr_str[pos]
if char.isspace():
pos += 1
continue
if char.isdigit():
start = pos
while pos < len(expr_str) and expr_str[pos].isdigit():
pos += 1
num_str = expr_str[start:pos]
tokens.append(('INT', int(num_str)))
continue
if char.isalpha(): # lowercase letter
var = char
pos += 1
exp = 1
if pos < len(expr_str) and expr_str[pos] == '^':
pos += 1
# after '^', there must be a digit (non-zero). But we can just read digits.
if pos < len(expr_str) and expr_str[pos].isdigit():
start = pos
while pos < len(expr_str) and expr_str[pos].isdigit():
pos += 1
exp_str = expr_str[start:pos]
exp = int(exp_str)
else:
# error, but assume at least one digit.
pass
tokens.append(('VAR', (var, exp)))
continue
if char == '+':
tokens.append(('PLUS', None))
pos += 1
continue
if char == '-':
tokens.append(('MINUS', None))
pos += 1
continue
if char == '(':
tokens.append(('LPAREN', None))
pos += 1
continue
if char == ')':
tokens.append(('RPAREN', None))
pos += 1
continue
# if none, maybe error (should not happen)
raise ValueError(f"Unknown character: {char}")
After loop, tokens.append(('EOF', None))
Now parsing:
We'll have a class Parser with tokens and current index.
Methods:
def parse_expression(self):
# parse term, then while next token is PLUS or MINUS, combine.
left = self.parse_term()
while self.current_token[0] in ('PLUS', 'MINUS'):
op = self.current_token[0]
self.advance()
right = self.parse_term()
if op == 'PLUS':
left = left.add(right)
else: # MINUS
left = left.subtract(right)
return left
def parse_term(self):
factors = []
# We need to detect start of factor: integer, variable, or lparen.
while self.current_token[0] in ('INT', 'VAR', 'LPAREN'):
factor = self.parse_factor()
factors.append(factor)
if not factors:
# Error: expected factor
raise SyntaxError("No factor in term")
# Multiply them sequentially
result = factors[0]
for f in factors[1:]:
result = result.multiply(f)
return result
def parse_factor(self):
tok = self.current_token
if tok[0] == 'INT':
val = tok[1]
self.advance()
return Polynomial.constant(val)
elif tok[0] == 'VAR':
var_name, exp = tok[1]
idx = ord(var_name) - ord('a')
self.advance()
return Polynomial.variable(idx, exp)
elif tok[0] == 'LPAREN':
self.advance()
expr_poly = self.parse_expression()
# expect RPAREN
if self.current_token[0] != 'RPAREN':
raise SyntaxError("Expected )")
self.advance()
return expr_poly
else:
raise SyntaxError("Unexpected token in factor")
We'll need to define Polynomial class with methods add, subtract, multiply, and classmethods constant and variable.
Now implement Polynomial.
We'll represent exponent vector as a tuple of 26 ints. But creating a tuple of 26 for each monomial may be overhead but fine.
Alternative: Use a tuple of 26 small ints. We'll generate it using list of zeros then set index.
To combine two monomials: we add exponent vectors element-wise.
We'll need to be able to hash the tuple.
Define:
class Polynomial:
def init(self, terms=None):
# terms: dict mapping tuple(26) -> int
self.terms = terms if terms is not None else {}
@staticmethod
def constant(c):
p = Polynomial()
if c != 0:
vec = tuple([0]*26)
p.terms[vec] = c
return p
@staticmethod
def variable(idx, exp=1):
p = Polynomial()
vec = [0]*26
vec[idx] = exp
p.terms[tuple(vec)] = 1
return p
def is_zero(self):
return len(self.terms)==0
def add(self, other):
new_terms = dict(self.terms)
for vec, coeff in other.terms.items():
new_terms[vec] = new_terms.get(vec, 0) + coeff
# Remove zeros
to_remove = [vec for vec, c in new_terms.items() if c == 0]
for vec in to_remove:
del new_terms[vec]
return Polynomial(new_terms)
def subtract(self, other):
# self - other
new_terms = dict(self.terms)
for vec, coeff in other.terms.items():
new_terms[vec] = new_terms.get(vec, 0) - coeff
# Remove zeros
to_remove = [vec for vec, c in new_terms.items() if c == 0]
for vec in to_remove:
del new_terms[vec]
return Polynomial(new_terms)
def multiply(self, other):
new_terms = {}
for vec1, coeff1 in self.terms.items():
for vec2, coeff2 in other.terms.items():
# compute new exponent vector
new_vec = tuple(vec1[i] + vec2[i] for i in range(26))
new_coeff = coeff1 * coeff2
if new_coeff != 0:
new_terms[new_vec] = new_terms.get(new_vec, 0) + new_coeff
# Remove zeros (though we only added non-zero, but could cancel if same vec from different combos? Actually we accumulate, might become zero if sums cancel? But multiplication of two polynomials with integer coefficients, no cancellation between different products unless same monomial appears from different pairs, which can cancel if coefficients sum to zero. So we need to remove zeros after.
to_remove = [vec for vec, c in new_terms.items() if c == 0]
for vec in to_remove:
del new_terms[vec]
return Polynomial(new_terms)
def __eq__(self, other):
# compare terms
if len(self.terms) != len(other.terms):
return False
for vec, coeff in self.terms.items():
if other.terms.get(vec, 0) != coeff:
return False
return True
But we need to be careful: The polynomial may have terms that simplify to zero; we always remove zeros.
Now note: In term parsing, when we have multiple factors, we multiply sequentially. That works.
Now about subtraction: Since we have a subtract method, we can use it.
Now potential issues: The parser's add and subtract and multiply will be called many times for small expressions; it's fine.
Now one nuance: The grammar allows something like "a - b" but not "-a". That's okay.
Now about exponent: In variable token, we store exponent as int. But what about case where exponent is 0? Not allowed; but if it appears? Not.
Now about integer constant: Could be zero. The spec says non-negative integer as digit sequence. So 0 is allowed.
Now about multiplication by zero: That will yield zero polynomial. We need to handle that: Polynomial.constant(0) returns empty dict.
Now about addition: If both zero, dict empty.
Now after parsing both expressions, we compare polynomial equality.
Now we need to test on sample.
Let's simulate sample.
Block 1:
correct: "a+b+c"
Should parse to terms: a, b, c, each as variable with exponent 1. So polynomial: {a:1, b:1, c:1}. (Vector representations)
Student1: "(a+b)+c". That's same.
Student2: "a- (b-c)+2". That's a - (b - c) + 2 = a - b + c + 2. So polynomial: a:1, b:-1, c:1, constant:2. Not equal to a+b+c. So output no.
Matches sample: yes, no, .
Block2:
correct: "4ab". That's 4ab? Actually "4ab" is integer 4 and variable a and b, so product: 4ab. So polynomial: 4ab.
Student1: "(a - b) (0-b+a) - 1a ^ 2 - b ^ 2". Let's parse: (a - b)(0 - b + a) - 1a^2 - b^2. But note: "0-b+a" is ambiguous? Actually "0 - b + a" = a - b? Because 0 - b + a = a - b. So (a-b)*(a-b) = (a-b)^2 = a^2 - 2ab + b^2. Then minus a^2 and minus b^2 => a^2 - 2ab + b^2 - a^2 - b^2 = -2ab. But the coefficient is -2, not 4. So not equivalent. Output no? Sample says no for first student? Actually sample output for block2:
no
yes
.
First line no, second yes. So first answer is no, second yes. So matches: (a - b)(0-b+a) - 1a^2 - b^2 simplifies to -2ab, not 4ab => no.
Second student: "2 b 2 a". That's 2 * b * 2 * a = 4ab => yes.
Block3:
correct: "108 a". That's 108 * a.
Student1: "2 2 3 3 3 a". That's 22333a = 108a => yes.
Student2: "4 a^1 27". That's 4a*27 = 108a => yes.
Matches sample.
Now consider other cases: Negative coefficients from subtraction, but no unary minus. Good.
Now there might be parentheses with sums multiplied: e.g., (a+b)(a-b) etc.
Now need to ensure that our lexer correctly parses "a^1" as variable a exponent 1. Good.
Now potential pitfalls: The parser's term detection uses while token in (INT, VAR, LPAREN). That is fine. But what about the case where after parsing a factor, the next token is not one of those? For example, after parsing a term, we might be at PLUS, MINUS, RPAREN, or EOF. So term stops appropriately.
Now about parsing expression: It calls parse_term, then while plus/minus. However, note that expression could be just a term, then EOF.
Now about parentheses: Inside parse_factor when encountering LPAREN, we call parse_expression, which will parse inside the parentheses, then expect RPAREN. That's correct.
Now about token consumption: In parse_expression, after parse_term, we check current token type. For a term that ends with RPAREN (closing parenthesis), the parse_expression will not consume the RPAREN; it's left for the caller (parse_factor) to consume. That's fine.
Now need to handle that parse_expression may be called from parse_factor and also from top-level. When we parse an expression inside parentheses, we parse_expression, then after that, we expect RPAREN. That works.
Now about EOF: Our token list ends with EOF. We'll have a method advance to move to next token.
Now about error handling: Input is guaranteed valid; we can assume no errors.
Now we should test with some cases.
Consider expression with multiple parentheses: "((a))". Should parse to a.
Consider "a + b - c". That's a + b - c.
Consider "a(b+c)". That's a term: factor a and factor (b+c). So product: a*(b+c) => ab + ac.
Our parser: parse_term: factors: parse_factor -> variable a; then next token is LPAREN -> parse_factor -> inside parentheses parse_expression: b+c => polynomial b+c. Then multiply a * (b+c). Works.
Now consider "a - b - c": This is left associative? The grammar: expression ::= term ( ('+'|'-') term )* . So a - b - c is (a - b) - c. That's correct.
Now about precedence: Multiplication (juxtaposition) binds tighter than addition/subtraction. Our parser respects that because term groups factors before handling plus/minus.
Now about exponent: "a^2b^3". That's variable a^2 and variable b^3 multiplied. Lexer: after reading a, sees '^', reads digit 2, token VAR(a,2). Then next token? The character after '2' is 'b'. So after consuming exponent digits, we are at 'b', which is letter. So next token will be VAR(b, maybe with ^?). So tokens: VAR(a,2), VAR(b,3). The term will multiply them => a^2 * b^3.
Now "a^2 b^3" with space: same.
Now "a^2 3": VAR(a,2) INT(3) => product a^2 * 3.
Now "a^2(b+c)": VAR(a,2) LPAREN => factor a^2 and factor (b+c) => product.
Now about integer with leading zeros? They said non-negative integer as digit sequence. Could have leading zeros? Usually not, but possible? They didn't forbid. Might treat as integer with leading zeros: e.g., "01" is 1. But we parse digits to integer, so leading zeros are fine.
Now about negative sign inside parentheses? Not allowed as unary. So "(-a)" is not allowed. But there could be "-(a)"? Actually "- (a)" as part of expression? The spec says operator + or - appears only as binary. So you could have "a - (b)" but not "-a". So negative constant cannot appear directly. So constants are non-negative.
Now about subtraction of parentheses: "a - (b - c)" we handle.
Now about multiple terms: Good.
Now about potential spaces: Our lexer skips spaces, so spaces are ignored as separators. But note that spaces are used to separate integers that would otherwise be concatenated. Our lexer treats