repl.it
@anonymous/

ThankfulAcceptableCodegeneration

Python

No description

fork
loading
Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def merge_sorted_1(xs, ys):
    res = []
    xs_i, ys_i = iter(xs), iter(ys)
    x, y = next(xs_i, None), next(ys_i, None)
    while x is not None and y is not None:
        if x < y:
            res.append(x)
            x = next(xs_i, None)
        elif y < x:
            res.append(y)
            y = next(ys_i, None)
        else:
            res.append(x)
            x, y = next(xs_i, None), next(ys_i, None)
    if x is not None:
        res.append(x)
    if y is not None:
        res.append(y)
    res += xs_i
    res += ys_i
    return res


def merge_sorted_2(a1, a2):
    return sorted(list(set(a1).union(set(a2))))


from random import randrange


import timeit

for l, i in ( (10000, 50), (100000, 5), (1000000, 1)):
    print('list length:', l, 'iterations:', i)
    xs = sorted(list(set(randrange(l * l) for _ in range(l))))
    ys = sorted(list(set(randrange(l * l) for _ in range(l))))
    print('merge_sorted_1', timeit.timeit(
        'merge_sorted(xs, ys)',
        number=i,
        globals={
            'merge_sorted': merge_sorted_1,
            'xs': xs.copy(),
            'ys': ys.copy()
        }))

    print('merge_sorted_2', timeit.timeit(
        'merge_sorted(xs, ys)',
        number=i,
        globals={
            'merge_sorted': merge_sorted_2,
            'xs': xs.copy(),
            'ys': ys.copy()
        }))

    print('-' * 70)
?