자연수 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의 값을 한번에 더합니다.
- nList = list(map(int, str(n)))
code - 2차
def solution(n):
return sum(map(int, str(n)))
- 코드 설명
- sum(map(int, str(n)))
- map 객체에서도 sum을 사용할 수 있다는 점을 참고하여 각 자리수의 int값을 한번에 더합니다.
- sum(map(int, str(n)))
https://github.com/seonmin5/codingtest_Python
GitHub - seonmin5/codingtest_Python
Contribute to seonmin5/codingtest_Python development by creating an account on GitHub.
github.com
반응형
'Python' 카테고리의 다른 글
[Python/level 0] 최댓값 만들기 (1) - 120847, sort(), sort(reverse=True) (1) | 2024.08.17 |
---|---|
[Python/level 1] 자연수 뒤집어 배열로 만들기 - 12932, reversed() (1) | 2024.08.17 |
[Python/level 0] 주사위의 개수 - 120845, list (0) | 2024.08.07 |
[Python/level 1] 문자열 내 p와 y의 개수 - 12916, count() (1) | 2024.08.07 |
[Python/level 0] 문자열 정수의 합 - 181849, sum, 리스트 컴프리헨션 (0) | 2024.08.03 |