Question

I need a python 3 help. Please help me with this question Part 2. Linked Lists...

I need a python 3 help. Please help me with this question

Part 2. Linked Lists

You start working with the class LinkNode that represents a single node of a linked list. It has two instance attributes: value and next.

class LinkNode: def __init__(self,value,nxt=None): assert isinstance(nxt, LinkNode) or nxt is None self.value = value self.next = nxt

Before you start with the coding questions, answer the following questions about the constructor

Valid Constructor or Not?

  1. LinkNode(1, 3)
  2. LinkNode(1, None)
  3. LinkNode(1, LinkNode(4, None))
  4. LinkNode(1, None)
  5. LinkNode()

Try to predict the output.

>>> r = LinkNode(1, LinkNode(2, LinkNode(3, None))) >>> r.value

>>> r.next >>> r.next.next >>> r.next.value

>>> r.next.next.value

Question 2.1. Empty Node

In some cases in it convenient to have a notion of an empty linked list. Usually it means that the linked list does not have any elements in it. In order to keep things simple (for now) we will assume that the list is empty, if it has a single node and its value is None.

Add a function is_empty to class LinkNode that checks whether a node is an empty node.

class LinkNode:

"""

>>> node = LinkNode(6, LinkNode(5, None))

>>> node.is_empty()

False

>>> node = LinkNode(None, None)

>>> node.is_empty()

True

"""

def __init__(self,value,nxt=None):

assert isinstance(nxt, LinkNode) or nxt is None

self.value = value

self.next = nxt

def is_empty(self):

# Your code is here

Question 2.2. Print Linked List

The representation of linked list that we used in class is not very convenient for people to comprehend. Therefore, the first function I'd like you to write

will take a linked list as an argument and will print it using box-and-pointer notation. (This function is not a part of the class)

You can assume that there is only one empty node and it will represent an empty linked list.

def print_list (lst):

  """ Prints linked list in a readable format

>>> print_list(LinkNode(3, None))

3 -> None

>>> print_list(LinkNode(3))

3 -> None

>>> print_list(LinkNode(3, LinkNode(2, LinkNode(1, None))))

3 -> 2 -> 1 -> None

>>> print_list (LinkNode(None, None))

empty list

"""

        # Your code is here

Question 2.3. Linked List Length

How many elements are in your linked list? Who knows...there are no function to use. Yeah..it means you have to write one. Please, write a function that returns

the length of a given linked list (number of elements in it).

You can solve this problem recursively.

def list_length(lst):

  """ Returns the number of elements in the linked list

>>> list_length(LinkNode(3, None))

1

>>> list_length(LinkNode(3))

1

>>> list_length(LinkNode(None, None))

0

>>> list_length(LinkNode(3, LinkNode(2, LinkNode(1, None))))

3

"""

  # Your code is here

Question 2.4. Find element at index

Linked List are not arrays. It means you have to start at the beginning of the linked list to get to a certain place, looping though one element at the time.

Write a function that loops though the list and returns a value at the given index. If index is out of bounds, it reports the error to the user. See doctests for more details.

def get_item(lst, index):

  """ Returns an element at the given index

>>> get_item(LinkNode(3, LinkNode(2, LinkNode(1, None))), 1)

2

>>> get_item(LinkNode(3, LinkNode(2, LinkNode(1, None))), 0)

3

>>> get_item(LinkNode(3, LinkNode(2, LinkNode(1, LinkNode(0, LinkNode(17))))), 4)

17

>>> get_item(LinkNode(3, LinkNode(2, LinkNode(1, None))), 4)

'index is out of bounds'

>>> get_item(LinkNode(3, LinkNode(2, LinkNode(1, None))), -4)

'index is out of bounds'

>>> get_item(LinkNode(None, None), 0)

'list is empty'

"""

        # Your code is here

0 0
Add a comment Improve this question Transcribed image text
Answer #1

About constructors.

2,3,4 constructors are valid.

Because,they are in a format we used to assign linked list.

constructor 1 is invalid. Because,it claims Assertion Error in the constructor second argument act like pointer .

But 3 is not a pointer thats why it claims Assertion Error.

Constructor 5 is invalid. Because,we have to pass one of the argument,or we can pass None as a argument if we want

to create an empty Linked List.  

code:

class LinkNode:

   def __init__(self,value,nxt=None):
  
       assert isinstance(nxt, LinkNode) or nxt is None

       self.value = value

       self.next = nxt

def print_list(lst):

   temp = lst
   if(is_empty(lst)):
       print("empty list")
   else:
       while temp:

           print(temp.value, end="->")

           temp = temp.next
       print ("None")
       print()

def is_empty(lst):
   if lst.value is None:
       return True
   else:
       return False
          
def list_length(lst):

   temp = lst
   k=0
  
   if(is_empty(lst)):
       return 0
   while temp:
       k=k+1
       temp = temp.next
          
   return k      
  
      
      
def get_item(self, data):
   current = self
   found = False
   if data<0:
       return "Index is out of Bounds"
   if (is_empty(self)):
       return "list is empty"
   for k in range(0,data):
       if current and found is False:
           if k == data:
               found = True
           else:
               current = current.next
       if current is None :
           return "Index is out of Bounds"
   return current.value
  
  
print()  
print("Predict the outputs")
r = LinkNode(1, LinkNode(2, LinkNode(3, None)))
print(r.value)
r.next
print(r.next.value)
r.next.next
print(r.next.next.value)


print()
print("Usage of is_empty function")

print(is_empty(LinkNode(6, LinkNode(5, None))))
print(is_empty(LinkNode(None,None)))
print()
print("Usage of Print_list function")

print_list(LinkNode(3, None))
print_list(LinkNode(3))
print_list(LinkNode(3, LinkNode(2, LinkNode(1, None))))
print_list (LinkNode(None, None))

print()
print("Usage of List_length function")

print(list_length(LinkNode(3, None)))
print(list_length(LinkNode(3)))
print(list_length(LinkNode(None, None)))
print(list_length(LinkNode(3, LinkNode(2, LinkNode(1, None)))))

print()
print("Usage of get_item function")

print(get_item(LinkNode(3,LinkNode(2,LinkNode(1,None))),1))

print(get_item(LinkNode(3,LinkNode(2,LinkNode(1,None))),0))

print(get_item(LinkNode(3,LinkNode(2,LinkNode(1,LinkNode(0,LinkNode(17))))),4))

print(get_item(LinkNode(3,LinkNode(2,LinkNode(1,None))),4))

print(get_item(LinkNode(3,LinkNode(2,LinkNode(1,None))),-4))

print(get_item(LinkNode(None,None),0))

output:

Predict the outputs sage of is_empty function False lrue sage of Print_list function 3-〉None З->None 3-2-1->None empty list U

If you have any queries, please comment below.

Please upvote , if you like this answer.

Add a comment
Know the answer?
Add Answer to:
I need a python 3 help. Please help me with this question Part 2. Linked Lists...
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 class LinkNode: def __init__(self,value,nxt=None): assert isinstance(nxt, LinkNode) or nxt is None self.value = value...

    Python question class LinkNode: def __init__(self,value,nxt=None): assert isinstance(nxt, LinkNode) or nxt is None self.value = value self.next = nxt Question 2.1. Empty Node In some cases in it convenient to have a notion of an empty linked list. Usually it means that the linked list does not have any elements in it. In order to keep things simple (for now) we will assume that the list is empty, if it has a single node and its value is None. Add...

  • Python3 You should use the getters and setters I post in the first pic 157 158...

    Python3 You should use the getters and setters I post in the first pic 157 158 class LinkNode: 159 160 def-initー(self.value,nxt One): assert isinstance(nxt,Lin㎾ode) or nxt is None self.value value self.next = nxt 61 162 163 164 165 166 167 168 169 170 def get_value(self): def set_value(self, value): def get_next(seif): def set_next(self,nxt): def _repr (self): return self.value self.value = value return self.next self.next = nxt return repr(self.value)+ ", "+repr(self.next) 172 173 A permutation can be considered as an injective (one-to-one)...

  • python3 Question 2.4. Find element at index Linked List are not arrays. It means you have...

    python3 Question 2.4. Find element at index Linked List are not arrays. It means you have to start at the beginning of the linked list to get to a certain place, looping though one element at the time. Write a function that loops though the list and returns a value at the given index. If index is out of bounds, it reports the error to the user. See doctests for more details def get item(ist, index) : Returns an element...

  • 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...

  • In Python 3 Write a LinkedList class that has recursive implementations of the display, remove, contains,...

    In Python 3 Write a LinkedList class that has recursive implementations of the display, remove, contains, insert, and normal_list methods. You may use default arguments and/or helper functions. The file must be named: LinkedList.py Here is what I have for my code so far. The methods I need the recursive implementations for will be bolded: class Node: """ Represents a node in a linked list (parent class) """ def __init__(self, data): self.data = data self.next = None class LinkedList: """...

  • 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) ->...

  • 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...

  • Finish each function python 3 LList.py class node(object): """ A version of the Node class with...

    Finish each function python 3 LList.py class node(object): """ A version of the Node class with public attributes. This makes the use of node objects a bit more convenient for implementing LList class.    Since there are no setters and getters, we use the attributes directly.    This is safe because the node class is defined in this module. No one else will use this version of the class. ''' def __init__(self, data, next=None): """ Create a new node for...

  • 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 Programming assignment: Let's think about doubly-linked lists. Define a class ListNode2, with three attributes: item,...

    python Programming assignment: Let's think about doubly-linked lists. Define a class ListNode2, with three attributes: item, left, and rightL. Left link points to the previous node in the list, right link points to the next node in the list. You can also add the display method to this class (like we did it in class for the ListNode class). Then test your class. For example, create a linked list of 5 values: 34,1, 23, 7, and 10. Display it. Then...

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
ADVERTISEMENT