Sunday, 27 October 2013

Week4

         In this week class, we learn about recursion and testing function that mutate values. A recursive function is a function that calls itself. We also introduce recursive thinking as an approach to problem solving (Tower of Hanoi). For testing function that mutate values, we learn about unittest, basically we do test by compare the output of the function with the expected output by using some bulif-in function like ‘asserequal’.


def r_sum(l:list) -> int:
    if l == []:
        return 0
    else:
        temp = 0
        for i in l:
            if isinstance(i,list):
                temp = temp + r_sum(i)
            else:
                temp = temp + i
        return temp



#print(r_sum([1,2,[2]]))
#print(sum([1,2,3]))

def remove_shared(l1, l2):
    for v in l2:
        if v in l1:
            l1.remove(v)


l1=[1,2,3,4]
l2=[3,4,5,6]
remove_shared(l1,l2)
print(l1,l2)

import unittest

class TestRemoveShared(unittest.TestCase):
    def test_genereal_case(self):
        list_1 = [1, 2, 3, 4, 5, 6]
        list_2 = [2, 4, 6, 7]
        list_1_expected = [1, 3, 5]
        list_2_expected = [2, 4, 6, 7]

        remove_shared(list_1,list_2)

        self.assertEqual(list_1, list_1_expected)
        self.assertEqual(list_2, list_2_expected)

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

No comments:

Post a Comment