Skip to content

Instantly share code, notes, and snippets.

@tyler-austin
Created June 1, 2017 18:15
Show Gist options
  • Save tyler-austin/32ba5041a8d51b6fd0badda837110e10 to your computer and use it in GitHub Desktop.
Save tyler-austin/32ba5041a8d51b6fd0badda837110e10 to your computer and use it in GitHub Desktop.
Code Fights - alternatingSums

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

  • [time limit] 4000ms (py3)

  • [input] array.integer a

Guaranteed constraints: 1 ≤ a.length ≤ 10, 45 ≤ a[i] ≤ 100.

  • [output] array.integer
from typing import List
ListOfInts = List[int]
class AlternatingSums:
@classmethod
def alternating_sums(cls, data: ListOfInts):
team1, team2 = cls._divide_into_teams(data)
return [sum(team1), sum(team2)]
@classmethod
def _divide_into_teams(cls, data: ListOfInts):
odd, even = list(), list()
for i, num in enumerate(data):
if i % 2 == 0:
even.append(num)
else:
odd.append(num)
return even, odd
def alternatingSums(data: list):
team1, team2 = _divide_into_teams(data)
return [sum(team1), sum(team2)]
def _divide_into_teams(data: list):
odd, even = list(), list()
for i, num in enumerate(data):
if i % 2 == 0:
even.append(num)
else:
odd.append(num)
return even, odd
import unittest
from alternating_sums import AlternatingSums
class TestAlternatingSums(unittest.TestCase):
def test_1(self):
a = [50, 60, 60, 45, 70]
solution = [180, 105]
result = AlternatingSums.alternating_sums(a)
self.assertEqual(result, solution)
def test_2(self):
a = [100, 50]
solution = [100, 50]
result = AlternatingSums.alternating_sums(a)
self.assertEqual(result, solution)
def test_3(self):
a = [80]
solution = [80, 0]
result = AlternatingSums.alternating_sums(a)
self.assertEqual(result, solution)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment