Exemplo n.º 1
0
 def setUp(self):
     """setup object to test"""
     self.ll = UnorderedList()
     #create a list with max index 3
     self.ll.add("ett")
     self.ll.add("två")
     self.ll.add("tre")
Exemplo n.º 2
0
    def test_insert(self):
        """ Test insert method. """

        # Raise ValueExistentError.
        self.ulist = UnorderedList()
        with self.assertRaises(ValueExistentError):
            self.ulist.insert(0, "test")

        # Raise IndexOutOfRangeError.
        self.ulist.add("test node")
        with self.assertRaises(IndexOutOfRangeError):
            self.ulist.insert(-1, "test")
        with self.assertRaises(IndexOutOfRangeError):
            self.ulist.insert(1, "test")
Exemplo n.º 3
0
 def setUp(cls):
     cls.ul = UnorderedList()
     cls.ul.append(5)
     cls.ul.append(7)
     cls.ul.append(9)
     cls.ul.append(7)
     cls.ul.append(6)
     cls.ul.append("Last one")
Exemplo n.º 4
0
    def __init__(self):
        "init method, creats list class"
        self.node_list = UnorderedList()

        while True:
            self.menu()

            choice = input("Välj ett alternativ ")
            while not self.try_input(choice):
                print(" input måste vara en siffra")
                choice = input("Välj ett alternativ ")

            choice = int(choice)

            if choice == 1:
                self.choice_one()

            if choice == 2:
                self.choice_two()

            if choice == 3:

                self.choice_three()

            if choice == 4:
                self.choice_four()

            if choice == 5:
                self.choice_five()

            if choice == 6:
                self.choice_six()

            if choice == 7:
                self.choice_seven()

            if choice == 8:
                self.choice_eight()

            if choice == 9:
                self.choice_nine()

            if choice == 10:
                break
Exemplo n.º 5
0
    def __init__(self):
        """ Ctor. """

        self.ulist = UnorderedList()
        self.choices = {
            "1": self.ulist.is_empty,
            "2": self.ulist.add,
            "3": self.ulist.insert,
            "4": self.ulist.set,
            "5": self.ulist.size,
            "6": self.ulist.get,
            "7": self.ulist.index_of,
            "8": self.ulist.print_list,
            "9": self.ulist.remove,
            "a": self.ulist.add_random_items,
            "i": sort.insertion_sort,
            "b": sort.bubble_sort,
            "0": "Program terminated.",
        }
Exemplo n.º 6
0
class TestList(unittest.TestCase):
    """ Test Class """

    studlist = UnorderedList()

    def test_a_empty_list(self):
        """ Test is_empty() """
        self.assertEqual(self.studlist.is_empty(), True)

    def test_b_nr_of_elements(self):
        """ Test size() and add() """
        self.studlist.add(30)
        self.studlist.add(55)
        self.studlist.add(10)
        self.studlist.add(25)
        self.studlist.add(40)

        self.assertEqual(self.studlist.size(), 5)

    def test_c_set_data(self):
        """ Test set() and get()"""
        self.studlist.set(3, 999)
        self.assertEqual(self.studlist.get(3), 999)

    def test_d_search(self):
        """ Test search() """
        self.assertTrue(self.studlist.search(25))
        self.assertFalse(self.studlist.search(888))

    def test_e_remove(self):
        """ Test remove() """
        current_size = self.studlist.size()
        self.assertTrue(self.studlist.search(30))
        self.studlist.remove(30)
        self.assertFalse(self.studlist.search(30))
        self.assertNotEqual(current_size, self.studlist.size())
Exemplo n.º 7
0
class TestList(unittest.TestCase):
    """ Submodule for unittests, derives from unittest.TestCase. """
    first_node_value = "one"
    second_node_value = "two"
    third_node_value = "three"
    fourth_node_value = "four"

    def setUp(self):
        """ Create object for all tests """
        # Arrange
        self.list = UnorderedList()

    def tearDown(self):
        """ Remove dependencies after test """
        self.list = None

    def test_list_append(self):
        """Test append node."""
        self.list.append(TestList.first_node_value)
        self.assertIsInstance(self.list.head, Node)
        self.list.append(TestList.second_node_value)
        self.assertIsInstance(self.list.tail, Node)
        self.assertEqual(self.list.head.data,
                         TestList.first_node_value,
                         msg='Head.data: {0}'.format(self.list.head.data))
        self.assertEqual(self.list.tail.data, TestList.second_node_value)
        self.assertIs(self.list.head.next, self.list.tail)

    def test_list_set_valid(self):
        """Test set node with valid index."""
        self.list.append(TestList.first_node_value)
        self.list.append(TestList.second_node_value)
        self.list.append(TestList.third_node_value)
        self.list[0] = TestList.fourth_node_value
        self.assertEqual(self.list.head.data,
                         TestList.fourth_node_value,
                         msg='Head.data: {0}'.format(self.list.head.data))
        # self.assertEqual(self.list.tail.data, TestList.second_node_value)

    def test_list_set_invalid(self):
        """Test set node with invalid index."""
        with self.assertRaises(ListIndexError) as _:
            self.list[0] = TestList.first_node_value
        self.list.append(TestList.first_node_value)
        with self.assertRaises(ListIndexError) as _:
            self.list[1] = ""

    def test_list_get(self):
        """Test get node."""
        with self.assertRaises(ListIndexError) as _:
            print(self.list[0])
        self.list.append(TestList.first_node_value)
        self.list.append(TestList.second_node_value)
        self.list.append(TestList.third_node_value)
        with self.assertRaises(ListIndexError) as _:
            print(self.list[3])
        self.assertEqual(self.list[2], TestList.third_node_value)

    def test_list_index_of(self):
        """Test index_of."""
        with self.assertRaises(ListValueError) as _:
            self.list.index_of("a")
        self.list.append(TestList.first_node_value)
        self.list.append(TestList.second_node_value)
        self.list.append(TestList.third_node_value)
        self.assertEqual(self.list.index_of(TestList.third_node_value), 2)
        with self.assertRaises(ListValueError) as _:
            self.list.index_of("a")

    def test_list_remove(self):
        """Test index_of."""
        with self.assertRaises(ListIndexError) as _:
            self.list.remove("a")
        self.list.append(TestList.first_node_value)
        self.list.append(TestList.second_node_value)
        self.list.append(TestList.third_node_value)
        # remove middle value and test if shifted to the left
        self.list.remove(TestList.second_node_value)
        self.assertEqual(self.list.index_of(TestList.third_node_value), 1)
        with self.assertRaises(ListValueError) as _:
            self.list.remove(TestList.second_node_value)
        # test adding again (had problem with it before)
        self.list.append(TestList.fourth_node_value)
        self.assertEqual(self.list.index_of(TestList.fourth_node_value), 2)
Exemplo n.º 8
0
class TestEx(unittest.TestCase):
    """test exeptions in method in undorderlist.py"""
    def setUp(self):
        """setup object to test"""
        self.ll = UnorderedList()
        #create a list with max index 3
        self.ll.add("ett")
        self.ll.add("två")
        self.ll.add("tre")

    #insert, set, get, index_of och remove.

    def test_insert(self):
        """test exceptions in method insert"""
        #test insert value at index 4
        with self.assertRaises(AttError):
            self.ll.insert("fjärde värdet", 4)

    def test_set(self):
        """test exception in method set """
        #test replace at index 4.
        with self.assertRaises(AttError):
            self.ll.set("new fourth value", 4)

    def test_get(self):
        """test exception in method get """
        #test get data from index 4
        with self.assertRaises(OutOfIndex):
            self.ll.get(4)

    def test_index_of(self):
        """test exception method index_of"""
        #test with random value
        with self.assertRaises(NoValue):
            self.ll.index_of("find me")

    def test_remove(self):
        """test exception method remove"""
        #test with no value
        with self.assertRaises(NoValue):
            self.ll.remove("remove me")
        #add the value
        self.ll.add("remove me")
        with self.assertRaises(NoValue):
            #remove the value. should result in fail in test.
            self.ll.remove("remove me")
Exemplo n.º 9
0
class TestUnorderedList(unittest.TestCase):
    """ Test class for UnorderedList. """
    def setUp(self):
        """ Setup the objects. """

        self.ulist = UnorderedList()
        self.ulist.add("test node")

    def tearDown(self):
        """ Remove the objects. """

        self.ulist = None

    def test_insert(self):
        """ Test insert method. """

        # Raise ValueExistentError.
        self.ulist = UnorderedList()
        with self.assertRaises(ValueExistentError):
            self.ulist.insert(0, "test")

        # Raise IndexOutOfRangeError.
        self.ulist.add("test node")
        with self.assertRaises(IndexOutOfRangeError):
            self.ulist.insert(-1, "test")
        with self.assertRaises(IndexOutOfRangeError):
            self.ulist.insert(1, "test")

    def test_set(self):
        """ Test set method. """

        with self.assertRaises(IndexOutOfRangeError):
            self.ulist.set(-1, "test")
        with self.assertRaises(IndexOutOfRangeError):
            self.ulist.set(1, "test")

    def test_get(self):
        """ Test get method. """

        with self.assertRaises(IndexOutOfRangeError):
            self.ulist.get(-1)
        with self.assertRaises(IndexOutOfRangeError):
            self.ulist.get(1)

    def test_index_of(self):
        """ Test index_of method. """

        with self.assertRaises(ValueExistentError):
            self.ulist.index_of("test node ")

    def test_remove(self):
        """ Test remove method. """

        with self.assertRaises(ValueExistentError):
            self.ulist.index_of(" test node")

    def test_populated_list_bubble_sort(self):
        """ Test lists are same after sorting. """

        print()

        lst = [1, 3, 4, 8, 9]

        self.ulist.remove("test node")
        self.ulist.add(9)
        self.ulist.add(1)
        self.ulist.add(4)
        self.ulist.add(3)
        self.ulist.add(8)

        sort.bubble_sort(self.ulist)

        current_node = self.ulist.head

        for item in lst:
            if current_node.next != None:
                self.assertEqual(item, current_node.data)
            current_node = current_node.next

    def test_empty_list_bubble_sort(self):
        """ Test if list is empty after sorting. """

        self.ulist.remove("test node")

        sort.bubble_sort(self.ulist)

        self.assertTrue(self.ulist.is_empty())
Exemplo n.º 10
0
 def __init__(self):
     """initate object"""
     self.uol = UnorderedList()
     self.uol.add('ett')
     self.uol.add('två')
Exemplo n.º 11
0
    def setUp(self):
        """ Setup the objects. """

        self.ulist = UnorderedList()
        self.ulist.add("test node")
Exemplo n.º 12
0
#!/usr/bin/env python3
""" Main file """

from unorderedlist import UnorderedList

ul = UnorderedList()

ul.add(20)
ul.add(10)
ul.add(30)
ul.add(40)
ul.add(50)

ul.print_list()
Exemplo n.º 13
0
class TestUnorderedList(unittest.TestCase):
    "initiation of test class."
    node_1 = 1
    node_2 = 2
    node_3 = 3

    def setUp(self):
        """ Create object for all tests """
        self.node_list = UnorderedList()

    def tearDown(self):
        """ Remove dependencies after test """
        self.node_list = None

    def test_append(self):
        """
        Test that one can add a node to the list.
        """
        self.node_list.append(TestUnorderedList.node_1)
        self.node_list.append(TestUnorderedList.node_2)
        self.node_list.append(TestUnorderedList.node_3)

        self.assertIsInstance(self.node_list.head, Node)
        self.assertEqual(self.node_list.head.data, TestUnorderedList.node_3)

    def test_set_correct(self):
        """
        Test that one can change value of node in list.
        """
        self.node_list.append(TestUnorderedList.node_1)
        self.node_list.append(TestUnorderedList.node_2)
        self.node_list.append(TestUnorderedList.node_3)

        self.node_list.set(1, 10)
        self.assertEqual(self.node_list.head.next.data, 10)

    def test_set_fail(self):
        """
        Test that exception raises when changing value for empty list
        and when index not exist.
        """

        with self.assertRaises(EmptyListException) as _:
            self.node_list.set(1, 10)

        self.node_list.append(TestUnorderedList.node_1)
        self.node_list.append(TestUnorderedList.node_2)
        self.node_list.append(TestUnorderedList.node_3)

        with self.assertRaises(IndexErrorException) as _:
            self.node_list.set(5, 10)

    def test_get_correct(self):
        """
        Test that get method returns the correct value of index.
        """
        self.node_list.append(TestUnorderedList.node_1)
        self.node_list.append(TestUnorderedList.node_2)
        self.node_list.append(TestUnorderedList.node_3)

        self.node_list.get(1)
        self.assertEqual(self.node_list.get(1), TestUnorderedList.node_2)

    def test_get_fail(self):
        """
        Test that get method raises exeptions when list empty and index dont exist.
        """
        with self.assertRaises(EmptyListException) as _:
            self.node_list.get(1)

        self.node_list.append(TestUnorderedList.node_1)
        self.node_list.append(TestUnorderedList.node_2)
        self.node_list.append(TestUnorderedList.node_3)

        with self.assertRaises(IndexErrorException) as _:
            self.node_list.get(4)

    def test_index_of_correct(self):
        """
        Test that index_of method returns the correct value.
        """
        self.node_list.append(TestUnorderedList.node_1)
        self.node_list.append(TestUnorderedList.node_2)
        self.node_list.append(TestUnorderedList.node_3)

        self.assertEqual(self.node_list.index_of(1), 2)

    def test_index_of_fail(self):
        """
        Test that that index_of method raises exeptions,
         when list empty and value dont exist.
        """
        with self.assertRaises(EmptyListException) as _:
            self.node_list.index_of(1)

        self.node_list.append(TestUnorderedList.node_1)
        self.node_list.append(TestUnorderedList.node_2)
        self.node_list.append(TestUnorderedList.node_3)

        with self.assertRaises(KeyErrorException) as _:
            self.node_list.index_of(5)

    def test_remove_correct_onenode(self):
        """
        Test that remove method returns correct with one node in list.
        """
        self.node_list.append(TestUnorderedList.node_1)
        self.node_list.remove(1)

        self.assertEqual(self.node_list.head, None)
        self.assertEqual(self.node_list.last, None)

    def test_remove_correct_nodelist(self):
        """
        Test that remove method returns the correct value in list of nodes.
        when removing first, middle and last node. """
        self.node_list.append(TestUnorderedList.node_1)
        self.node_list.append(TestUnorderedList.node_2)
        self.node_list.append(TestUnorderedList.node_3)

        self.node_list.remove(3)
        self.assertEqual(self.node_list.head.data, 2)

        self.node_list.append(3)
        self.node_list.remove(2)
        self.assertEqual(self.node_list.head.next.data, 1)

        self.node_list.append(2)
        self.node_list.remove(1)
        self.assertEqual(self.node_list.last.data, 3)

    def test_remove_fail(self):
        """
        Test that remove method raises exception when list empty and value
        not found."""
        with self.assertRaises(EmptyListException) as _:
            self.node_list.remove(1)

        self.node_list.append(TestUnorderedList.node_1)
        self.node_list.append(TestUnorderedList.node_2)
        self.node_list.append(TestUnorderedList.node_3)

        with self.assertRaises(KeyErrorException) as _:
            self.node_list.remove(5)

    def test_recursive_sort_correct(self):
        """
        Test that recursive insertion sort function returns correct.
        """
        self.node_list.append(TestUnorderedList.node_1)
        self.node_list.append(TestUnorderedList.node_2)
        self.node_list.append(TestUnorderedList.node_3)

        n = self.node_list.size()

        recursive_insertion_sort(self.node_list, n)
        self.assertEqual(self.node_list.print_list(), [1, 2, 3])

    def test_recursive_sort_empty(self):
        """
        Test that recursive insertion sort function returns correct,
        when list empty.
        """
        n = self.node_list.size()
        self.assertEqual(recursive_insertion_sort(self.node_list, n), None)

    def test_recursive_sort_one_element(self):
        """
        Test that recursive insertion sort function returns correct,
        when list has 1 element.
        """
        self.node_list.append(TestUnorderedList.node_1)
        n = self.node_list.size()
        self.assertEqual(recursive_insertion_sort(self.node_list, n), None)
Exemplo n.º 14
0
class TestSort(unittest.TestCase):
    """ Submodule for unittests, derives from unittest.TestCase """
    def setUp(self):
        """ Create list """

        self.unordered_list = UnorderedList()

    def tearDown(self):
        """ Remove dependencies after test """

        self.unordered_list = []

    def test_list_ordered(self):
        """ Test Bubble Sort """

        self.unordered_list.add(8)
        self.unordered_list.add(2)
        self.unordered_list.add(4)

        # First test so the unordered list is following the pattern
        # 8 -> 2 -> 4
        current_node = self.unordered_list.head
        self.assertEqual(current_node.data, 8)
        current_node = current_node.next
        self.assertEqual(current_node.data, 2)
        current_node = current_node.next
        self.assertEqual(current_node.data, 4)

        # Bubble sort the list order should now be
        # 2 -> 4 -> 8
        bubble_sort(self.unordered_list)

        current_node = self.unordered_list.head
        self.assertEqual(current_node.data, 2)
        current_node = current_node.next
        self.assertEqual(current_node.data, 4)
        current_node = current_node.next
        self.assertEqual(current_node.data, 8)

    def test_list_ordered_str(self):
        """ Test Bubble Sort with string values """

        self.unordered_list.add("c")
        self.unordered_list.add("b")
        self.unordered_list.add("a")

        # First test so the unordered list is following the pattern
        # c -> b -> a
        current_node = self.unordered_list.head
        self.assertEqual(current_node.data, "c")
        current_node = current_node.next
        self.assertEqual(current_node.data, "b")
        current_node = current_node.next
        self.assertEqual(current_node.data, "a")

        # Bubble sort the list order should now be
        # a -> b -> c
        bubble_sort(self.unordered_list)

        current_node = self.unordered_list.head
        self.assertEqual(current_node.data, "a")
        current_node = current_node.next
        self.assertEqual(current_node.data, "b")
        current_node = current_node.next
        self.assertEqual(current_node.data, "c")
Exemplo n.º 15
0
class Handler():
    """handle the linked list"""
    def __init__(self):
        """initate object"""
        self.uol = UnorderedList()
        # self.uol.add(3)
        # self.uol.add(1)
        # self.uol.add(2)
        # self.uol.add("anna")
        # self.uol.add("cindy")
        # self.uol.add("bertil")

    def handle_is_empty(self):
        """1 is_empty: Returnera True/False för om listan är tom eller inte."""
        print('Is list empty? {}'.format(self.uol.is_empty()))
        return True

    def handle_add(self):
        """ 2 add: Lägg till nytt element/nod sist i listan."""
        value = (input('Add: '))
        self.uol.add(value)
        return True

    def handle_insert(self):
        """3 insert: Lägg till nytt element/nod på specifikt index.
        Om index inte finns lyft exception."""
        value = (input("New value: "))

        try:
            i = int(input("At index: "))
            self.uol.insert(value, i)
        except (ValueError, WrongType):
            print("Not an integer, try again!")
        except AttError:
            print("No value at that index.")

        return True

    def handle_set(self):
        """4 set: Skriv över element med ny data som finns på index.
        Om index inte finns lyft exception."""
        value = (input("New value: "))

        try:
            i = int(input("At index: "))
            self.uol.set(value, i)

        except (ValueError, WrongType):
            print("Not an integer, try again!")
        except AttError:
            print("No element at that index.")

    def handle_size(self):
        """5 size: Returnera antaler element i listan."""
        print('Number of elements in list: {}'.\
        format(self.uol.size()))

    def handle_get(self):
        """6 get: Returnera värde på index.
        Om index inte finns lyft exception."""

        try:
            i = int(input('Get element at index: '))

            element = self.uol.get(i)
            if element:
                print('Data at index: {}, is: {}'.\
                format(i, element))
        except (TypeError, ValueError):
            print("Not an integer, try again!")
        except OutOfIndex:
            print("Out of index.")

    def handle_index_of(self):
        """7 index_of: Om data finns i listan returnera dess index.
        Om nod med data inte finns lyft exception."""
        value = str(input("Get index of: "))
        value.strip()

        try:
            index = self.uol.index_of(value)

            if index:
                print('Your word is at index: {}'.\
                format(index))
        except NoValue:
            print('Could not find your word {}'.\
            format(value))

    def handle_print_list(self):
        """8 print_list: Skriv ut listans innehåll."""
        print(self.uol.print_list())

    def handle_remove(self):
        """9 remove: Ta bort nod med samma data.
        Om nod med data inte finns lyft exception."""

        value = input("Remove: ")
        value.strip()  #remove whitespace

        try:
            self.uol.remove(value)
            print('Removed {}'.format(value))
        except NoValue:
            print('Could not remove {}'.\
            format(value))

    def handle_print_el(self):
        """print elements"""
        self.uol.print_el()

    def handle_insertion_sort(self):
        """sort with insertion_sort() function"""
        print(insertion_sort(self.uol))

    def handle_bubble_sort(self):
        """sort with bubble_sort() function"""
        try:
            print(bubble_sort(self.uol))
        except WrongType:
            return print("Can't sort string.")
        except NoValue:
            return print("There are no elements to sort.")

    def handle_input(self, choice):
        """handle user input"""

        if choice == "1":
            self.handle_is_empty()

        elif choice == "2":
            self.handle_add()

        elif choice == "3":
            self.handle_insert()

        elif choice == "4":
            self.handle_set()

        elif choice == "5":
            self.handle_size()

        elif choice == "6":
            self.handle_get()

        elif choice == "7":
            self.handle_index_of()

        elif choice == "8":
            self.handle_print_list()

        elif choice == "9":
            self.handle_remove()

        elif choice == "10":
            self.handle_insertion_sort()

        elif choice == "11":
            self.handle_bubble_sort()

        else:
            print("invalid choice.")

    def start(self):
        """eternal loop for menu until user shoose q or keyinterrupt"""

        while True:
            print("--------------------------\n" +
                  "1) check if list is empty. Return True/False.\n" +
                  "2) add a new value to the end of the list.\n" +
                  "3) insert new value at a specific index.\n" +
                  "4) replace a value at a specific index.\n" +
                  "5) get number of values in list.\n" +
                  "6) get value at a specific index.\n" +
                  "7) get index of specific value.\n" +
                  "8) print the entire list.\n" +
                  "9) remove node with your value.\n" +
                  "10) sort list using insert_sort.\n" +
                  "11) sort list using bubble.\n" + "q) quit.\n")

            choice = (input("-->  "))
            if choice == "q":
                break
            elif choice is None:
                print("please enter your choice")
                continue
            elif choice == "p":
                self.handle_print_el()
            else:
                self.handle_input(choice)
Exemplo n.º 16
0
class Handler():
    """initiation of Handler class, containging a infinity while loop,
    contaninga meny of all methods in the unorderedlist class"""
    def __init__(self):
        "init method, creats list class"
        self.node_list = UnorderedList()

        while True:
            self.menu()

            choice = input("Välj ett alternativ ")
            while not self.try_input(choice):
                print(" input måste vara en siffra")
                choice = input("Välj ett alternativ ")

            choice = int(choice)

            if choice == 1:
                self.choice_one()

            if choice == 2:
                self.choice_two()

            if choice == 3:

                self.choice_three()

            if choice == 4:
                self.choice_four()

            if choice == 5:
                self.choice_five()

            if choice == 6:
                self.choice_six()

            if choice == 7:
                self.choice_seven()

            if choice == 8:
                self.choice_eight()

            if choice == 9:
                self.choice_nine()

            if choice == 10:
                break

    @staticmethod
    def menu():
        "meny method, gets printed in while loop"

        print('1. Lägg till värde')
        print('2. tar bort en Nod')
        print('3. ändra data för nod')
        print('4. storlek på listan')
        print('5. Returnerar värde på index')
        print('6. Returnerar index av värde')
        print('7. skriver ut listans innehåll')
        print('8. Sortera lista')
        print('9. Sortera lista rekursivt')
        print('10. Avsluta')

    @staticmethod
    def try_input(choice):
        "error handler, checks that input for variable 'choice' is int"
        try:
            int(choice)
            return True
        except ValueError:
            return False

    def choice_one(self):
        """ method for appending element to list"""

        data = input("värde ")
        self.node_list.append(data)

    def choice_two(self):
        """ method for removing element to list"""

        data = input("värde ")
        try:
            self.node_list.remove(data)
        except (KeyErrorException, EmptyListException):
            print("Error: lista tom eller data existerar ej, försök igen")

    def choice_three(self):
        """ method for change value of index element """

        try:
            index = int(input('skriv index på nod du vill byta data på '))
            data = input(' skriv data du vill ändra värdet på ')
        except ValueError:
            print(" value input måste vara siffra ")
            return

        try:
            self.node_list.set(index, data)
        except (IndexErrorException, EmptyListException):
            print("Error: lista tom eller index existerar ej, försök igen")

    def choice_four(self):
        """ method for printing out size of list element to list"""
        print("size ", self.node_list.size())

    def choice_five(self):
        """ returning value of input index"""

        try:
            index = int(input('skriv index på nod du vill returnera värde '))
        except ValueError:
            print("index måste vara en siffra")
            return

        try:
            print(self.node_list.get(index))
        except (IndexErrorException, EmptyListException):
            print("Error: lista tom eller data existerar ej, försök igen")

    def choice_six(self):
        """ returning index of input element"""

        value = input(' skriv värde vars index ska returneras ')

        try:
            print(self.node_list.index_of(value))
        except (KeyErrorException, EmptyListException):
            print("Error: lista tom eller index existerar ej, försök igen")

    def choice_seven(self):
        """ method for printing out all elements in list"""
        print("lista: ", self.node_list.print_list())

    def choice_eight(self):
        """ method for sorting list with insertion_sort"""
        insertion_sort(self.node_list)
        print(self.node_list.print_list())

    def choice_nine(self):
        """ method for sorting list with recursive_insertion_sort"""
        recursive_insertion_sort(self.node_list, self.node_list.size())
        print(self.node_list.print_list())
Exemplo n.º 17
0
class Handler:
    """ Handler class """

    _OPTIONS = {
        "1": "append",
        "2": "set",
        "3": "size",
        "4": "get",
        "5": "index_of",
        "6": "print_list",
        "7": "remove",
        "q": "quit"
    }

    def __init__(self):
        """ Initialize class """
        self.list = UnorderedList()
        self.start()

    def _get_method(self, method_name):
        """
        Uses function getattr() to dynamically get value of an attribute.
        """
        return getattr(self, self._OPTIONS[method_name])

    def _print_menu(self):
        """
        Use docstring from methods to print options for the program.
        """
        menu = ""

        for key in sorted(self._OPTIONS):
            method = self._get_method(key)
            docstring = inspect.getdoc(method)

            menu += "{choice}: {explanation}\n".format(choice=key,
                                                       explanation=docstring)

        print(chr(27) + "[2J" + chr(27) + "[;H")
        print(menu)

    def append(self):
        """ Adds a node to the list. """
        value = input("\nAdd a value: \n>>> ")
        self.list.append(value)
        print(f"{value} has been added.")
        # print("Head.data: '" + self.list.head.data + "'")

    def set(self):
        """Replace value (data) for the node on the index place."""
        index = input("\nIndex: ")
        value = input("Value: ")
        try:
            self.list.set(index, value)
            print(f"{value} has been changed.")
        except ListIndexError as e:
            print(f"Error: {e}")

    def size(self):
        """ Shows the list length. """
        print(self.list.size())

    def get(self):
        """Get data on the index position."""
        index = input("\nEnter index value: ")
        try:
            print(self.list.get(index))
        except ListIndexError as e:
            print(f"Error: {e}")

    def index_of(self):
        """Get the first index of the data."""
        value = input("\nEnter data value: ")
        try:
            print(self.list.index_of(value))
        except ListValueError as e:
            print(f"Error: {e}")

    def print_list(self):
        """Print all nodes in the list."""
        print(self.list.print_list())

    def remove(self):
        """ Removes the first node from the list. """
        value = input("\nEnter data value: ")
        try:
            self.list.remove(value)
            print(f"{value} has been removed.")
        except (ListIndexError, ListValueError) as e:
            print(f"Error: {e}")

    @staticmethod
    def quit():
        """ Quit the program """
        sys.exit()

    def start(self):
        """ Start method """
        while True:
            self._print_menu()
            choice = input("Enter menu selection:\n-> ")

            try:
                self._get_method(choice.lower())()
            except KeyError:
                print("Invalid choice!")

            input("\nPress any key to continue ...")
Exemplo n.º 18
0
 def __init__(self):
     """ Initialize class """
     self.list = UnorderedList()
     self.start()
Exemplo n.º 19
0
class TestList(unittest.TestCase):
    """ Submodule for unittests, derives from unittest.TestCase. """
    first_node_value = "one"
    second_node_value = "two"
    third_node_value = "three"
    fourth_node_value = "four"
    test_list1 = [5, 3, 4, 1, 2]
    test_list2 = ["a", "d", "b", "e", "c"]
    test_list3 = ["a", 5, 3, "e", 1, "abc", 10, 6]
    test_list1_sorted = [1, 2, 3, 4, 5]
    test_list2_sorted = ["a", "b", "c", "d", "e"]
    test_list3_sorted = [1, 3, 5, 6, 10, 'a', 'abc', 'e']

    def setUp(self):
        """ Create object for all tests """
        # Arrange
        self.list = UnorderedList()

    def tearDown(self):
        """ Remove dependencies after test """
        self.list = None

    def test_list_append(self):
        """Test append node."""
        self.list.append(TestList.first_node_value)
        self.assertIsInstance(self.list.head, Node)
        self.list.append(TestList.second_node_value)
        self.assertIsInstance(self.list.tail, Node)
        self.assertEqual(
            self.list.head.data,
            TestList.first_node_value,
            msg='Head.data: {0}'.format(self.list.head.data)
        )
        self.assertEqual(self.list.tail.data, TestList.second_node_value)
        self.assertIs(self.list.head.next, self.list.tail)

    def test_list_set_valid(self):
        """Test set node with valid index."""
        self.list.append(TestList.first_node_value)
        self.list.append(TestList.second_node_value)
        self.list.append(TestList.third_node_value)
        self.list[0] = TestList.fourth_node_value
        self.assertEqual(
            self.list.head.data,
            TestList.fourth_node_value,
            msg='Head.data: {0}'.format(self.list.head.data)
        )
        # self.assertEqual(self.list.tail.data, TestList.second_node_value)

    def test_list_set_invalid(self):
        """Test set node with invalid index."""
        with self.assertRaises(ListIndexError) as _:
            self.list[0] = TestList.first_node_value
        self.list.append(TestList.first_node_value)
        with self.assertRaises(ListIndexError) as _:
            self.list[1] = ""

    def test_list_get(self):
        """Test get node."""
        with self.assertRaises(ListIndexError) as _:
            print(self.list[0])
        self.list.append(TestList.first_node_value)
        self.list.append(TestList.second_node_value)
        self.list.append(TestList.third_node_value)
        with self.assertRaises(ListIndexError) as _:
            print(self.list[3])
        self.assertEqual(self.list[2], TestList.third_node_value)

    def test_list_index_of(self):
        """Test index_of."""
        with self.assertRaises(ListValueError) as _:
            self.list.index_of("a")
        self.list.append(TestList.first_node_value)
        self.list.append(TestList.second_node_value)
        self.list.append(TestList.third_node_value)
        self.assertEqual(self.list.index_of(TestList.third_node_value), 2)
        with self.assertRaises(ListValueError) as _:
            self.list.index_of("a")

    def test_list_remove(self):
        """Test remove element."""
        with self.assertRaises(ListIndexError) as _:
            self.list.remove("a")
        self.list.append(TestList.first_node_value)
        self.list.append(TestList.second_node_value)
        self.list.append(TestList.third_node_value)
        # remove middle value and test if shifted to the left
        self.list.remove(TestList.second_node_value)
        self.assertEqual(self.list.index_of(TestList.third_node_value), 1)
        with self.assertRaises(ListValueError) as _:
            self.list.remove(TestList.second_node_value)
        # test adding again (had problem with it before)
        self.list.append(TestList.fourth_node_value)
        self.assertEqual(self.list.index_of(TestList.fourth_node_value), 2)

    def test_list_insertionsort_all_numeric(self):
        """test_list_insertionsort_all_numeric"""
        for node in self.test_list1:
            self.list.append(node)
        self.list.insertionsort()
        res_list = []
        for i in range(len(self.list)):
            res_list.append(self.list[i])
        self.assertEqual(self.test_list1_sorted, res_list)

    def test_list_insertionsort_all_strings(self):
        """test_list_insertionsort_all_strings"""
        for node in self.test_list2:
            self.list.append(node)
        self.list.insertionsort()
        res_list = []
        for i in range(len(self.list)):
            res_list.append(self.list[i])
        self.assertEqual(self.test_list2_sorted, res_list)

    def test_list_insertionsort_mixed(self):
        """test_list_insertionsort_mixed"""
        for node in self.test_list3:
            self.list.append(node)
        self.list.insertionsort()
        res_list = []
        for i in range(len(self.list)):
            res_list.append(self.list[i])
        self.assertEqual(self.test_list3_sorted, res_list)

    def test_list_recursive_insertionsort_all_numeric(self):
        """test_list_recursive_insertionsort_all_numeric"""
        for node in self.test_list1:
            self.list.append(node)
        self.list.recursive_insertionsort()
        res_list = []
        for i in range(len(self.list)):
            res_list.append(self.list[i])
        self.assertEqual(self.test_list1_sorted, res_list)

    def test_list_recursive_insertionsort_all_strings(self):
        """test_list_recursive_insertionsort_all_strings"""
        for node in self.test_list2:
            self.list.append(node)
        self.list.recursive_insertionsort()
        res_list = []
        for i in range(len(self.list)):
            res_list.append(self.list[i])
        self.assertEqual(self.test_list2_sorted, res_list)

    def test_list_recursive_insertionsort_mixed(self):
        """test_list_recursive_insertionsort_mixed"""
        for node in self.test_list3:
            self.list.append(node)
        self.list.recursive_insertionsort()
        res_list = []
        for i in range(len(self.list)):
            res_list.append(self.list[i])
        self.assertEqual(self.test_list3_sorted, res_list)
Exemplo n.º 20
0
 def setUp(self):
     """ Create object for all tests """
     # Arrange
     self.list = UnorderedList()
Exemplo n.º 21
0
    def setUp(self):
        """ Create object for all tests """

        self.unordered_list = UnorderedList()
        self.unordered_list.add("Patrik")
        self.unordered_list.add("Karlsson")
Exemplo n.º 22
0
 def setUp(self):
     """ Create object for all tests """
     self.node_list = UnorderedList()
from sys import path
path.append('D:\Data_structure\Chapter3')
from unorderedlist import UnorderedList,Node
import timeit

mylist=UnorderedList()
syslist=[]


popmy = timeit.Timer("mylist.add(0)", "from __main__ import mylist")
print("Time for mylist is",popmy.timeit(number=1000))

popsys=timeit.Timer("syslist.append(0)","from __main__ import syslist")
print("Time for syslist is",popsys.timeit(number=1000))
Exemplo n.º 24
0
#!/usr/bin/env python3

"""
Main file for testing
"""
# Imports
from my_bubblesort import bubble_sort
from unorderedlist import UnorderedList

# Create a new list
my_list = UnorderedList()

# Add 10 numbers to the list
my_list.add(56)
my_list.add(89)
my_list.add(34)
my_list.add(76)
my_list.add(78)
my_list.add(13)
my_list.add(32)
my_list.add(234)
my_list.add(2)
my_list.add(1)

# Checks that the list is unsorted in the beginning
my_list.print_list()

# Sort the list
bubble_sort(my_list)

# Checks the structure of the list
Exemplo n.º 25
0
    recursive_insertion_sort(items, n-1)
    # tilldelar sista och näst sita elementet temp-variabler
    last = items.get(n-1)
    j = n-2

    while j >= 0 and items.get(j) > last:
        value_j = items.get(j)
        #value_jplus = items.get(j+1)
        items.set(j+1, value_j)

        j -= 1

    items.set(j+1, last)
    return items




if __name__ == "__main__":

    lista = UnorderedList()
    lista.append(1)
    lista.append(2)
    lista.append(1)
    lista.append(4)
    lista.append(5)
    print(lista.print_list())

    new = (insertion_sort(lista))
    print(new.print_list())
Exemplo n.º 26
0
 def __init__(self):
     """initate object"""
     self.uol = UnorderedList()
Exemplo n.º 27
0
    def __init__(self):
        """ Initialize Unordered List class and start"""

        self.my_list = UnorderedList()
        self.start()
Exemplo n.º 28
0
    def setUp(self):
        """ Create list """

        self.unordered_list = UnorderedList()
Exemplo n.º 29
0
class Handler:
    """ Handler class """



    def __init__(self):
        """ Initialize Unordered List class and start"""

        self.my_list = UnorderedList()
        self.start()



    def start(self):
        """ Start """

        while True:
            print("""
[1] Check if the list is empty
[2] Add value last in list
[3] Insert value at a specific index
[4] Replace value at a specific index
[5] Show size of list
[6] Show value at a specific index
[7] Show index of a specific value
[8] Show all values in the list
[9] Remove node that match value
[exit] Exit
            """)
            val = input('Choice: \n>>> ')

            if val == "1":
                print("\nCheck if the list is empty:")
                print(self.my_list.is_empty())

            elif val == "2":
                print("\nAdd value last in list:")
                data = input("Value: ")
                self.my_list.add(data)

            elif val == "3":
                print("\nInsert value at a specific index:")
                index = input("Index: ")
                data = input("Value: ")

                try:
                    self.my_list.insert(int(index), data)
                except IndexErrorException as e:
                    print(e)

            elif val == "4":
                print("\nReplace value at a specific index:")
                index = input("Index: ")
                data = input("Value: ")

                try:
                    self.my_list.set(int(index), data)
                except IndexErrorException as e:
                    print(e)

            elif val == "5":
                print("\nShow size of list:")
                res = self.my_list.size()
                print(res)

            elif val == "6":
                print("\nShow value at a specific index:")
                data = input("Index: ")

                try:
                    res = self.my_list.get(int(data))
                    print(res)
                except IndexErrorException as e:
                    print(e)

            elif val == "7":
                print("\nShow index by value:")
                data = input("Value: ")

                try:
                    res = self.my_list.index_of(data)
                    print(res)
                except ValueErrorException as e:
                    print(e)

            elif val == "8":
                print("\nShow all values in the list:")
                self.my_list.print_list()
                print(" ")

            elif val == "9":
                print("\nRemove node by value:")
                data = input("Value: ")

                try:
                    self.my_list.remove(data)
                except ValueErrorException as e:
                    print(e)

            elif val == "exit":
                sys.exit()

            else:
                print("No choice that match! try again")
Exemplo n.º 30
0
class TestUnorderedList(unittest.TestCase):
    """ Submodule for unittests, derives from unittest.TestCase """



    def setUp(self):
        """ Create object for all tests """

        self.unordered_list = UnorderedList()
        self.unordered_list.add("Patrik")
        self.unordered_list.add("Karlsson")



    def tearDown(self):
        """ Remove dependencies after test """

        self.unordered_list = None



    def test_insert(self):
        """ Test method insert """
        # List looks like this 0: Patrik 1: Karlsson

        # Trying to insert new value at index 3 and -1 should raise exception
        self.assertRaises(IndexErrorException,
                          self.unordered_list.insert, int(3), "test")
        self.assertRaises(IndexErrorException,
                          self.unordered_list.insert, int(-1), "test")

        # Trying to insert new value at index 0 should work and not raise
        # exception
        self.unordered_list.insert(int(0), "test")
        # 0: test 1: Patrik 2: Karlsson

        # Trying to insert new value at index 3 should work and not raise
        # exception
        self.unordered_list.insert(int(3), "test2")
        # 0: test 1: Patrik 2: Karlsson 3: test2

        # Check if index 0 == test and index 3 = test2
        self.assertEqual(self.unordered_list.get(int(0)), "test")
        self.assertEqual(self.unordered_list.get(int(3)), "test2")



    def test_set(self):
        """ Test method set """

        # Trying to replace new value at index 2 or -1 should raise exception
        self.assertRaises(IndexErrorException,
                          self.unordered_list.set, int(2), "test")
        self.assertRaises(IndexErrorException,
                          self.unordered_list.set, int(-1), "test")

        # Replace a valid index value and check so that the value = new value
        self.unordered_list.set(int(0), "test")
        self.assertEqual(self.unordered_list.get(0), "test")



    def test_get(self):
        """ Test method get """

        # Trying to get value at index 2 or -1 should raise exception
        self.assertRaises(IndexErrorException, self.unordered_list.get, int(2))
        self.assertRaises(IndexErrorException, self.unordered_list.get, int(-1))

        # Test get value at indec 0 and 1 should return Patrik and Karlsson
        self.assertEqual(self.unordered_list.get(int(0)), "Patrik")
        self.assertEqual(self.unordered_list.get(int(1)), "Karlsson")



    def test_index_of(self):
        """ Test index_of method """

        # Trying to get value at index 2 or -1 should raise exception
        self.assertRaises(ValueErrorException,
                          self.unordered_list.index_of, "Patrik_test")
        self.assertRaises(ValueErrorException,
                          self.unordered_list.index_of, "Karlsson_test")

        # Test get index for Patrik and Karlsson should return 0 and 1
        self.assertEqual(self.unordered_list.index_of("Patrik"), 0)
        self.assertEqual(self.unordered_list.index_of("Karlsson"), 1)



    def test_remove(self):
        """ Test remove method """

        # Trying to remove a value that doesnt exist should raise exception
        self.assertRaises(ValueErrorException,
                          self.unordered_list.remove, "test")

        # Before removing items in list should be 2
        self.assertEqual(self.unordered_list.size(), 2)
        self.unordered_list.remove("Patrik")
        # After removing items in list should be 1
        self.assertEqual(self.unordered_list.size(), 1)
        # After removing last item in list, the list shall be emtpy
        self.unordered_list.remove("Karlsson")
        self.assertEqual(self.unordered_list.is_empty(), True)
Exemplo n.º 31
0
class Handler:
    """ Handler class """

    _OPTIONS = {
        "1": "append",
        "2": "set",
        "3": "size",
        "4": "get",
        "5": "index_of",
        "6": "print_list",
        "7": "remove",
        "8": "sort",
        "9": "recursive_sort",
        "a": "recursive_bubblesort",
        "f": "gen_test_list",
        "q": "quit"
    }
    # test_list = [5, 3, 4, 1, 2]
    # test_list = ["a", "d", "b", "e", "c"]
    test_list = ["a", 5, 3, "e", 1, "abc", 10, 6]

    def __init__(self):
        """ Initialize class """
        self.list = UnorderedList()
        self.start()

    def _get_method(self, method_name):
        """
        Uses function getattr() to dynamically get value of an attribute.
        """
        return getattr(self, self._OPTIONS[method_name])

    def _print_menu(self):
        """
        Use docstring from methods to print options for the program.
        """
        menu = ""

        for key in sorted(self._OPTIONS):
            method = self._get_method(key)
            docstring = inspect.getdoc(method)

            menu += "{choice}: {explanation}\n".format(choice=key,
                                                       explanation=docstring)

        print(chr(27) + "[2J" + chr(27) + "[;H")
        print(menu)

    def append(self):
        """Adds a node to the list."""
        value = input("\nAdd a value: \n>>> ")
        if value.isnumeric():
            value = int(value)
        else:
            try:
                value = float(value)
            except ValueError:
                pass
        self.list.append(value)
        print(f"{value} has been added.")
        # print("Head.data: '" + self.list.head.data + "'")

    def set(self):
        """Replace value (data) for the node on the index place."""
        index = input("\nIndex: ")
        value = input("Value: ")
        try:
            self.list.set(index, value)
            print(f"{value} has been changed.")
        except ListIndexError as e:
            print(f"Error: {e}")

    def size(self):
        """ Shows the list length. """
        print(self.list.size())

    def get(self):
        """Get data on the index position."""
        index = input("\nEnter index value: ")
        try:
            print(self.list.get(index))
        except ListIndexError as e:
            print(f"Error: {e}")

    def index_of(self):
        """Get the first index of the data."""
        value = input("\nEnter data value: ")
        try:
            print(self.list.index_of(value))
        except ListValueError as e:
            print(f"Error: {e}")

    def print_list(self):
        """Print all nodes in the list."""
        print(self.list.print_list())

    def remove(self):
        """ Removes the first node from the list. """
        value = input("\nEnter data value: ")
        try:
            self.list.remove(value)
            print(f"{value} has been removed.")
        except (ListIndexError, ListValueError) as e:
            print(f"Error: {e}")

    def sort(self):
        """Sort list (insert)."""
        print("Sorted list: ")
        print(self.list.insertionsort())

    def recursive_sort(self):
        """Sort list Recursively (insert)."""
        print(self.list)
        print("Recursively sorted list: ")
        print(self.list.recursive_insertionsort())

    def recursive_bubblesort(self):
        """Bubblesort list Recursively."""
        print(self.list)
        print("Recursively bubblesorted list: ")
        print(self.list.recursive_bubblesort())

    def gen_test_list(self):
        """Generate test list."""
        if len(self.list) > 0:
            for i in range(len(self.list) - 1, -1, -1):
                self.list.remove(self.list[i])
        for node in self.test_list:
            self.list.append(node)
        print("Generated list: ", self.list)

    @staticmethod
    def quit():
        """ Quit the program """
        sys.exit()

    def start(self):
        """ Start method """
        while True:
            self._print_menu()
            choice = input("Enter menu selection:\n-> ")

            try:
                self._get_method(choice.lower())()
            except KeyError:
                print("Invalid choice!")

            input("\nPress any key to continue ...")