Skip to content

Instantly share code, notes, and snippets.

Created May 21, 2013 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/5621241 to your computer and use it in GitHub Desktop.
Save anonymous/5621241 to your computer and use it in GitHub Desktop.
Given a list of 10k 32-bit integers, calculate the number of set bits in each. Quickly.
import random
data = list()
for i in range(10000):
data.append(random.randint(0, 2**32))
bits_set = {0: 0}
for i in range(256):
bits_set[i] = (i & 1) + bits_set[i / 2]
def count_ones(x):
return (
bits_set[x & 255] + bits_set[(x >> 8) & 255] +
bits_set[(x >> 16) & 255] + bits_set[(x >> 24) & 255])
for x in data:
print '%s: %s: %s' % (x, bin(x), count_ones(x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment