Coding/Programmers

[코딩테스트 입문] 다항식 더하기(Python3)

Soo_buglosschestnut 2022. 11. 21. 19:25

[코딩테스트 입문] 다항식 더하기(Python3)


이번에는 57% 인거 도전ㅎㅎ!

 

https://school.programmers.co.kr/learn/courses/30/lessons/120863?language=python3 

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

def solution(polynomial):
    a = polynomial.split(' ')
    num = 0
    num_int = 0
    r = [s for s in a if "x" in s]

    for i in range(len(r)):
        if r[i] == 'x':
            num +=1
        else:
            x_n = r[i].split('x')
            num += int(x_n[0])

    a_sub_b = [w for w in a if w not in r]

    for i in range(len(a_sub_b)):
        if '+' not in a_sub_b[i] :
            num_int += int(a_sub_b[i])
    
    if num_int == 0:
        if num == 1:
            answer = 'x'
        elif num == 0:
            answer = '0'
        else:
            answer = str(num)+'x'
    else:
        if num == 1:
            answer = 'x + '+str(num_int)
        elif num == 0:
            answer = str(num_int)
        else:
            answer = str(num)+'x + '+str(num_int)
    return answer

나는 split으로 쪼개서 했고, 마지막에 x가 혼자인 식일때, 상수항만있을때, 주어진 다항식이 0일때 등등 고려해서 if else문으로 answer값을 return 해줬다. (질문하기에서 도움 좀 받았음 !!)

 

다른 사람의 풀이 보는데 re라는 모듈을 사용한 사람도 있고 그래서 신기방기 

이번주는 python 문법들과 모듈들을 조금씩 정리해보는 시간을 가지려한다!

 

def solution(polynomial):
    coef = 0
    const = 0
    for term in polynomial.split(' + '):
        if 'x' in term:
            if len(term) != 1:
                coef += int(term[:-1]) - 1
            coef += 1 
        else:
            const += int(term)
    answer = []
    if coef != 0:
        answer.append('x' if coef == 1 else f'{coef}x')
    if const != 0:
        answer.append(str(const))
    return ' + '.join(answer) if answer else '0'

{~~~~}이렇게 쓰는건 또 뭣인고..! 기억에 없다ㅎㅎ

 

from functools import reduce
def solution(polynomial):
    result = reduce(lambda hap, x: [hap[0]+int(x[:-1] or "1"), hap[1]] if x[-1]=="x" else [hap[0], hap[1]+int(x)],polynomial.split(" + "), [0, 0])
    return (f"{result[0] if result[0] > 1 else ''}x" if result[0] != 0 else "") + ("" if result[0]==0 or result[1]==0 else " + ") + (f"{result[1]}" if result[1] > 0 or result[0]==0 else "")

reduce는 또 뭘까! 열심히 공부해야겠다~