본문 바로가기

Python

[Python/level 1] 자릿수 더하기 - 12931, map, sum

문제 설명

자연수 N이 주어지면, N의 각 자릿수의 합을 구해서 return 하는 solution 함수를 만들어 주세요.
예를들어 N = 123이면 1 + 2 + 3 = 6을 return 하면 됩니다.

 

map

  • map(function, iterables)
Parameter Description
function Required. The function to execute for each item
항목별로 실행할 기능
iterable Required. A sequence, collection or an iterator object. You can send as many iterables as you like, just make sure the function has one parameter for each iterable.
반복할 매개변수
def myfunc(a, b):
  return a + b
x = map(myfunc, ('apple', 'banana', 'cherry'), ('orange', 'lemon', 'pineapple'))
print(list(x))
# 실행결과: ['appleorange', 'bananalemon', 'cherrypineapple']

 

 

 

Sum 함수의 사용 범위

  • 리스트뿐만 아니라 튜플, 집합, 딕셔너리, 문자열, map 객체 등 여러 가지 이터러블 객체에서 사용할 수 있습니다.
  • 이터러블 객체: Python에서 반복이 가능한 객체, 즉 하나씩 순회할 수 있는 개체를 말합니다. (특징: for문을 사용할 수 있음)

 

 code - 1차

def solution(n):
    nList = list(map(int, str(n)))
    return (sum(nList))
  • 코드 설명
    • nList = list(map(int, str(n)))
      • str(n): n을 한 자리씩 받와야 하는데, n이 int 값이므로 str으로 변경합니다.
      • map: str으로 변경한 n의 값을 다시 int로 변경합니다.
      • list: map 함수로 반환한 결과값을 list에 저장합니다.
    • sum(nList)
      • nList의 값을 한번에 더합니다.

 

 code - 2차

def solution(n):
    return sum(map(int, str(n)))
  • 코드 설명
    • sum(map(int, str(n)))
      • map 객체에서도 sum을 사용할 수 있다는 점을 참고하여 각 자리수의 int값을 한번에 더합니다.

 

반응형