implement a search feature within a linked list structure

My goal is to implement a search function in Python for linked lists. The purpose of this function is to search for a specific string within the linked list nodes (where each node contains a word). For example, given a linked list with nodes: I -> am -> a -> python -> developer. If I search for the text 'python', it should return True. Similarly, searching for 'apython' will also return True. However, searches for 'java' or 'ajava' should return False. I have written the following code for the search function, but it does not seem to be working properly. I'm considering implementing a recursive function to address this issue.

class Node:
    def __init__(self, value):
        self.value = value
        self.next = None


class LinkedList:
    def __init__(self, head = None):
        self.head = head

    def append(self, new_node):
        curr = self.head
        if curr:
            while curr.next:
                curr = curr.next
            curr.next = new_node
        else:
            self.head = new_node

    def search(self, text, cur):
        if cur.value == text:
            return True
        while cur.next != self.head and cur.next != None:
            if cur.next:
                cur = cur.next
                if cur.value == text:
                    return True
        return False

Answer №1

Your existing code is currently limited to checking for exact matches with a single node value.

Here are some additional points to consider:

  • The condition cur.next != self.head will never be true since the head node is always the first node in the list and can never be the successor of another node.

  • The statement if cur.next is unnecessary as it will always evaluate to true, explaining why the while loop does not exit.

  • You have repeated the check if cur.value == text multiple times in your code - look into applying the principle of DRY (Don't Repeat Yourself).

However, the main issue lies in the fact that your code doesn't attempt to match nodes with parts of the given text.

One approach to addressing this could involve creating two functions: one to determine if a specific node marks the beginning of a sequence of nodes that collectively correspond to the provided text, and another function to iterate through each node and apply the initial function. If any iteration returns a successful match, then the search is considered successful.

Consider implementing the following code snippets:

    def startswith(self, text, cur):
        while cur and text.startswith(cur.value):
            text = text[len(cur.value):]
            if not text:
                return True
            cur = cur.next
        return False
    
    def search(self, text, cur):
        if not text:  
            return True  
        while cur and not self.startswith(text, cur):
            cur = cur.next
        return cur is not None

To test the example scenario mentioned previously, use the following code snippet:

lst = LinkedList()
for word in "I am a python developer".split(" "):
    lst.append(Node(word))

print(lst.search("apython", lst.head))  # Output: True

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to using Python for automating the process of clicking on an email link to retrieve data

I'm attempting to access a specific email from my inbox and need to click on the 'Click here' hyperlink in order to download an Excel file onto my laptop. Here's the code I've been working with: import smtplib import time impo ...

What could be the reason for this tag showing up empty after being parsed with beautiful soup?

Currently utilizing beautiful soup to parse through this particular page: In an effort to retrieve the total revenue for 27/09/2014 (42,123,000) which is among the primary values at the top of the statement. Upon examining the element in chrome tools, it ...

Django is successfully loading CSS, but images and javascript files are not found with a 404 error

Currently working on a Django website project where I have successfully created a login page. However, upon testing it on the development server, I noticed that the CSS loads perfectly fine, but the images and JavaScript files are returning a 404 error, ev ...

Is there a way for me to change related_name in inherited or child objects?

Consider the given models: class Module(models.Model): pass class Content(models.Model): module = models.ForeignKey(Module, related_name='contents') class Blog(Module): pass class Post(Content): pass I am looking to retrieve al ...

Use the inline IF statement to adjust the icon class depending on the Flask variable

Is it feasible to achieve this using the inline if function? Alternatively, I could use JavaScript. While I've come across some similar posts here, the solutions provided were not exactly what I expected or were implemented in PHP. <i class="f ...

Celery - pulling offspring from group identifier

Can a list of tasks be accessed by only using a group identifier? from celery import group def f1(): task_group = group(task1, task2) return task_group().id def f2(group_id): pass # TODO: retrieve task1.id and task2.id GroupResult(id=f1( ...

Leveraging NumPy for array index discovery

If I am working with the following array: array = ['KDI', 'KDI', 'KDU', 'KDA', 'ANU', 'AMU', 'BDU', 'CDU', 'CDU', 'DAI', 'DAH'], dtype='

Exploring the concept of Starred Expression

Currently, I am working on implementing some reinforcement learning algorithms in a basic game. However, instead of dealing with RL issues, the problem seems to be more related to Python syntax. There is an issue with the starred expression that I can&apos ...

Tips for modifying each third column within a matrix

Just starting out with Python and it's my first time posting here. I am working on a project involving an LED panel that has UV, green, and blue lights in a 16x96 matrix. My goal is to allow the user to select a specific color and set the intensity f ...

An error has arisen: ImportError unable to bring in the name 'imap' from 'itertools' (location unknown)

System Information: Operating System: Linux Mint 20 Ulyana Kernel Version: 5.4.0-65-generic Architecture: 64-bit Compiler: gcc v9.3.0 Desktop Environment: Cinnamon 4.6.7 Window Manager: muffin Display Manager: LightDM Distro Base: Ubuntu 20.04 focal I tho ...

Drag and drop a file onto the center of the screen to upload it using Python

I need to upload a file to a website using Python Selenium, but because I am working in headless mode, I cannot click on the upload file button. Is there a way for me to automatically upload a file by dropping it in the center of the screen? I attempted th ...

Eliminate the generic placeholder text

Is it possible to extract only important information from a user's calendar event descriptions obtained through the Google Calendar API? For example, if we have a string like the one below: <br>Hi, please keep this text.<br> <br>Bob ...

Having trouble with CSS selectors in Python using Selenium?

https://i.stack.imgur.com/e48Kf.jpgI am attempting to navigate to the second link that has the class = "TabLink_tab__uKOPj" from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.webdriver.support.ui import WebDrive ...

Is there a way to parse this source text using selenium in Python?

<iframe id="frameNewAnimeuploads0" src="http://www.watchcartoononline.com/inc/animeuploads/embed.php?file=rick%20and%20morty%2FRick.and.Morty.S02E10.The.Wedding.Squanchers.720p.WEB-DL.DD5.1.flv&amp;hd=1" width="530" height="410" frameborder="0" scro ...

What could be causing sympy.diff to not behave as anticipated when differentiating sympy polynomials?

Trying to understand why the differentiation of sympy polynomials using sympy.diff isn't producing the expected result. It seems that when a function is defined with sympy.Poly, the derivative calculation doesn't work as intended even though it w ...

Learn how to tally the occurrences of "subINT" within an array using PHP

Let's say we have an array [1, 2, 1, 3, 4, 5]. In this scenario, the goal is to find a way to count occurrences of subINT in the given array. Unfortunately, using substr_count(); won't work as intended since the values within the array are not st ...

Single-line ELLIDED QLabel

Currently, I am working on creating a Qlabel in Qt (specifically in PyQt) that will dynamically adjust to the available space. This label is intended to display file paths, which can sometimes be quite lengthy. However, the current setup causes the label t ...

Tips for adjusting QTextTable to span the entire width of the document

I'm seeking a way to make the QTextTable within QTextDocument take up 100% or full width of the document. Unfortunately, there doesn't seem to be a method in the QTextTableFormat class that allows for formatting the QTextTable to have 100% width. ...

Using a matplotlib colormap from pyplot.jl as a custom function in Julia programming language

Is there a comparable method in Julia-lang to achieve the following: import numpy as np import matplotlib.pyplot as plt i = 0, f = 255, N = 100 colors = [ plt.cm.viridis(x) for x in np.linspace(i, f, N) ] How can I obtain the RGB list from a colormap usi ...

Ways to create mobility for IIWA

We are developing a simulation for a robot that is tasked with navigating through a grocery store to pick up items for online orders. In order to accomplish this, we need to modify the IIWA robot to have mobility rather than being fixed in place. We are se ...