From the course: Faster Python Code

Unlock this course with a free trial

Join today to access over 25,500 courses taught by industry experts.

Pre-calculating

Pre-calculating

- [Narrator] We'd like to count how many beats in a number for set one. This is sometimes known as pop count for population count. Knowing the number of set base is useful in several algorithms such as hemmingway. Here's an implementation. In line four, we have nbits, which does the wire loop on the number and checks how many beats are there and in line 16, we define a test for that, which checks the number of beats. And in the main in line 28, we call this test. Let's try it out. So ipython. And then we run nbits.py. And since we don't have an error, we're good to go. And now we can time. Time it nbits of, let's say, 350. It's 1.07 microseconds. How can we speed this up? The test might be less than ideal. We can precalculate the value for each number once and then we turn these values. This works well with the numbers are bounded by size. Let's assume that our numbers can have a maximum of 16 beats. What's the…

Contents