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

Get a random element from a BTree #185

Open
azmeuk opened this issue Sep 19, 2022 · 2 comments
Open

Get a random element from a BTree #185

azmeuk opened this issue Sep 19, 2022 · 2 comments

Comments

@azmeuk
Copy link
Member

azmeuk commented Sep 19, 2022

I would love to have a performant way to get a random element out of a BTree.

At the moment I use random.choice (random.choice(mybtree.keys())), but internally it calls len on the ITreeItems, and on large BTrees (>200k items) the operation is long enough (3~4s on my computer) to not fit a web request expectations.

Due to the nature of BTrees, I would expect that this would not be hard to build a pseudo-random method that would go through random child BTrees until it meets a leaf bucket, and then choose a random item in it. This would not exactly be randomness if the tree is not perfectly balanced but this would be good enough in my opinion.

What do you think? Did I miss a simpler way to get a random element? Would such a PR be OK?

@d-maurer
Copy link
Contributor

d-maurer commented Sep 19, 2022 via email

@azmeuk
Copy link
Member Author

azmeuk commented Sep 19, 2022

Buckets are the leaves of a BTree. Thus, your terminology is not optimal.

Indeed. Maybe go through random child BTrees until it meets a leaf bucket, and then choose a random item in it is a better reformulation.

I will have a look at the check module.

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

2 participants