티스토리 뷰

Codesignal

code signal - 14. alternatingSums

터보건 2020. 2. 10. 00:05

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 be alternatingSums(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로 설정한 뒤에 홀수 인덱스 , 짝수 인덱스를 구분해준다.

 

'Codesignal' 카테고리의 다른 글

code signal - 16. Are similar?  (0) 2020.02.16
code signal - 15. Add Border  (0) 2020.02.16
code signal - 13. reverseInParentheses  (0) 2020.02.09
code signal - 12. Sort by Height  (0) 2020.01.29
code signal - 11. isLucky  (0) 2020.01.29
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
글 보관함