title: "[프로그래머스] 다항식 더하기 Python 파이썬 해설 (Level 0) - 이도훈"
cleanUrl: "programmers/120863"
description: "프로그래머스 Level 0 문제 [다항식 더하기]의 풀이를 정리합니다."
def solution(polynomial):
tokens = polynomial.replace(' ', '').split('+')
xcoeffs = [int(tok[:-1]) if len(tok) > 1 else 1 for tok in tokens if tok.endswith('x')]
xcoeff = None if not xcoeffs else sum(xcoeffs)
consts = [int(tok) for tok in tokens if not tok.endswith('x')]
const = None if not consts else sum(consts)
if xcoeff is None and const is None:
return '0'
elif xcoeff is None:
return f'{const}'
elif const is None:
if xcoeff == 1:
return f'x'
else:
return f'{xcoeff}x'
else:
if xcoeff == 1:
return f'x + {const}'
else:
return f'{xcoeff}x + {const}'
프로그래머스 코딩테스트 연습 https://school.programmers.co.kr/learn/challenges