Move some utility functions into the cdsl package.

- is_power_of_two
- next_power_of_two

Make sure we run doctests on these functions.
This commit is contained in:
Jakob Stoklund Olesen
2016-11-11 13:04:30 -08:00
parent 77c672a279
commit c20d7d8f13
4 changed files with 53 additions and 28 deletions

View File

@@ -13,5 +13,47 @@ camel_re = re.compile('(^|_)([a-z])')
def camel_case(s):
# type: (str) -> str
"""Convert the string s to CamelCase"""
"""Convert the string s to CamelCase:
>>> camel_case('x')
'X'
>>> camel_case('camel_case')
'CamelCase'
"""
return camel_re.sub(lambda m: m.group(2).upper(), s)
def is_power_of_two(x):
# type: (int) -> bool
"""Check if `x` is a power of two:
>>> is_power_of_two(0)
False
>>> is_power_of_two(1)
True
>>> is_power_of_two(2)
True
>>> is_power_of_two(3)
False
"""
return x > 0 and x & (x-1) == 0
def next_power_of_two(x):
# type: (int) -> int
"""
Compute the next power of two that is greater than `x`:
>>> next_power_of_two(0)
1
>>> next_power_of_two(1)
2
>>> next_power_of_two(2)
4
>>> next_power_of_two(3)
4
>>> next_power_of_two(4)
8
"""
s = 1
while x & (x + 1) != 0:
x |= x >> s
s *= 2
return x + 1

View File

@@ -0,0 +1,8 @@
from __future__ import absolute_import
import doctest
import cdsl
def load_tests(loader, tests, ignore):
tests.addTests(doctest.DocTestSuite(cdsl))
return tests

View File

@@ -6,7 +6,7 @@ polymorphic by using type variables.
"""
from __future__ import absolute_import
import math
from . import types
from . import types, is_power_of_two
try:
from typing import Tuple, Union # noqa
@@ -20,11 +20,6 @@ MAX_LANES = 256
MAX_BITS = 64
def is_power_of_two(x):
# type: (int) -> bool
return x > 0 and x & (x-1) == 0
def int_log2(x):
# type: (int) -> int
return int(math.log(x, 2))

View File

@@ -6,6 +6,7 @@ don't attempt parfect hashing, but simply generate an open addressed
quadratically probed hash table.
"""
from __future__ import absolute_import
from cdsl import next_power_of_two
def simple_hash(s):
@@ -24,27 +25,6 @@ def simple_hash(s):
return h
def next_power_of_two(x):
"""
Compute the next power of two that is greater than `x`:
>>> next_power_of_two(0)
1
>>> next_power_of_two(1)
2
>>> next_power_of_two(2)
4
>>> next_power_of_two(3)
4
>>> next_power_of_two(4)
8
"""
s = 1
while x & (x + 1) != 0:
x |= x >> s
s *= 2
return x + 1
def compute_quadratic(items, hash_function):
"""
Compute an open addressed, quadratically probed hash table containing