코딩 테스트/Level 0
다항식 더하기
컴닥
2022. 11. 8. 16:36
반응형
https://school.programmers.co.kr/learn/courses/30/lessons/120863
코딩테스트는 알고리듬 문제와 구현 문제로 나눌 수 있다,
레벨 0의 구현은 어렵지 않으므로 가독성에 신경 써서 깔끔하게 정리하면 된다.
temp 리스트에 x항과 상수항을 각각 분리.
분리된 항의 계수의 합을 구함.
각각의 항을 텍스트로 변환 후 기호를 넣어 병합.
파이썬
def solution(polynomial):
coefficients = [0, 0] # 계수들
terms = polynomial.split(' + ')
for term in terms:
if term[-1] == 'x': # 항의 마지막 글자가 x면
t = term[:-1] # 항의 마지막 글자를 제외한 부분
if t: # t가 ''이 아니면
coefficients[0] += int(t)
else: # 'x'
coefficients[0] += 1
else: # 상수항
coefficients[1] += int(term)
result = []
if coefficients[0]: # x항의 계수
if coefficients[0] == 1: # x항이 1인 경우 1을 생략해야 함.
result.append('x')
else:
result.append(f'{coefficients[0]}x')
if coefficients[1]: # 상수항
result.append(f'{coefficients[1]}')
return ' + '.join(result) # 병합
if문을 가볍게...
conditional expression 사용.
타 언어의 3항 연산자와 비슷합니다.
':=' 연산자 사용.
파이썬 3.8부터 사용할 수 있는 연산자로
expression 안에서 변수를 정의하고 바인딩할 수 있는 문법입니다.
:= 는 모양이 바다코끼리를 닮았다고 해서
바다코끼리 연산자라고도 합니다.
https://int-i.github.io/python/2020-05-29/python-walrus-operator/
원래 수학에서 =는 동등의 의미죠?
초창기 컴퓨터 언어에서도 동등은 =로,
대입(바인딩)은 :=으로 표현했는데...
코딩에는 동등보다 대입을 많이 쓰다 보니,
동등은 ==, 대입은 =이 되었다는 썰이 있습니다.
def solution(polynomial):
coefficients = [0, 0]
for term in polynomial.split(' + '):
if term[-1] == 'x':
coefficients[0] += int(t if (t := term[:-1]) else 1)
else:
coefficients[1] += int(term)
result = []
if coefficients[0]:
result.append('x' if coefficients[0] == 1 else f'{coefficients[0]}x')
if coefficients[1]:
result.append(f'{coefficients[1]}')
return ' + '.join(result)
주의: '1x'라는 표현은 쓰지 못함.
def solution(polynomial):
coefficients = [0, 0]
for term in polynomial.split(' + '):
if term[-1] == 'x':
coefficients[0] += int(1 if len(term) == 1 else term[:-1])
else:
coefficients[1] += int(term)
result = []
if coefficients[0]:
result.append('x' if coefficients[0] == 1 else f'{coefficients[0]}x')
if coefficients[1]:
result.append(f'{coefficients[1]}')
return ' + '.join(result)
코틀린
class Solution {
fun solution(polynomial: String): String {
val counter = mutableListOf(0, 0)
for (each in polynomial.split(" + "))
if (each[each.length - 1] == 'x')
counter[0] += if (each.length == 1) 1 else each.slice(0..(each.length - 2)).toInt()
else
counter[1] += each.toInt()
return "${
if (counter[0] == 0) "" else if (counter[0] == 1) "x" else "${counter[0]}x"
}${
if (counter[0] * counter[1] == 0) "" else " + "
}${
if (counter[1] == 0) "" else "${counter[1]}"
}"
}
}
class Solution {
fun solution(polynomial: String): String {
val counter = mutableListOf(0, 0)
for (each in polynomial.split(" + "))
if (each[each.length - 1] == 'x')
counter[0] += if (each.length == 1) 1 else each.slice(0..(each.length - 2)).toInt()
else
counter[1] += each.toInt()
val result = mutableListOf<String>()
if (counter[0] > 0)
result.add("${if (counter[0] == 1) "" else counter[0]}x")
if (counter[1] > 0)
result.add("${counter[1]}")
return result.joinToString(" + ")
}
}
반응형