Skip to content

Tag: optimization

A weighted version of random.choice

I needed to write a weighted version of random.choice (each element in the list has a different probability for being selected). This is what I came up with: This function seems overly complex to me, and ugly. I’m hoping everyone here can offer some suggestions on improving it or alternate ways of doing…

Fastest way to list all primes below N

This is the best algorithm I could come up. Can it be made even faster? This code has a flaw: Since numbers is an unordered set, there is no guarantee that numbers.pop() will remove the lowest number from the set. Nevertheless, it works (at least for me) for some input numbers: Answer Warning: timeit results …

How to iterate over a list in chunks

I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don’t have control of the input, or I’d have it passed in as a list of four-element tuples. Currently, I’m iterating over it this way: It looks a lot like &#822…