Question

In: Computer Science

Python class LinkedNode: # DO NOT MODIFY THIS CLASS # __slots__ = 'value', 'next' def __init__(self,...

Python

class LinkedNode:
    # DO NOT MODIFY THIS CLASS #
    __slots__ = 'value', 'next'

    def __init__(self, value, next=None):
        """
        DO NOT EDIT
        Initialize a node
        :param value: value of the node
        :param next: pointer to the next node in the LinkedList, default is None
        """
        self.value = value  # element at the node
        self.next = next  # reference to next node in the LinkedList

    def __repr__(self):
        """
        DO NOT EDIT
        String representation of a node
        :return: string of value
        """
        return str(self.value)

    __str__ = __repr__


# IMPLEMENT THESE FUNCTIONS - DO NOT MODIFY FUNCTION SIGNATURES #


def insert(value, node=None):
    pass


def to_string(node):
    pass


def remove(value, node):
    pass


def remove_all(value, node):
    pass


def search(value, node):
    pass


def length(node):
    pass


def sum_list(node):
    pass


def count(value, node):
    pass


def reverse(node):
    pass


def remove_fake_requests(head):
    pass

Testcases:

import unittest
from LinkedList import insert, remove, remove_all, to_string, search, sum_list, \
    count, reverse, length, remove_fake_requests


class TestProject2(unittest.TestCase):
    def test_insert(self):
        linked_list = insert(0)
        insert(1, linked_list)
        insert(2, linked_list)

        for i in range(0, 3):
            assert linked_list.value == i
            linked_list = linked_list.next

    def test_to_string(self):
        list1 = insert(0)
        insert(1, list1)
        insert(2, list1)
        insert(3, list1)

        assert to_string(list1) == "0, 1, 2, 3"

    def test_length(self):
        list1 = insert(1)
        insert(2, list1)
        insert(3, list1)

        assert length(list1) == 3

    def test_search(self):
        list1 = insert(0)
        insert(1, list1)
        insert(2, list1)

        assert search(2, list1)
        assert not search(3, list1)

    def test_count(self):
        list1 = insert(0)
        insert(1, list1)
        insert(2, list1)

        assert count(0, list1) == 1
        assert count(1, list1) == 1
        assert count(2, list1) == 1

    def test_sum_list(self):
        list1 = insert(0)
        insert(1, list1)
        insert(2, list1)
        insert(3, list1)

        assert sum_list(list1) == 6

    def test_remove(self):
        list1 = insert(0)
        insert(1, list1)
        insert(2, list1)
        insert(3, list1)

        list1 = remove(1, list1)
        for i in [0, 2, 3]:
            assert list1.value == i
            list1 = list1.next

        assert list1 == None

    def test_remove_all(self):
        list1 = insert(0)
        insert(1, list1)
        insert(0, list1)
        insert(2, list1)
        insert(3, list1)
        insert(0, list1)

        list1 = remove_all(0, list1)
        test_list = list1
        for i in [1, 2, 3]:
            assert test_list.value == i
            test_list = test_list.next

        assert test_list == None

    def test_reverse(self):
        list1 = insert(0)
        insert(1, list1)
        insert(2, list1)
        insert(3, list1)

        list1 = reverse(list1)

        for i in [3, 2, 1, 0]:
            assert list1.value == i
            list1 = list1.next

    def test_fake_requests(self):
        requests = insert(170144)
        insert(567384, requests)
        insert(604853, requests)
        insert(783456, requests)
        insert(783456, requests)
        insert(903421, requests)

        real_requests = remove_fake_requests(requests)
        for i in [170144, 567384, 604853, 903421]:
            assert real_requests.value == i
            real_requests = real_requests.next


if __name__ == "__main__":
    unittest.main()

Thanks!

Solutions

Expert Solution

That's a lot of methods. Please note that we will be given 2 hours of time to solve a problem. In 2 hours I have done all the methods except two. reverse() fake_request(). I have taken full 2 hours.

So, please post another question asking for only these two.

class LinkedNode:
    # DO NOT MODIFY THIS CLASS #
    __slots__ = 'value', 'next'

    def __init__(self, value, next=None):
        """
        DO NOT EDIT
        Initialize a node
        :param value: value of the node
        :param next: pointer to the next node in the LinkedList, default is None
        """
        self.value = value  # element at the node
        self.next = next  # reference to next node in the LinkedList

    def __repr__(self):
        """
        DO NOT EDIT
        String representation of a node
        :return: string of value
        """
        return str(self.value)

    __str__ = __repr__


# IMPLEMENT THESE FUNCTIONS - DO NOT MODIFY FUNCTION SIGNATURES #


def insert(value, node=None):
    # Is it an empty linked list??
    if node == None:
        # Create a new LinkedList
        head = LinkedNode(value)
        return head
    else:
        # Append a node
        n = LinkedNode(value)
        temp = node
        while temp.next != None:
            temp = temp.next
            
        temp.next = n


def to_string(node):
    # Take all the values in a list 
    values = []
    temp = node
    while temp != None:
        values.append(temp.value)
        temp = temp.next
    # Return the string representation of the values
    return ', '.join(str(i) for i in values)


def remove(value, node):
    # Add the first node 
    new_head = insert(node.value)
    temp = node
    while temp.next != None:
        # Found the value?? ignore it to add to list
        if temp.next.value != value:
            new_head.next = temp
            temp = temp.next
        else:
            temp.next=temp.next.next
    return new_head


def remove_all(value, node):
    if node.value==value:
        new_head = insert(node.next.value)
    else:
        new_head = insert(node.value)
    temp = node
    while temp.next!= None:
        if temp.next.value != value:
            new_head.next = temp
            temp = temp.next
        else:
            temp.next = temp.next.next
    return new_head


def search(value, node):
    temp = node
    while temp != None:
        if temp.value == value: # FOUND!!!
            return True
        temp = temp.next
    return False #NOT FOUND


def length(node):
    count = 0
    temp = node
    while temp != None:
        temp = temp.next
        count += 1
    return count #RETURN THE NUMBER OF VALUES


def sum_list(node):
    sum_ = 0
    temp = node
    while temp != None:
        sum_ += temp.value
        temp = temp.next# ADD THE VALUES
    return sum_


def count(value, node):
    count = 0
    temp = node
    while temp != None:
        if temp.value == value:
            count += 1 
        temp = temp.next
    return count


def reverse(node):
    pass


def remove_fake_requests(head):
    pass

======================================

SCREENSHOT:

OUTPUT:

SOURCE CODE:


Related Solutions

python class Node(): def __init__(self, value): pass class PostScript(): def __init__(self): pass    def push(self, value):...
python class Node(): def __init__(self, value): pass class PostScript(): def __init__(self): pass    def push(self, value): pass    def pop(self): return None    def peek(self): pass    def is_empty(self): pass def stack(self): pass    def exch(self): pass    def index(self): pass    def clear(self): pass    def dup(self): pass    def equal(self): pass    def depth(self): pass    stack = PostScript() def decode(command_list): for object in command_list: if object == '=': stack.equal() elif object == 'count': stack.depth() elif object ==...
For python... class car:    def __init__(self)          self.tire          self.gas    def truck(self,color)        &nb
For python... class car:    def __init__(self)          self.tire          self.gas    def truck(self,color)               style = color                return    def plane(self,oil)              liquid = self.oil + self.truck(color) For the plane method, I am getting an error that the class does not define __add__ inside init so I cannot use the + operator. How do I go about this.             
using repl or python class House():    valuationRate = 10       def __init__(self,city,sqft,price):        ...
using repl or python class House():    valuationRate = 10       def __init__(self,city,sqft,price):         self.city = city         self.sqft = sqft         self.price = price           def getPrice(self):         return self.price    def applyValuation(self):         self.price += self.price * self.valuationRate/100 # create class Townhouse that inherits from class House # class Townhouse should have valuationRate = 5    # implement method setPrice(self,price) in class Townhouse    # create an object House: city=Atlanta, sqft=10000, price=200000   ...
How would I setup this dictionary for Python 3? class Student(object): def __init__(self, id, firstName, lastName,...
How would I setup this dictionary for Python 3? class Student(object): def __init__(self, id, firstName, lastName, courses = None): The “id”, “firstName” and “lastName” parameters are to be directly assigned to member variables (ie: self.id = id) The “courses” parameter is handled differently. If it is None, assign dict() to self.courses, otherwise assign courses directly to the member variable. Note: The “courses” dictionary contains key/value pairs where the key is a string that is the course number (like “course1”) and...
class Board: def __init__(self): self.pieces = [[None for i in range(8)] for j in range(8)] def...
class Board: def __init__(self): self.pieces = [[None for i in range(8)] for j in range(8)] def __str__(self): s = "" for j in range(7, -1, -1): #for each row for i in range(8): # for each column if self.pieces[j][i] is None: # if self.pieces[j][i] is None s += "." # populate the row with '.' val for each column else: s += self.pieces [j][i].get_symbol() s += "\n" #after each row add a new line return s # return after iterating...
''' File: pyPatientLL.py Author: JD ''' class Node: #ADT        def __init__(self, p = None):             ...
''' File: pyPatientLL.py Author: JD ''' class Node: #ADT        def __init__(self, p = None):              self.name = ""              self.ss = self.age = int(0)              self.smoker = self.HBP = self.HFD = self.points = int(0)              self.link = None              #if list not empty              if p != None:                     p.link = self        ptrFront = ptrEnd = None choice = int(0) def menu():        print( "\n\tLL Health Clinic\n\n")        print( "1. New patient\n")        print( "2. View patient by...
1) What is the argument in “class AddressBook(object):” 2) What is the roll of “def __init__(self):”?...
1) What is the argument in “class AddressBook(object):” 2) What is the roll of “def __init__(self):”? 3) What is the roll of “def __repr__ (self):”? 4) Please copy and run “Addressbook” Python program. Submit the code and the output 5) Discuss the two outputs’ differences (data type). 6) Please add 2 more people and report the output. Code: class AddressBook(object): def init_(self): self.people=[] def add_entry(self, new_entry): self.people.append(new_entry) class AddressEntry(object): def __init__(self, first_name=None, family_name= None, email_address= None, DOB= None): self.first_name =...
write pseudocode for this program . thank you import random class cal():    def __init__(self, a,...
write pseudocode for this program . thank you import random class cal():    def __init__(self, a, b):        self.a = a        self.b = b    def add(self):        return self.a + self.b    def mul(self):        return self.a * self.b    def div(self):        return self.a / self.b    def sub(self):        return self.a - self.b def playQuiz():    print("0. Exit")    print("1. Add")    print("2. Subtraction")    print("3. Multiplication")    print("4. Division")...
class Car: condition = "new" def __init__(self, model, color, mpg): self.model = model self.color = color...
class Car: condition = "new" def __init__(self, model, color, mpg): self.model = model self.color = color self.mpg = mpg my_car = Car("Corvette", "Black", “30”) print my_car.model print my_car.color print my_car.MPG print my_car.condition Add class “getter” methods to return the values for model, color, and MPG Add class “setter” methods to change the existing values for model, color, and MPG. The value to be used in the methods will be passed as an input argument. Add class method that will calculate...
"""stack.py implements stack with a list""" class Stack(object): def __init__(self): #creates an empty stack. O(1) self.top...
"""stack.py implements stack with a list""" class Stack(object): def __init__(self): #creates an empty stack. O(1) self.top = -1 #the index of the top element of the stack. -1: empty stack self.data = [] def push(self, item): # add item to the top of the stack. O(1) self.top += 1 self.data.append(item) def pop(self): # removes and returns the item at the top O(1) self.top -=1 return self.data.pop() def peek(self): # returns the item at the top O(1) return self.data[len(self.data)-1] def isEmpty(self):...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT