Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: return index where item is added when calling SortedList.add() #195

Closed
MarrickLip opened this issue Jul 23, 2022 · 3 comments
Closed

Comments

@MarrickLip
Copy link

MarrickLip commented Jul 23, 2022

Hi,

For a use case I'm working with at the moment (today's LeetCode.com challenge 🤓) it is necessary to know the index at which an item gets inserted to after calling s.add(item), where s is a SortedList.

However, the add method returns nothing and so I have to call s.bisect_left(item) to get the index and then s.add(item) to perform the update. This is a waste of computation, however.

Currently s.add(item) returns nothing so it would be a backwards compatible change to return the index where the item is added. I had a look at sortedlist.py and it appears that this would be a fairly straight forward feature to implement, but I couldn't go about it myself as I can't wrap my head around a few edge cases e.g. how best to handle when the inserted item already exists and hence the index it enters is arbitrary.

Thanks,

Marrick.

@grantjenks
Copy link
Owner

Getting the index of the item requires the positional index to be built which add() specifically avoids. I think this is a fine example for simply inheriting and implementing the needed functionality in your own code.

The other problem is that bisect.insort doesn’t return the index and that’s what’s used by the library. Get that changed in Python and the project could benefit.

@MarrickLip
Copy link
Author

Gotcha! Thanks for looking into it though :D

@Serpens66
Copy link

Gotcha! Thanks for looking into it though :D

I just asked the same question (sorry for not searching properly).
Did you MarrickLip implement your own function that does this and is still faster than doing both operations one after the other?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants