From 63ca1cdd8eb728136ad8ba01bda18a0bbef447fe Mon Sep 17 00:00:00 2001 From: yichin Date: Mon, 20 May 2019 11:10:31 +0800 Subject: [PATCH] add more test --- python_test_code/uni/population.py | 72 ++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 python_test_code/uni/population.py diff --git a/python_test_code/uni/population.py b/python_test_code/uni/population.py new file mode 100644 index 000000000..5e1b759e0 --- /dev/null +++ b/python_test_code/uni/population.py @@ -0,0 +1,72 @@ +import unittest +from random import randint + + +def pop_count(value: int) -> int: + value -= ((value >> 1) & 0x55555555) + value = (((value >> 2) & 0x33333333) + (value & 0x33333333)) + value = (((value >> 4) + value) & 0x0f0f0f0f) + value += (value >> 8) + value += (value >> 16) + return value & 0x0000003f + + +def bit_reverse(value: int) -> int: + value = (((value & 0xaaaaaaaa) >> 1) | ((value & 0x55555555) << 1)) + value = (((value & 0xcccccccc) >> 2) | ((value & 0x33333333) << 2)) + value = (((value & 0xf0f0f0f0) >> 4) | ((value & 0x0f0f0f0f) << 4)) + value = (((value & 0xff00ff00) >> 8) | ((value & 0x00ff00ff) << 8)) + return (value >> 16) | (value << 16) + + +def umc_pass_check(v1: int, v2: int) -> bool: + return pop_count(v1) + pop_count(v2) == 4 + + +class PopCountTest(unittest.TestCase): + def test_zero(self): + self.assertEqual(0, pop_count(0)) + + def test_one(self): + self.assertEqual(1, pop_count(1)) + + def test_two(self): + for _ in range(4): + a = randint(0, 8) + b = randint(0, 8) + + while a == b: + b = randint(0, 8) + + a = 1 << a + b = 1 << b + v = a | b + self.assertEqual(2, pop_count(v)) + + +class BitReverseTest(unittest.TestCase): + def test_zero(self): + self.assertEqual(0, bit_reverse(0)) + + def test_one(self): + self.assertEqual(0x8000_0000, bit_reverse(1)) + + def test_random_one(self): + for _ in range(4): + a = randint(0, 15) + b = 31 - a + + va = 1 << a + vb = 1 << b + + self.assertEqual(vb, bit_reverse(va), f"a = {a}, b = {b}") + + +class UmcPassCheckTest(unittest.TestCase): + def test_validate(self): + self.assertFalse(umc_pass_check(0b0101_0001_0100_0000_0000_0000_0000_0000, + 0b0101_0000_0000_1100_0000_0000_0000_0000)) + + +if __name__ == '__main__': + unittest.main()