MyPoorBrain MyPoorBrain - 2 months ago 32
Python Question

Function that returns a list of the count of positive numbers and sum of negative numbers

I have a problem when I ran my code against the unit test. Any advice would be appreciated. Please find the code below:

def manipulate_data(data):
count = 0
sum1 = 0
new_list = []
for x in data:
if x > 0:
count += 1

if x < 0:
sum1 += x

new_list.append(count)
new_list.append(sum1)

return new_list


The unit test is below:

import unittest

class ManipulateDataTestCases(unittest.TestCase):
def test_only_lists_allowed(self):
result = manipulate_data({})
self.assertEqual(result, 'Only lists allowed', msg='Invalid argument')

def test_it_returns_correct_output_with_positives(self):
result = manipulate_data([1, 2, 3, 4])
self.assertEqual(result, [4, 0], msg='Invalid output')

def test_returns_correct_ouptut_with_negatives(self):
result = manipulate_data([1, -9, 2, 3, 4, -5]);
self.assertEqual(result, [4, -14], msg='Invalid output')


The error I get is:

`Total Specs: 3 Total Failures: 1
1 . test_only_lists_allowed
Failure in line 11, in test_only_lists_allowed
self.assertEqual(result, 'Only lists allowed', msg='Invalid argument')
AssertionError: Invalid argument`

Answer

For the case of {}, the result of manipulate_data is [0,0] try this:

def manipulate_data(data):
    if not isinstance(data, list):
        return 'Only lists allowed'

    count = 0
    sum1 = 0
    new_list = []
    for x in data:
        if x > 0:
            count += 1

        if x < 0:
            sum1 += x

    new_list.append(count)
    new_list.append(sum1)
    return new_list

import unittest

class ManipulateDataTestCases(unittest.TestCase):
  def test_only_lists_allowed(self):
    result = manipulate_data({})
    # print('result: ', result)
    self.assertEqual(result, 'Only lists allowed', msg='Invalid argument')


if __name__ == '__main__':
    unittest.main()