List with dynamic substrings. Ten elements preceding the variable

I am struggling with dynamic substrings. My list can vary in size, containing anywhere from 20 to 1000 elements. I want to create a new list based on a variable number that includes elements starting from -10 up to that variable. For instance (using pseudo-code):

L = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
variable = 12
print L[substring:variable]
>>> L = [2,3,4,5,6,7,8,9,10,12]

Despite my efforts, I can't seem to get it right as the variable is constantly changing by one.

This is the code snippet I have been working on:

def Existing(self, Pages):
     if(self.iter <= 10):
         list = self.other_list[:self.iter]
     else:
         list = self.other_list[self.iter-10:self.iter]
     result = 0
     page = Pages[0]

     list.reverse()

     for blocks in Pages:
         if(list.index(blocks) > result):
             result = list.index(blocks)
             page = blocks

     return page

This method is intended to find the element with the farthest index. However, this part may be confusing. Let's take an example:

list = [1,2,3,4,1,5,2,1,2,3,4]

The desired outcome of the method should be 5 since it is the element with the highest index value. The issue arises due to substring operations in self.other_list.

Can you offer guidance on how to correct this problem? Any advice would be greatly appreciated.

EDIT: To clarify the problem further, here are additional examples.

Let's assume the list Pages contains pages currently in use. The second list "list" consists of all pages that have been used before. The method aims to identify a page that has not been used for the longest duration, based on index values. How do we determine the farthest element? It refers to the one with the smallest index (accounting for duplicates).

For instance:

Pages = [1,3,5,9]

and

list = [1,2,5,3,6,3,5,1,2,9,3,2]

In this scenario, the method should return 5.

To summarize: I need help finding the correct substring output:

With list =[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] 
For variable 12: [2,3,4,5,6,7,8,9,10,12] 
for 13: [3,4,5,6,7,8,9,10,11,13] 

etc :-) I understand this may be a complex issue, so I kindly request your focus solely on substrings. Thank you very much!

Answer №1

If I correctly understand your issue, you are trying to determine the index of items on pages that appear at the minimum position in lst, considering duplicates.

To achieve this, you should first reverse the list and then find the index of each item in pages within lst. If an item is not found, return negative Infinity. Among those indices, identify the maximum item to get the desired result.

from functools import partial

pages = [1, 3, 5, 9]
lst = [1, 2, 5, 3, 6, 3, 5, 1, 2, 9, 3, 2]

def get_index(seq, i):
    try:
        return seq.index(i)
    except ValueError:
        return float('-inf')

lst.reverse()
print max(pages, key=partial(get_index, lst))
#5

It's important to note that the method above has a quadratic time complexity, which might not be suitable for large lists. For linear time complexity with some extra memory usage, you can consider using sets and dictionaries:

pages_set = set(pages)
d = {}
for i, k in enumerate(reversed(lst), 1):
    if k not in d and k in pages_set:
        d[k] = len(lst) - i

print min(d, key=d.get)
#5

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

What is the process for assigning an ID to an object by clicking on an adjacent link in Django?

Trying to set an identifier for a CSV file's name so that clicking on a link next to it will lead to viewing the file itself on another webpage. Encountering the error message 'QueryDict' object has no attribute 'objects' Please ...

A Guide to Replacing a json Field with Null and Inserting it into a PostgreSQL Database

I have thoroughly examined the available options discussed in this context, but I find that most of them do not adequately address my specific situation. In my scenario, I import this information into a database where the field is designated as SMALLINT. H ...

Python's CSV writer puts quotation marks around values to ensure that the data is properly enclosed and doesn

Is there a way to save a list in a csv file without the values becoming strings upon reloading it? Upon executing my code and checking the content of the file using "cat", the output shows: cat test.csv -> "[1, 2]","[3, 4]","[5, 3]" This is the code ...

Converting a whole number into a timestamp using Python

After struggling with converting the list l: l = [0, 1] into timestamps corresponding to the indexes of dataframe df: dt val 2017-11-13 00:00:00 8 2017-11-13 01:00:00 17 Ideally, I want the result to be: l = [2017-11-13 00:00:00, 2 ...

Exploring the Discrepancies in Augmented Dickey-Fuller Test Outputs between R and Python

What could explain the significant difference in results between the ADF test in R and Python? Dataset: The R test indicates that the time series is stationary, while the Python test suggests it is non-stationary. Python df = pd.read_csv("../data/ai ...

Is it possible to identify the beginning of a download using Selenium?

Currently, I am using Python and Selenium to download a large batch of files. To ensure that each file is successfully downloaded, I am implementing a basic time.sleep() function, but I want to enhance efficiency and guarantee the completion of each downlo ...

Issues with accessing global IDs in PyOpenCL within 2D arrays are causing errors

I'm completely new to OpenCL and decided to experiment with it using the code provided on a website. I made some changes to the code and am attempting to send a 4x4 matrix filled with all 1s to the kernel and retrieve it back. It may seem like a simpl ...

Object-Oriented Programming in Python: Classes and Inheritance

... from PyQt4.QtGui import * from PyQt4.QtCore import * class UserInfoModalWindow(QDialog): def init(self): super(UserInfoModalWindow, self).init() self.dialog_window = QDialog(self) ... ...

The unexpected issue concerning frameworks within PIL

While attempting to install PIL on my Mac OSX, I run sudo python setup.py install and everything seems to be going smoothly until I receive the following output. Has anyone else encountered this issue before? running build_ext --- using frameworks at /S ...

What is causing the error when attempting to install xlwings via the terminal?

Recently, I've started learning Python and embarked on a personal project. I wanted to install xlwings to execute Python code from Excel but I encountered issues with the installation process. Here's what I attempted: C:\Users\Rafi> ...

Failed attempts to retrieve the binary large object (BLOB) from SQLite using Flask SQLAlchemy results in a null

I'm facing an issue while attempting to retrieve a BLOB (LargeBinary) object from SQLite using Flask-SQLAlchemy. The error message I'm encountering is: TypeError: must be string or read-only buffer, not None. This is the code snippet that I am w ...

Ways to effectively utilize crosstab/pivot when dealing with multiple dimensions

I attempted to utilize pivot tables in order to include more than one value in the 'values' field for the pivot_table function, but unfortunately it didn't work. So now I am exploring the possibility of achieving this with crosstabs. Below ...

Encountering an issue while trying to execute a selenium application in the terminal: (Error message: ImportError - Unable to

Although I am a beginner in Python and Selenium, I have encountered an issue: When I execute my Python script using the IDLE (pressing F5), Selenium works perfectly (it opens Firefox, navigates to a website, and performs tasks). However, when I attempt to ...

Django: Various URL patterns originating from the root directory and separated into multiple files

Is it possible to have the standard URL patterns spread across multiple files, namely the project-wide urls.py and several app-specific urls.py? Imagine the project's urls.py looking like this: from django.conf.urls import patterns, include, url adm ...

Unable to access Docker Flask App connected to Docker DB in browser

I currently have a Flask App running in one Docker container and a Postgres database in another Docker container. I am attempting to build and run these containers using 'docker-compose up --build'. However, when I attempt to open the 'Runni ...

Ways to have Python recognize a variable as a grouping (such as a list or set) of strings

Below is a simple code snippet: for link in links: products[link] = get_products(link) In this code, the variable links should ideally be a set of strings. However, there are cases where it is just a single string, causing Python to treat it as indiv ...

Is there a way to create a more user-friendly header in Django's StackedInline for a through model that is

Currently, I am using a Django admin StackedInline setup like this: class BookInline(admin.StackedInline): model = Book.subject.through    verbose_name = 'Book' verbose_name_plural = 'Books associated with this subject' cla ...

Updating a div element dynamically using AJAX in DJANGO

Currently in the process of developing a chat application. Using jquery $.post() to add chat messages has been successful thus far. My next step is to fetch the most recent chat message from the table and update the list on the chat page. As a beginner in ...

pandas parallel coordinate plot utilizing distinct axis boundaries

Looking to create a parallel plot for a dataset with varying ranges? Check out this stunning javascript example on this website. I've prepared a sample dataset for testing and aiming to achieve a parallel plot with y-axis ticks and different-range y- ...

Avoiding error messages while attempting to import cv2

Can someone help me understand this error message? I successfully installed opencv using the command "pip install opencv-python" in Python 3 within Jupyter Notebook. import cv2 When I tried to import opencv, I encountered this TypeError: 'numpy._DT ...