Question

from __future__ import annotations from typing import Any, Optional class _Node: """A node in a linked...

from __future__ import annotations
from typing import Any, Optional


class _Node:
    """A node in a linked list.

    Note that this is considered a "private class", one which is only meant
    to be used in this module by the LinkedList class, but not by client code.

    === Attributes ===
    item:
        The data stored in this node.
    next:
        The next node in the list, or None if there are no more nodes.
    """
    item: Any
    next: Optional[_Node]

    def __init__(self, item: Any) -> None:
        """Initialize a new node storing <item>, with no next node.
        """
        self.item = item
        self.next = None  # Initially pointing to nothing


class LinkedList:
    """A linked list implementation of the List ADT.
    """
    # === Private Attributes ===
    # _first:
    #     The first node in the linked list, or None if the list is empty.
    _first: Optional[_Node]

    def __init__(self) -> None:
        """Initialize an empty linked list.
        """
        self._first = None

    def print_items(self) -> None:
        """Print out each item in this linked list."""
        curr = self._first
        while curr is not None:
            print(curr.item)
            curr = curr.next

  
    def __len__(self) -> int:
        """Return the number of elements in this list.

        >>> lst = LinkedList()
        >>> len(lst)              # Equivalent to lst.__len__()
        0
        >>> lst = LinkedList()
        >>> node1 = _Node(1)
        >>> node2 = _Node(2)
        >>> node3 = _Node(3)
        >>> node1.next = node2
        >>> node2.next = node3
        >>> lst._first = node1
        >>> len(lst)
        3
        """
        # TODO: implement this method
        # curr = self._first
        # while curr is not None:
        #     ... curr.item ...
        #     curr = curr.next

    def __contains__(self, item: Any) -> bool:
        """Return whether <item> is in this list.

        Use == to compare items.

        >>> lst = LinkedList()
        >>> node1 = _Node(1)
        >>> node2 = _Node(2)
        >>> node3 = _Node(3)
        >>> node1.next = node2
        >>> node2.next = node3
        >>> lst._first = node1
        >>> 2 in lst                     # Equivalent to lst.__contains__(2)
        True
        >>> 4 in lst
        False
        """
        # TODO: implement this method
        # curr = self._first
        # while curr is not None:
        #     ... curr.item ...
        #     curr = curr.next


    def append(self, item: Any) -> None:
        """Append <item> to the end of this list.

        >>> lst = LinkedList()
        >>> lst.append(1)
        >>> lst._first.item
        1
        >>> lst.append(2)
        >>> lst._first.next.item
        2
        """
        # TODO: implement this method
        # curr = self._first
        # while curr is not None:
        #     ... curr.item ...
        #     curr = curr.next


if __name__ == '__main__':
    import python_ta
    python_ta.check_all(config={
        'allowed-io': ['print_items']
    })

    import doctest
    doctest.testmod()
0 0
Add a comment Improve this question Transcribed image text
Answer #1
from __future__ import annotations
from typing import Any, Optional


class _Node:
    """A node in a linked list.

    Note that this is considered a "private class", one which is only meant
    to be used in this module by the LinkedList class, but not by client code.

    === Attributes ===
    item:
    The data stored in this node.
    next:
    The next node in the list, or None if there are no more nodes.
    """
    item: Any
    next: Optional[_Node]

    def __init__(self, item: Any) -> None:
        """Initialize a new node storing <item>, with no next node.
        """
        self.item = item
        self.next = None # Initially pointing to nothing


class LinkedList:
    """A linked list implementation of the List ADT.
    """
    # === Private Attributes ===
    # _first:
    # The first node in the linked list, or None if the list is empty.
    _first: Optional[_Node]

    def __init__(self) -> None:
        """Initialize an empty linked list.
        """
        self._first = None

    def print_items(self) -> None:
        """Print out each item in this linked list."""
        curr = self._first
        while curr is not None:
            print(curr.item)
            curr = curr.next

    # ------------------------------------------------------------------------
    # Prep 5 exercises
    # ------------------------------------------------------------------------
    # For each of the following linked list methods, read its docstring
    # and the complete its implementation.
    # You should use as your starting point our *linked list traversal*
    # code template, but of course you should modify it as necessary!
    #
    # NOTE: the first two methods are new special methods (you can tell by the
    # double underscores), and enable some special Python behaviour that we've
    # illustrated in the doctests.
    #
    # At the bottom of this file, we've included some helpers
    # to create some basic linked lists for our doctests.
    def __len__(self) -> int:
        """Return the number of elements in this list.

        >>> lst = LinkedList()
        >>> len(lst) # Equivalent to lst.__len__()
        0
        >>> lst = LinkedList()
        >>> node1 = _Node(1)
        >>> node2 = _Node(2)
        >>> node3 = _Node(3)
        >>> node1.next = node2
        >>> node2.next = node3
        >>> lst._first = node1
        >>> len(lst)
        3
        """
        l = 0
        curr = self._first
        while curr is not None:
            l += 1
            curr = curr.next
        return l

    def __contains__(self, item: Any) -> bool:
        """Return whether <item> is in this list.

        Use == to compare items.

        >>> lst = LinkedList()
        >>> node1 = _Node(1)
        >>> node2 = _Node(2)
        >>> node3 = _Node(3)
        >>> node1.next = node2
        >>> node2.next = node3
        >>> lst._first = node1
        >>> 2 in lst # Equivalent to lst.__contains__(2)
        True
        >>> 4 in lst
        False
        """
        curr = self._first
        while curr is not None:
            if curr.item == item:
                return True
            curr = curr.next
        return False


    # HINTS: for this one, you'll be adding a new item to a linked list.
    # 1. Create a new _Node object first.
    # 2. Consider the cases where the list is empty and non-empty separately.
    # 3. For the non-empty case, you'll first need to iterate to the
    # *last node* in the linked list. (Review this prep's Quercus quiz!)
    def append(self, item: Any) -> None:
        """Append <item> to the end of this list.

        >>> lst = LinkedList()
        >>> lst.append(1)
        >>> lst._first.item
        1
        >>> lst.append(2)
        >>> lst._first.next.item
        2
        """
        n = _Node(item)
        curr = self._first

        if curr is None:
            self._first = n
        else:
            while curr.next is not None:
                curr = curr.next
            curr.next = n
Add a comment
Know the answer?
Add Answer to:
from __future__ import annotations from typing import Any, Optional class _Node: """A node in a linked...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Python question. i have to start from an empty linked list, using the method addNodeEnd() to...

    Python question. i have to start from an empty linked list, using the method addNodeEnd() to add the nodes containing the values (3*i+5)%17, where i is from 0 to 10. Then print the values of all the nodes in this linked list to the screen. This is the code that i created right here and i need help checking if i made any mistakes thanks! The code is below: class Node: def __init__(self, data): self.data = data self.next = None...

  • Python code that sorts books

    class Book:    def __init__(self,id,bookName,authorName,nextNode=None):         self.id = id         self.bookName = bookName         self.authorName = authorName         self.nextNode = nextNode    def getId(self):        return self.id     def getBookName(self):        return self.bookName    def getAuthorName(self):        return self.authorName    def getNextNode(self):        return self.nextNode       def setNextNode(self,val):         self.nextNode = val   class LinkedList:    def __init__(self,head = None):         self.head = head         self.size = 0     def getSize(self):        return self.size    def AddBookToFront(self,newBook):         newBook.setNextNode(self.head)         self.head = newBook         self.size+=1     def DisplayBook(self):         curr = self.head        while curr:            print(curr.getId(),curr.getBookName(),curr.getAuthorName())              curr = curr.getNextNode()    def RemoveBookAtPosition(self,n):         prev = None         curr = self.head         curPos = 0         while curr:            if curPos == n:                if prev:                     prev.setNextNode(curr.getNextNode())                else:                     self.head = curr.getNextNode()                 self.size = self.size - 1                 return True                  prev = curr             curr = curr.getNextNode()              curPos = curPos + 1          return False     def AddBookAtPosition(self,newBook,n):         curPos = 1         if n == 0:             newBook.setNextNode(self.head)             self.head = newBook             self.size+=1             return         else:             currentNode = self.head            while currentNode.getNextNode() is not None:                if curPos == n:                     newBook.setNextNode(currentNode.getNextNode())                     currentNode.setNextNode(newBook)                     self.size+=1                     return                 currentNode = currentNode.getNextNode()                 curPos = curPos + 1             if curPos == n:                 newBook.setNextNode(None)                 currentNode.setNextNode(newBook)                 self.size+=1             else:                print("cannot add",newBook.getId(),newBook.getBookName(),"at that position")    def SortByAuthorName(self):        for i in range(1,self.size):             node1 = self.head             node2 = node1.getNextNode()            while node2 is not None:                if node1.authorName > node2.authorName:                     temp = node1.id                     temp2 = node1.bookName                     temp3 = node1.authorName                     node1.id = node2.id                     node1.bookName = node2.bookName                     node1.authorName = node2.authorName                     node2.id = temp                     node2.bookName = temp2                     node2.authorName = temp3                 node1 = node1.getNextNode()                 node2 = node2.getNextNode()     myLinkedList = LinkedList() nodeA = Book("#1","cool","Isaac") nodeB = Book("#2","amazing","Alfred") nodeC = Book("#3","hello","John") nodeD = Book("#4","why","Chase") nodeE = Book("#5","good","Mary") nodeF = Book("#6","hahaha","Radin") myLinkedList.AddBookToFront(nodeA) myLinkedList.AddBookToFront(nodeB) myLinkedList.AddBookToFront(nodeC) myLinkedList.AddBookAtPosition(nodeD,1) myLinkedList.AddBookAtPosition(nodeE,1) myLinkedList.AddBookAtPosition(nodeF,1) myLinkedList.RemoveBookAtPosition(2) myLinkedList.RemoveBookAtPosition(2) myLinkedList.DisplayBook() myLinkedList.SortByAuthorName()print(myLinkedList.getSize())...

  • Python 3: Python 3: Write a LinkedList class that has recursive implementations of the add, display,...

    Python 3: Python 3: Write a LinkedList class that has recursive implementations of the add, display, remove methods. You may use default arguments and/or helper functions. class Node: """ Represents a node in a linked list """ def __init__(self, data): self.data = data self.next = None class LinkedList: """ A linked list implementation of the List ADT """ def __init__(self): self.head = None def add(self, val): """ Adds a node containing val to the linked list """ if self.head is...

  • Write an implementation similar to the Priority Queue method (from chapter 26) to the linked list...

    Write an implementation similar to the Priority Queue method (from chapter 26) to the linked list using node. (from chapter 24). Your code should utilize the selectionsort method from attached and create another method call selectionsort in linkedlist class. To demonstrate the usage of the selection sort method, you should manually create a link list of random integer (say of 5 numbers), and you need to demonstrate the use the selection sort to sorted the link list. Please submit your...

  • Python 3: Write a LinkedList method named contains, that takes a value as a parameter and...

    Python 3: Write a LinkedList method named contains, that takes a value as a parameter and returns True if that value is in the linked list, but returns False otherwise. class Node: """ Represents a node in a linked list """ def __init__(self, data): self.data = data self.next = None class LinkedList: """ A linked list implementation of the List ADT """ def __init__(self): self.head = None def add(self, val): """ Adds a node containing val to the linked list...

  • from __future__ import annotations import random from typing import TYPE_CHECKING, List, Any from course import sort_students...

    from __future__ import annotations import random from typing import TYPE_CHECKING, List, Any from course import sort_students if TYPE_CHECKING: from survey import Survey from course import Course, Student def slice_list(lst: List[Any], n: int) -> List[List[Any]]: """ Return a list containing slices of <lst> in order. Each slice is a list of size <n> containing the next <n> elements in <lst>. The last slice may contain fewer than <n> elements in order to make sure that the returned list contains all elements...

  • If I wanted to create a method called getNum(n) that should return the data item from...

    If I wanted to create a method called getNum(n) that should return the data item from the node in the nth spot in the list. I am stuck and getting errors when I write my method. I have two files already, the first file linkedlist.py has the code .... ''' class Node(object): def __init__(self, data=None, nextNode=None): self.data = data self.nextNode = nextNode class linkedList(object): def __init__(self, head=None): self.head = head self.size = 0 def insert(self, node): if not self.head: self.head...

  • ill thumb up do your best python3 import random class CardDeck: class Card: def __init__(self, value):...

    ill thumb up do your best python3 import random class CardDeck: class Card: def __init__(self, value): self.value = value self.next = None def __repr__(self): return "{}".format(self.value) def __init__(self): self.top = None def shuffle(self): card_list = 4 * [x for x in range(2, 12)] + 12 * [10] random.shuffle(card_list) self.top = None for card in card_list: new_card = self.Card(card) new_card.next = self.top self.top = new_card def __repr__(self): curr = self.top out = "" card_list = [] while curr is not None:...

  • class Node(object): def __init__(self, data, next=None): self.data = data self.next = next class List(object):    def...

    class Node(object): def __init__(self, data, next=None): self.data = data self.next = next class List(object):    def __init__(self): self.head = None self.tail = None Implement the following functions for Linked List in Python and use the constructors above : Copy(lList) Builds and returns a copy of list ItemAt(List,i) Returns the data item at position i in list Pop(List,i=0) Remove item at position i in list. If i is not specified, it removes the first item in list Count(List,x) Returns the number...

  • Task 2: SecretWord class: Download and save a copy of LinkedLists.py (found at the bottom of...

    Task 2: SecretWord class: Download and save a copy of LinkedLists.py (found at the bottom of this assignment page on eClass). In this file, you have been given the complete code for a LinkedList class. Familiarize yourself with this class, noticing that it uses the Node class from Task 1 and is almost identical to the SLinkedList class given in the lectures. However, it also has a complete insert(pos, item) method (which should be similar to the insert method you...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT