우선 처음 문제를 보고 생각한점은 a+b=c라면 a,b,c,를 전부 list를 만들어서 append를 한다.
그리고 기호가 + 일때는 if a+b==c return "O"
-일때는 a-b == c return "O"을 한다면 된다고 생각헀다.
def solution(quiz):
answer = []
before = []
after = []
result = []
first = []
last = []
k = []
for i in quiz:
answer.append(i.replace(' ',''))
for i in range(len(answer)):
for j in range(len(answer[i])):
if (answer[i][j] == '='):
result.append(answer[i][j+1:])
last.append(j)
break
elif (answer[i][j] == '+' or answer[i][j] == '-'):
after.append(answer[i][:j])
first.append(j)
for i in range(len(answer)):
if i < len(first) and i < len(last):
value = answer[i][first[i]:last[i]].replace('+','')
before.append(value)
for i in range(len(quiz)):
if int(after[i])+int(before[i]) == int(result[i]):
k.append("O")
else:
k.append("X")
return k
하지만 코드를 이렇게 작성할 경우에는 ValueError: invalid literal for int() with base 10: 시간을 초과하게 된다.
케이스를 찾아보니 -5 - -5 = 0일떄 -기호가 총 3번 나오게 된다. 하지만 위의 경우에서는 부호를 신경쓰지않고
-5-5로 판정되기때문에 오류가 발생했다.
def solution(quiz):
answer = []
for i in range(len(quiz)):
result = quiz[i].split(" ")
if result[1] == '+' and int(result[0])+int(result[2]) == int(result[4]):
answer.append("O")
elif result[1] == '-' and int(result[0])-int(result[2]) == int(result[4]):
answer.append("O")
else:
answer.append("X")
return answer
코드를 다시 작성하였다. result를 통해 a+b=c의 경우일때
result[0] = a,result[1] = (+or-),result[2] = b,result[3] = c 이다
그래서 result[1]을 기준으로 result[0] +or- result[2] = result[3]가 True일떈 answer.append("O")
else: answer.append("X")를 해주면 된다
'코딩테스트' 카테고리의 다른 글
프로그래머스 옹알이 (1) level0 python (0) | 2024.07.21 |
---|---|
프로그래머스 겹치는 선분의 길이 level0 python (0) | 2024.07.20 |
프로그래머스 주사위 게임 3 level0 python (0) | 2024.07.17 |
프로그래머스 level0 캐릭터의 좌표 (0) | 2024.07.15 |
프로그래머스 level0 숨어있는 숫자의 덧셈 (2) (0) | 2024.07.14 |