Debian Codegraph @

rpython/rlib/test/test_listsort.py

raw symbols SCIP
1 import py
2 from rpython.rlib.listsort import TimSort, powerloop
3 import random, os
4
5 from hypothesis import given, strategies as st, example
6
7 def makeset(lst):
8 result = {}
9 for a in lst:
10 result.setdefault(id(a), []).append(True)
11 return result
12
13 class TestTimSort(TimSort):
14 def merge_compute_minrun(self, n):
15 return 1 # that means we use the "timsorty" bits of the algorithm more
16 # than just mostly binary insertion sort
17
18 def sorttest(lst1):
19 _sorttest(TimSort, lst1)
20 _sorttest(TestTimSort, lst1)
21
22 def _sorttest(cls, lst1):
23 lst2 = lst1[:]
24 cls(lst2).sort()
25 assert len(lst1) == len(lst2)
26 assert makeset(lst1) == makeset(lst2)
27 position = {}
28 i = 0
29 for a in lst1:
30 position.setdefault(id(a), []).append(i)
31 i += 1
32 for i in range(len(lst2)-1):
33 a, b = lst2[i], lst2[i+1]
34 assert a <= b, "resulting list is not sorted"
35 if a == b:
36 assert position[id(a)][0] < position[id(b)][-1], "not stable"
37
38
39 class C(int):
40 pass
41
42 def test_v():
43 for v in range(137):
44 up = 1 + int(v * random.random() * 2.7)
45 lst1 = [C(random.randrange(0, up)) for i in range(v)]
46 sorttest(lst1)
47
48 @given(st.lists(st.integers(), min_size=2))
49 def test_hypothesis(l):
50 sorttest(l)
51
52 def test_file():
53 for fn in py.path.local(__file__).dirpath().listdir():
54 if fn.ext == '.py':
55 lines1 = fn.readlines()
56 sorttest(lines1)
57
58
59 def power(s1, n1, n2, n):
60 # from Tim's Python sketch code here: https://bugs.python.org/issue34561
61 assert s1 >= 0
62 assert n1 >= 1 and n2 >= 1
63 assert s1 + n1 + n2 <= n
64 # a = s1 + n1/2
65 # b = s1 + n1 + n2/2 = a + (n1 + n2)/2
66 a = 2*s1 + n1 # 2*a
67 b = a + n1 + n2 # 2*b
68 # Array length has d bits. Max power is d:
69 # b/n - a/n = (b-a)/n = (n1 + n2)/2/n >= 2/2/n = 1/n > 1/2**d
70 # So at worst b/n and a/n differ in bit 1/2**d.
71 # a and b have <= d+1 bits. Shift left by d-1 and divide by 2n =
72 # shift left by d-2 and divide by n. Result is d - bit length of
73 # xor. After the shift, the numerator has at most d+1 + d-2 = 2*d-1
74 # bits. Any value of d >= n.bit_length() can be used.
75 d = n.bit_length() # or larger; smaller can fail
76 a = (a << (d-2)) // n
77 b = (b << (d-2)) // n
78 return d - (a ^ b).bit_length()
79
80
81 @example(s1=0, n1=2, n2=2, moreitems=0)
82 @given(st.integers(min_value=0), st.integers(min_value=2), st.integers(min_value=2), st.integers(min_value=0))
83 def test_powerloop_equal_power(s1, n1, n2, moreitems):
84 n = s1 + n1 + n2 + moreitems
85 assert powerloop(s1, n1, n2, n) == power(s1, n1, n2, n)
86