Python Forum
Building a DoublyLinkedList in Python - - append method
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Building a DoublyLinkedList in Python - - append method
#1
Greetings Pythonistas!

I am learning how to write basic algorithms in Python but am taking an unusual approach. I am taking a Udemy course which teaches algorithms in JavaScript. What I do is watch the lesson where the instructor uses an interactive and dynamic visual aid to explain how the algorithm’s feature works, provides the pseudo code, asks the student to try writing the script themselves, and then provides the solution in JavaScript. I follow along and do all of that except for the last step, I use Python instead of JS. Based on the pseudo code, I write the algorithm in Python. Afterwards, I look at the solution in JS and make modifications as necessary.

Below is my attempt at building a Doubly Linked List (DLL). So far I’ve written the base Node constructor, the DLL constructor, the DLL append method, and the DLL string method. Below I have also included some testing in my Python REPL shell.

Having said all of that, my script doesn’t work as intended. When I instantiate a test list object and try to append integers one at a time, Python is only recording the most recent value. The list is not being extended by each value. The old value is just being overwritten by the new one in place. Any idea why? What kind of changes do I need to make so that when I call the append method, the list increases by the value being entered?

class Node:
    # Create a new node with the value passed to the function
    def __init__(self, value):
        self.value = value
        self.next = None
        self.prev = None

class DoublyLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
        self.length = 0

    def append(self, value):
        # If the head property is null set the head and tail to be the newly created node
        newNode = Node(value)
        if self.length == 0:
            self.head = newNode
            self.tail = newNode
        # If not... 
        else:
            # Set the next property on the tail to be that node
            self.tail.next = newNode
            # Set the previous property on the newly created node to be the tail
            newNode.prev = self.tail
            # Set the tail to be the newly created node
            self.tail = newNode
        # Increment the length
        self.length = self.length + 1
        # Return the Doubly Linked List
        return self
    
    def __str__(self):
        current = self.head
        result = []
        while current:
            result.append(current.value)
            current = current.next
        return str(result)
$ python      
Python 3.11.6 (main, Nov 14 2023, 09:36:21) [GCC 13.2.1 20230801] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from script import Node,DoublyLinkedList
>>> DLL_obj = DoublyLinkedList().append(24)
>>> print(DLL_obj)
[24]
>>> DLL_obj = DoublyLinkedList().append(2)
>>> DLL_obj = DoublyLinkedList().append(256)
>>> print(DLL_obj)
[256]
>>> 
Reply
#2
Your code is fine. The problem is you keep creating new lists, so each list is really length 1.
class Node:
    # Create a new node with the value passed to the function
    def __init__(self, value, prev=None, next=None):
        self.value = value
        self.next = next
        self.prev = prev
 

class DoublyLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
        self.length = 0
 
    def append(self, value):
        """Add value to tail."""
        node = Node(value, self.tail)
        if self.tail is not None:
            self.tail.next = node
        else:
            self.head = node
        self.tail = node
        self.length += 1
        return self

    def __len__(self):
        return self.length
     
    def __str__(self):
        values = []
        node = self.head
        while node:
            values.append(node.value)
            node = node.next
        return str(values)


x = DoublyLinkedList()
x.append(1).append(2).append(3)
print(x)
Output:
[1, 2, 3]
Reply
#3
Hi @deanystad. Thank you for your reply. You are right that I wasn't calling my custom append() method properly in my shell. Not sure how I let that slip through my fingers.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  building app in XCODE with python phantom115 2 898 Aug-02-2023, 11:56 AM
Last Post: phantom115
  How to modify python script to append data on file using sql server 2019? ahmedbarbary 1 1,232 Aug-03-2022, 06:03 AM
Last Post: Pedroski55
  Docker -building a python image saisankalpj 5 3,958 Jul-13-2022, 12:53 PM
Last Post: saisankalpj
  Building python (3.9.5) with different libexpat version (2.4.6) raghupcr 0 1,321 Feb-25-2022, 11:29 AM
Last Post: raghupcr
  Building a method name in a function ffgth 9 3,210 Oct-19-2020, 01:21 PM
Last Post: buran
  How to append to a set in Python dgrunwal 7 4,170 Oct-01-2020, 04:27 PM
Last Post: ndc85430
  Including modules in Python using sys.path.append JoeDainton123 1 2,916 Aug-24-2020, 04:51 AM
Last Post: millpond
  How to append a tuple full of records to a dbf file in Python? DarkCoder2020 4 3,759 May-29-2020, 02:40 PM
Last Post: DarkCoder2020
  Solaris 10 building Python 3.8.3 problems. munocat 0 1,532 May-26-2020, 01:05 AM
Last Post: munocat
  Cant Append a word in a line to a list err "str obj has no attribute append Sutsro 2 2,610 Apr-22-2020, 01:01 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020