본문 바로가기
문제풀이/Programmers

[프로그래머스💯] 코딩테스트 연습 > 연습문제 > 두 정수 사이의 합 / Python 문제풀이

by 서상혁 2020. 3. 12.

<프로그래머스 문제풀이>

<출처 : 프로그래머스(Programmers)>

 


해답)

 

from functools import reduce


def solution(a, b):
    return reduce(lambda x, y: x+y, range(a, b+1)) if a <= b \
        else reduce(lambda x, y: x+y, range(b, a+1))

 

풀이)

 

* reduce 함수는 이터러블 내의 두 인자씩 계속 계산을 해줍니다. (recursive하게 갑니다.) 

https://codepractice.tistory.com/86

 

(파이썬) functools 모듈의 reduce 함수

functools 모듈의 reduce 함수는 다음과 같다. def reduce(function, iterable, initializer=None): it = iter(iterable) if initializer is None: value = next(it) else: value = initializer for element in it..

codepractice.tistory.com

저는 자바스크립트에 익숙해서 reduce를 써줬는데

파이썬은 그냥 sum(range(a,b+1)) 이런식으로 해도 상관없더군요 ㅎㅎ

reduce 복습한다 생각했습니다~

 

 

* 이 문제 및 로고의 저작권은 Programmers에 있습니다.

출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges

728x90

댓글