| 1 | 1 | def answer(question: str) -> int: |
| 2 | | pass |
| 2 | # Edge Case: Empty question |
| 3 | if not question: |
| 4 | raise ValueError("syntax error") |
| 5 | |
| 6 | # Edge Case: Question doesn't start with "What is" |
| 7 | if not question.startswith("What is"): |
| 8 | raise ValueError("unknown operation") |
| 9 | |
| 10 | # Remove "What is" and "?" from the question |
| 11 | question = question[8:-1].strip() |
| 12 | |
| 13 | # Edge Case: Empty expression after removing "What is" and "?" |
| 14 | if not question: |
| 15 | raise ValueError("syntax error") |
| 16 | |
| 17 | # Split the question into tokens |
| 18 | tokens = question.split() |
| 19 | |
| 20 | # Edge Case: No tokens |
| 21 | if not tokens: |
| 22 | raise ValueError("syntax error") |
| 23 | |
| 24 | # Parse the first token as a number |
| 25 | try: |
| 26 | result = int(tokens[0]) |
| 27 | except ValueError: |
| 28 | # Edge Case: First token is not a number |
| 29 | raise ValueError("syntax error") |
| 30 | |
| 31 | # Process the rest of the tokens |
| 32 | i = 1 |
| 33 | while i < len(tokens): |
| 34 | # Get the operation |
| 35 | op = tokens[i] |
| 36 | |
| 37 | # Edge Case: Operator is missing or duplicated |
| 38 | if op in ["plus", "minus", "multiplied", "divided"]: |
| 39 | # Handle "multiplied by" and "divided by" |
| 40 | if op == "multiplied" or op == "divided": |
| 41 | # Edge Case: Missing "by" after "multiplied" or "divided" |
| 42 | if i + 1 >= len(tokens) or tokens[i + 1] != "by": |
| 43 | raise ValueError("syntax error") |
| 44 | i += 1 # Skip "by" |
| 45 | else: |
| 46 | # Edge Case: Unknown operation |
| 47 | raise ValueError("unknown operation") |
| 48 | |
| 49 | # Edge Case: Missing number after operator |
| 50 | if i + 1 >= len(tokens): |
| 51 | raise ValueError("syntax error") |
| 52 | |
| 53 | # Get the next number |
| 54 | try: |
| 55 | num = int(tokens[i + 1]) |
| 56 | except ValueError: |
| 57 | # Edge Case: Token after operator is not a number |
| 58 | raise ValueError("syntax error") |
| 59 | |
| 60 | # Apply the operation |
| 61 | if op == "plus": |
| 62 | result += num |
| 63 | elif op == "minus": |
| 64 | result -= num |
| 65 | elif op == "multiplied": |
| 66 | result *= num |
| 67 | elif op == "divided": |
| 68 | result //= num # Integer division as per examples |
| 69 | |
| 70 | # Move to the next pair of operator and number |
| 71 | i += 2 |
| 72 | |
| 73 | # Edge Case: Leftover tokens after processing |
| 74 | if i != len(tokens): |
| 75 | raise ValueError("syntax error") |
| 76 | |
| 77 | return result |
| 78 | # Handled Edge Cases: Empty question, Question doesn't start with "What is", Empty expression after removing "What is" and "?", No tokens, First token is not a number, Operator is missing or duplicated, Missing "by" after "multiplied" or "divided", Missing number after operator, Token after operator is not a number, Unknown operation, Leftover tokens after processing |