Question
Several people are standing in a row and need to be divided into two teams. The first person goes into team 1, the second goes into team 2, the third goes into team 1 again, the fourth into team 2, and so on.
You are given an array of positive integers - the weights of the people. Return an array of two integers, where the first element is the total weight of team 1, and the second element is the total weight of team 2 after the division is complete.
Example
- For
a = [50, 60, 60, 45, 70]
, the output should bealternatingSums(a) = [180, 105]
.
Input/Output
[execution time limit] 4 seconds (py3)
[input] array.integer a
Guaranteed constraints:
1 ≤ a.length ≤ 105
,45 ≤ a[i] ≤ 100
.[output] array.integer
MY_ANSWER
def alternatingSums(a):
team1 = []
team2 = []
for i, v in enumerate(list(a)):
if i % 2 == 0:
team1.append(v)
else:
team2.append(v)
return [sum(team1), sum(team2)]
- 인덱스를 나누었을때 나머지가 0이되면 team1, 나머지가 1이되면 team2로 넣은 다음에 더해준다.
Best_ANSWER
def alternatingSums(a):
return [sum(a[::2]),sum(a[1::2])]
- 시작 위치를 다르게 한 뒤 간격을 2로 설정한 뒤에 홀수 인덱스 , 짝수 인덱스를 구분해준다.