Coding/Basic Skills(Python)

[Programmers, Level 0] OX Quiz

xeohyuni 2023. 4. 16. 11:37

Description

The addition/subtraction formula "X [operator] Y = Z" is given as a parameter. If the formula is correct, complete the solution function to return the array containing "X" in order if "O" is incorrect.

Restrictions

  • There is always one space between the arithmetic symbol and the number. However, there is no space between the minus sign and the number that displays the negative number.
  • 1 ≤ quiz's length ≤ 10
  • X, Y, and Z are integers consisting of numbers from 0 to 9, respectively, and each number may have one minus sign at the front, which means a negative number.
  • X, Y, and Z do not start with zero.
  • -10,000 ≤ X, Y ≤ 10,000
  • -20,000 ≤ Z ≤ 20,000
  • "Operator" is  either + or -.
Quiz Result
["3 - 4 = -3", "5 + 6 = 11"] ["X", "O"]
["19 - 6 = 13", "5 + 66 = 71", "5 - 15 = 63", "3 - 1 = 2"] ["O", "O", "X", "O"]

Input/Output Example Description

Input/Output Example #1
3 - 4 = -3 is the wrong formula, so "X", and 5 + 6 = 11 is the correct formula, so "O", so return [X], "O".

 

Input/Output Example #2

19 - 6 = 13 is the correct formula, so "O", 5 + 66 = 71 is the correct formula, 5 - 15 = 63 is the wrong formula, and 3 - 1 = 2 is the correct formula, so return ["O", 'O'].

def solution(quiz):
    answer = []
    for q in quiz:
        spl_q = q.split()
        if spl_q[1] == '-':
            if int(spl_q[0]) - int(spl_q[2]) == int(spl_q[4]):
                answer.append("O")
            else:
                answer.append("X")
        if spl_q[1] == '+':
            if int(spl_q[0]) + int(spl_q[2]) == int(spl_q[4]):
                answer.append("O")
            else:
                answer.append("X")
    return answer

 

Discussion

The key point of this probelm is to use split method and using elements to decide whether the equation is correct or incorrect throughly.

I forgot how to use split method in Python because I didn't revise it.

When calculating numbers that are in string type, I need to convert all the string element into integers, and I missed this basic method. 

I should solve more problems related with spliting elements in lists.