コード例 #1
0
ファイル: Task5.py プロジェクト: GaveenA/Python-Projects
    def __init__(self):
        """
        This method is defined such that the user is allowed to provide the size upon creation.
        If they do not provide size, a default value of 10 is set.

        @:param self: the object
        @Post Condition: Creates an array
        @complexity: Best case O(1), Worst case O(1)
                """

        self.text_lines = ListADT()
コード例 #2
0
def test_getitem():
    """function gets element from a specific index"""
    x = ListADT()
    x.unsafe_set_array([4, 3, 5, 6, None, None], 4)
    # if 4 is in position 0
    assert (x[0] == 4), "Should be 4 but it is" + str(x[0])
    # if 3 is in position 1
    assert (x[1] == 3), "Should be 3 but it is" + str(x[1])
    # if 6 is in position 3
    assert (x[3] == 6), "Should be 6 but it is" + str(x[3])
    try:
        # checks if IndexError raised when index is out of range
        x[7] == 0
        print("Should have raised IndexError")
    except IndexError:
        True
コード例 #3
0
def test_setitem():
    """function sets element in a specific position"""
    x = ListADT()
    x.unsafe_set_array([4, 3, 5, None, None], 3)
    # if value at index 0 is changed to 10
    x[0] = 10
    # if value at  1 is changed to 20
    x[1] = 20
    # if value at  2 is changed to 30
    x[2] = 30
    assert (x[0] == 10), "Should be 10 but it is" + str(x[0])
    assert (x[1] == 20), "Should be 20 but it is" + str(x[1])
    assert (x[2] == 30), "Should be 30 but it is" + str(x[2])
    try:
        # checks if IndexError raised when index is out of range
        x[7] = 0
        print("Should have raised IndexError")
    except IndexError:
        True
コード例 #4
0
ファイル: Task3.py プロジェクト: GaveenA/Python-Projects
def read_text_file(name):
    """
    This Function takes the name of a text file as input and reads each line of text into a string,
    returning a list of strings associated to the file
    (i.e., the function converts the text in the file into a list of strings).
    The function makes use of the List ADT implemented in Task 2 for this, that is,
    the list of strings returned by the function is an object of the ListADT class implemented in Task 2.

    @:param name: name of the text file
    @:return the list of strings created from the content of the text file
    """
    try:
        myfile = open(name)
        string_list = ListADT()

        for i in myfile:
            string_list.append(i.rstrip())
        myfile.close()

        return string_list
    except Exception as error:
        print("Unable to access file: ")
        print(error)
        return None
コード例 #5
0
def test_str():
    """function test string representation of list"""
    x = ListADT()
    # checks if empty string returned for empty ListADT
    assert str(x) == "", "Should be empty string but it is" + str(x)
    x.insert(0, 2)
    # checks if 2 returned
    assert str(x) == "2\n", "Should be a 2 string but it is" + str(x)
    x.unsafe_set_array([1, 2, 3, None, None], 3)
    # Check string containing 1,2,3 returned
    assert str(x) == "1\n2\n3\n", "Should be a 1 2 3 string but it is" + str(x)
コード例 #6
0
def test_contains():
    """function checks whether list contains an element"""
    x = ListADT()
    # checks if 2 in a empty listADT
    assert (2
            in x) == False, "Should be False as x is empty but it is" + str(x)
    x.insert(0, 2)
    # check if numeber 2 present within list containing 2 at index 0
    assert (2 in x), "Should be True as x=[2] but it is" + str(x)
    x.unsafe_set_array([4, 2, 3, None, None], 3)
    # checks if 3 is in list that has 3 as a element
    assert (3 in x), "Should be True as x=[4,2,3] but it is" + str(x)
コード例 #7
0
ファイル: Task5.py プロジェクト: GaveenA/Python-Projects
class Editor:
    def __init__(self):
        """
        This method is defined such that the user is allowed to provide the size upon creation.
        If they do not provide size, a default value of 10 is set.

        @:param self: the object
        @Post Condition: Creates an array
        @complexity: Best case O(1), Worst case O(1)
                """

        self.text_lines = ListADT()

    def read_filename(self, name):
        self.text_lines = read_text_file(name)
        print(self.text_lines.the_array)
        print(self.text_lines.size)

    def is_number(self, s):
        """
        Function returns True if index is number, otherwise returns False

        @:param self: the object
        @:param s: input to be tested if number
        @:return String containing the items of the list or returns the empty string if the list is empty
        @Pre Condition: None
        @Post Condition: True if index is number, False if not number
        @complexity: Best case O(1), Worst case O(1)
        """
        try:
            int(s)  # checking if input s is a integer
            return True  # Return true if integer
        except ValueError:  # ValueError raised if input is not a integer.
            return False  # Return false if not an integer

    def print_num(self, rest_string):
        """
        Function prints line of text at line given by the user.
        And function Prints all lines of text if user inputs empty string.

        @:param self: the object
        @:param rest_string: valid number (integer)
        @Pre Condition: Input should be a valid number
        @Post Condition: Prints line of text at index = rest_string -1
                        or Prints all lines
        @complexity: Best case O(1), Worst case O(1)

        """

        try:
            if self.is_number(
                    rest_string
            ) == True:  # running is_number() on rest_string to check if its a number
                index = int(
                    rest_string)  # index variable assigned to int(rest_string)
                if index == 0:
                    raise IndexError(
                        'Invalid Line Number'
                    )  # index error raised if line number input by user = 0
                elif int(rest_string) < 0 and int(
                        rest_string) >= -self.text_lines.length:
                    index = self.text_lines.length + int(
                        rest_string)  # Converting negative index to positive
                    print("\n\n" +
                          self.text_lines[index])  # printing element at index
                else:
                    index = index - 1  # if index positive,  subtract 1 from index, since index numbers start from 0
                    print("\n\n" +
                          self.text_lines[index])  # printing element at index
            elif rest_string == "":  # check if rest_string is empty string
                length = len(self.text_lines)
                print("\n\n")
                for i in range(length):
                    print(
                        self.text_lines[i]
                    )  # if user inputs empty string, printing all elements in List
            else:
                print("??")
                raise IndexError(
                    "Index is not a Number "
                )  # IndexError raised if index is not a number.
        except Exception as error:  # All Exceptions in Try block are  caught and printed.
            print("??")
            print(error)
            userInput = input(
                "\nEnter Num of line to print (or nothing to print all lines) : "
            )
            self.print_num(
                userInput
            )  # Giving user another chance to enter correct line_number to print

    def delete_num(self, rest_string):
        """
        Function deletes elements at line given by user,
        if the input is empyty it deletes all lines of text.

        @:param self: the object
        @:param rest_string: valid number (integer)
        @Pre Condition: input should be a valid number
        @Post Condition: Deletes the line of text index = rest_string-1
                        Or delets all lines
        @complexity: Best case O(1), Worst case O(n)
        """
        try:
            if self.is_number(
                    rest_string
            ) == True:  # running is_number() on rest_string to check if its a number

                index = int(
                    rest_string)  # index variable assigned to int(rest_string)
                if index == 0:
                    raise IndexError(
                        'Invalid Line Number'
                    )  # index error raised if line number input by user = 0

                #print("Deleted Element: ")

                if int(rest_string) < 0 and int(
                        rest_string) >= -self.text_lines.length:
                    index = self.text_lines.length + int(
                        rest_string)  # Converting negative index to positive
                    self.text_lines.delete(index)  # Deleting element at index
                else:
                    if index >= 1:
                        index = index - 1  # if index positive  subtract 1 from index, since index numbers start from 0
                    self.text_lines.delete(index)  # Deleting element at index
            elif rest_string == "":  # if user inputs empty string, deleting  all elements in List
                while not self.text_lines.is_empty():
                    index = len(self.text_lines) - 1
                    self.text_lines.delete(index)
            else:
                print("??")
                raise IndexError(
                    "Index is not a Number "
                )  # IndexError raised if index is not a number.
        except Exception as error:  # All Exceptions in Try block are caught and printed.
            print("??")
            print(error)
            userInput = input(
                "\nEnter Num of line to delete (or nothing to delete all lines) : "
            )
            self.delete_num(
                userInput
            )  # Giving user another chance to enter correct line_number to delete

    def insert_num_strings(self, number, list_of_strings):
        """
        Function inserts individual  elements in  list_of_strings from index = number -1 into self.text_lines.
        Insertion continues until user enters "." by itself.


        @:param self: the object
        @:param number: valid number (integer)
        @:param list_of_strings: List with the elements user enters to be inserted.
        @Pre Condition: input should be a valid number
        @Post Condition: Inserts the new element entered by user at index number-1.
        @complexity: Best case O(1), Worst case O(n)

        """

        try:
            if self.is_number(
                    number
            ) == True:  # running is_number() on number to check if its a number
                number = int(number)  # index variable assigned to int(number)
                if number == 0:
                    raise IndexError(
                        'Invalid line number'
                    )  # index error raised if line number input by user = 0
                elif int(number) < 0 and int(
                        number) >= -self.text_lines.length:
                    index = self.text_lines.length + int(
                        number)  # Converting negative index to positive
                elif number > 0:
                    index = number - 1  # if index positive  subtract 1 from index, since index numbers start from 0

            else:
                print("?")
                raise IndexError(
                    "Index is not a Number"
                )  # IndexError raised if index is not a number.

        except Exception as error:  # All Exceptions in Try block are caught and printed.
            print("?")
            print(error)

        try:
            for i in range(len(list_of_strings)):
                self.text_lines.insert(
                    index,
                    list_of_strings[i])  # inserting items in list_of_strings
                index += 1  # to self.text_lines at position index
        except Exception as e:  # All Exceptions in Try block are caught and printed.
            print("?")
            print(e)

    def search_string(self, string):
        """
       Function searches for string
       function prints the line numbers 'string' appears in

       @:param self: the object
       @:param string: string that user searches for
       @:param list_of_strings: List with the elements user enters to be inserted.
       @Post Condition: prints lines where string is contained.
       @complexity: Best case O(1), Worst case O(n)
        """

        present = False
        for i in range(len(self.text_lines)):
            # Convert to lower case and search
            if string.lower() in self.text_lines[i].lower():
                present = True
                print(i + 1)
        if not present:
            print("String not present.")

    def print_menu(self):
        """
        Function prints Menu

        @:param self: the object
        @Pre Condition: None
        @Post Condition:  Prints the menu
        @complexity: Best case O(1), Worst case O(1)
        """

        print("\n\n***************  MENU  ***************")
        print("\n" + "List of Commands:" + "\n" + "read filename\n" +
              "print num\n" + "delete num\n" + "insert num\n" + "quit\n")

    def prompt_user(self):
        """
        Function calls print_menu.
        Function asks user for selected inputs inputs.
        Function quits when thr user types "quit"

        @:param self: the object
        @Pre Condition: User has to type a command, Exception raised if incorrect command typed by user
        @Post Condition: Calls the appropriate function, and updates the list
        @complexity: Best case O(1), Worst case O(n)

        """

        end = False

        while not end:  # while end = False the outermost loop runs
            try:
                printMenu = False
                if printMenu == False:
                    self.print_menu()  # Call print menu
                    # Prompt user to type command
                user_input = input("Enter Command: (eg: read small.txt ) :  \n"
                                   ).lower().split(" ")

                if len(user_input) == 2 and user_input[
                        0] == "read":  # if length of user_input == 2 and first
                    self.text_lines = read_text_file(
                        user_input[1]
                    )  # element is "read" call read_text_files()
                    # method and store output in self.text_lines

                # if length of user_input <= 2 and first element is "print" then:
                elif len(user_input) <= 2 and user_input[0] == "print":
                    if len(user_input) == 1:  # if length of user_input == 1
                        rest_string = ""
                        self.print_num(rest_string)  # initiate print all lines
                    else:
                        self.print_num(
                            (user_input[1])
                        )  # else print item at line num  = second user input element

                # if length of user_input <= 2 and first element is "delete" then:
                elif len(user_input) <= 2 and user_input[0] == "delete":
                    if len(user_input) == 1:  # if length of user_input == 1
                        rest_string = ""
                        self.delete_num(
                            rest_string)  # initiate delete all lines
                    else:
                        self.delete_num(
                            user_input[1]
                        )  # Else delete item at line num = second element of user input

                # if length of user_input == 2 and first element is "insert" then:
                elif len(user_input) == 2 and user_input[0] == "insert":

                    try:
                        # running is_number() on second element of user input to check if its a number
                        if self.is_number(user_input[1]) == True:
                            number = int(
                                user_input[1]
                            )  # storing line number as type integer
                            if number == 0:  # if line number = 0
                                raise IndexError(
                                    'Invalid line number'
                                )  # index error raised if line number = 0
                            else:
                                # Creating new ListADT instance to store the content user wants to add
                                list_strings = ListADT()
                                end_insert = False  # setting end_insert condition to false
                                print("Enter text: ")

                                # while end inster = False run while loop to prompt user to type lines to enter
                                while not end_insert:
                                    prompt_user = input(" - ").strip()
                                    # if full stop typed by user, set end_insert to true and stop prompting user to type lines
                                    if prompt_user == ".":
                                        end_insert = True
                                    else:
                                        list_strings.append(prompt_user)
                                self.insert_num_strings(
                                    user_input[1], list_strings
                                )  # List_strings inserted to self
                        else:
                            raise IndexError(
                                'Enter valid Line number'
                            )  # IndexError raised if index is not a number.
                    except Exception as e:  # All Exceptions in Try block are caught and printed.
                        print("??")
                        print(e)

                elif len(user_input) == 2 and user_input[0] == "search":
                    print(self.search_string(user_input[1]))

                elif len(user_input) == 1 and (user_input[0] == "quit"):
                    # Sets 'end' to true when user types Quit, which stops the outermost while loop from running
                    end = True
                else:
                    print("You must enter one of the listed commands")
                    print("Try again ")
                    self.prompt_user(
                    )  # If invalid input is entered, allows user to try again.
            except Exception as e:  # All Exceptions in outer most Try block are caught and printed.
                end = True
                print(e)
                print("??")
                self.prompt_user()
コード例 #8
0
ファイル: Task5.py プロジェクト: GaveenA/Python-Projects
    def prompt_user(self):
        """
        Function calls print_menu.
        Function asks user for selected inputs inputs.
        Function quits when thr user types "quit"

        @:param self: the object
        @Pre Condition: User has to type a command, Exception raised if incorrect command typed by user
        @Post Condition: Calls the appropriate function, and updates the list
        @complexity: Best case O(1), Worst case O(n)

        """

        end = False

        while not end:  # while end = False the outermost loop runs
            try:
                printMenu = False
                if printMenu == False:
                    self.print_menu()  # Call print menu
                    # Prompt user to type command
                user_input = input("Enter Command: (eg: read small.txt ) :  \n"
                                   ).lower().split(" ")

                if len(user_input) == 2 and user_input[
                        0] == "read":  # if length of user_input == 2 and first
                    self.text_lines = read_text_file(
                        user_input[1]
                    )  # element is "read" call read_text_files()
                    # method and store output in self.text_lines

                # if length of user_input <= 2 and first element is "print" then:
                elif len(user_input) <= 2 and user_input[0] == "print":
                    if len(user_input) == 1:  # if length of user_input == 1
                        rest_string = ""
                        self.print_num(rest_string)  # initiate print all lines
                    else:
                        self.print_num(
                            (user_input[1])
                        )  # else print item at line num  = second user input element

                # if length of user_input <= 2 and first element is "delete" then:
                elif len(user_input) <= 2 and user_input[0] == "delete":
                    if len(user_input) == 1:  # if length of user_input == 1
                        rest_string = ""
                        self.delete_num(
                            rest_string)  # initiate delete all lines
                    else:
                        self.delete_num(
                            user_input[1]
                        )  # Else delete item at line num = second element of user input

                # if length of user_input == 2 and first element is "insert" then:
                elif len(user_input) == 2 and user_input[0] == "insert":

                    try:
                        # running is_number() on second element of user input to check if its a number
                        if self.is_number(user_input[1]) == True:
                            number = int(
                                user_input[1]
                            )  # storing line number as type integer
                            if number == 0:  # if line number = 0
                                raise IndexError(
                                    'Invalid line number'
                                )  # index error raised if line number = 0
                            else:
                                # Creating new ListADT instance to store the content user wants to add
                                list_strings = ListADT()
                                end_insert = False  # setting end_insert condition to false
                                print("Enter text: ")

                                # while end inster = False run while loop to prompt user to type lines to enter
                                while not end_insert:
                                    prompt_user = input(" - ").strip()
                                    # if full stop typed by user, set end_insert to true and stop prompting user to type lines
                                    if prompt_user == ".":
                                        end_insert = True
                                    else:
                                        list_strings.append(prompt_user)
                                self.insert_num_strings(
                                    user_input[1], list_strings
                                )  # List_strings inserted to self
                        else:
                            raise IndexError(
                                'Enter valid Line number'
                            )  # IndexError raised if index is not a number.
                    except Exception as e:  # All Exceptions in Try block are caught and printed.
                        print("??")
                        print(e)

                elif len(user_input) == 2 and user_input[0] == "search":
                    print(self.search_string(user_input[1]))

                elif len(user_input) == 1 and (user_input[0] == "quit"):
                    # Sets 'end' to true when user types Quit, which stops the outermost while loop from running
                    end = True
                else:
                    print("You must enter one of the listed commands")
                    print("Try again ")
                    self.prompt_user(
                    )  # If invalid input is entered, allows user to try again.
            except Exception as e:  # All Exceptions in outer most Try block are caught and printed.
                end = True
                print(e)
                print("??")
                self.prompt_user()
コード例 #9
0
def testing_delete():

    x = Editor()
    x.text_lines = read_text_file('small.txt')
    x.delete_num(1)

    y = ListADT()
    for i in ['not to utter','another word.']:
        y.append(i)
    # Check if delete function is correctly deleting item at correct position by comparing 2 lists./
    # both which should contain the same elements.
    assert (x.text_lines.the_array == y.the_array), "Should be True, but  \n x = " + str(x.text_lines) + "\n y = " + str(y)


    x = Editor()
    x.text_lines = read_text_file('small.txt')
    list_of_strings =ListADT()
    list_of_strings.insert(0, 'He is a')
    list_of_strings.insert(1, 'Good Friend')
    x.insert_num_strings(-1, list_of_strings)
    x.delete_num(-2)

    y = ListADT()
    for i in ['Yossarian decided', 'not to utter','another word.','Good Friend']:
        y.append(i)
    # Check if delete function is correctly deleting item at correct position by comparing 2 lists./
    # both which should contain the same elements.
    assert (x.text_lines.the_array == y.the_array), "Should be True, but  \n x = " + str(
        x.text_lines) + "\n y = " + str(y)



    x = Editor()
    x.text_lines = read_text_file('small.txt')
    x.delete_num(-1)

    y = ListADT()
    for i in ['Yossarian decided', 'not to utter']:
        y.append(i)
    # Check if delete function is correctly deleting item at correct position by comparing 2 lists./
    # both which should contain the same elements.
    assert (x.text_lines.the_array == y.the_array), "Should be True, but  \n x = " + str(x.text_lines) + "\n y = " + str(y)
コード例 #10
0
def test_eq():
    """function checks whether two lists are equal"""
    x = ListADT()
    x.unsafe_set_array([4, 3, 5, None, None], 3)
    y = ListADT()
    y.unsafe_set_array([4, 3, 5, None, None], 3)
    z = ListADT()
    z.unsafe_set_array([4, 5, 3, None, None], 3)
    w = ListADT()
    w.unsafe_set_array([4, 5, None, None], 2)
    # tests if two lists with same elements are equal
    assert (x == y), "Should be True but it is" + "x=" + str(x) + "y=" + str(y)
    # tests if two lists with different element are not equal
    assert (x !=
            z), "Should be False but it is" + "x=" + str(x) + "z=" + str(z)
    # tests if two lists with different element are not equal
    assert (x !=
            w), "Should be False but it is" + "x=" + str(x) + "w=" + str(w)

    try:
        # checks if IndexError raised when index is out of range
        x[7] = 0
        print("Should have raised IndexError")
    except IndexError:
        True
コード例 #11
0
def test_len():
    """function tests length of list"""
    x = ListADT()
    # check if length of initial list is 0.
    assert len(x) == 0, "Length should be 0 but is " + str(len(x))
    x.insert(0, 2)
    # checks length of list = 1 after insertion
    assert len(x) == 1, "Length should be 1 but is " + str(len(x))
    x.unsafe_set_array([1, 2, 3, 3, 4, 5, 5, 6, 7, 6, 8, None, None], 11)
    # checks if length of list = 11
    assert len(x) == 11, "Length should be 11 but is" + str(len(x))

    try:
        # checks if ValueError raised when size is set below 35
        x = ListADT(27)
        print("Should have raised value error")
    except Exception as e:
        True

    x = ListADT(98)
    x.unsafe_set_array(
        [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18] +
        79 * [None], 19)
    x.append(19)
    # checks if length of list = 20 and new size ==49 after shrinking
    assert x.size == 49, "Length should be 20 but is" + str(len(x))
コード例 #12
0
def test_delete():
    """function tests whether element at index is deleted"""
    x = ListADT()
    x.unsafe_set_array([1, 2, 5, 6, 7, None, None], 5)
    y = ListADT()
    y.unsafe_set_array([1, 2, 6, 7, None, None], 4)
    item = x.delete(2)
    # checks if functions deletes 5 from position 2, and if  item equals 5
    assert (item == 5 and x == y), "Should be True but it is " + "item=" + str(
        item) + " x= " + str(x) + " y= " + str(y)
    item = x.delete(0)
    y.unsafe_set_array([2, 6, 7, None, None], 3)
    # checks if functions deletes 1 from position 0 and if item equals 1
    assert (item == 1 and x == y), "Should be True but it is" + "item=" + str(
        item) + "x=" + str(x) + "y=" + str(y)
    # tests if deleting from a list at an invalid index is raising IndexError
    try:
        x.delete(12)
        print("Should have raised IndexError")
    except IndexError:
        True

    x = ListADT()
    x.unsafe_set_array([0] + 5 * [1] + 35 * [None], 6)
    y = ListADT()
    y.unsafe_set_array(5 * [1] + 30 * [None], 5)
    item = x.delete(0)
    # checks if functions deletes 0 from position 0, and if  item equals 0
    assert (item == 0 and x == y), "Should be True but it is " + "item=" + str(
        item) + " x= " + str(x) + "y=" + str(y)

    x = ListADT()
    x.unsafe_set_array([1] * 20 + [None] * 15, 20)
    y = ListADT()
    y.unsafe_set_array(19 * [1] + 16 * [None], 19)
    x.delete(19)
    # checks if functions deletes 0 from position 19, and if  item equals 0
    assert (item == 0 and x == y), "Should be True but it is " + "item=" + str(
        item) + " x= " + str(x) + "y=" + str(y)
コード例 #13
0
def test_insert():
    """function checks whether an element is inserted correctly"""
    x = ListADT()
    x.unsafe_set_array([1, 2, 5, 6, 7, None, None], 5)
    y = ListADT()
    y.unsafe_set_array([1, 2, 3, 5, 6, 7, None], 6)
    x.insert(2, 3)
    # check if x and y are equal, after inserting 3 in position 2
    assert (
        x == y), "Should be True but it is " + "x=" + str(x) + "y=" + str(y)
    x.insert(0, 0)
    y.unsafe_set_array([0, 1, 2, 3, 5, 6, 7, None], 7)
    # check if x and y are equal, after inserting 0 in position 0
    assert (x == y), "Should be True but it is" + "x=" + str(x) + "y=" + str(y)
    # tests if inserting to a list which is full is raising IndexError
    try:
        x.insert(12, 2)
        print("Should have raised IndexError")
    except IndexError:
        try:
            x.insert(1, 2)
            #print("Should have raised Exception")
        except Exception:
            True

    x = ListADT()
    x.unsafe_set_array(5 * [1] + 35 * [None], 5)
    y = ListADT()
    y.unsafe_set_array([0] + 5 * [1] + 29 * [None], 6)
    x.insert(0, 0)
    # check if x and y are equal, after inserting 0 in position 0
    assert (x == y), "Should be True but it is" + "x=" + str(x) + "y=" + str(y)

    x = ListADT()
    x.unsafe_set_array(9 * [1] + 31 * [None], 9)
    y = ListADT()
    y.unsafe_set_array(10 * [1] + 30 * [None], 10)
    x.insert(9, 1)
    # check if x and y are equal, after inserting 1 in position 9
    assert (x == y), "Should be True but it is" + "x=" + str(x) + "y=" + str(y)