builtin_sorted.pyx 2.04 KB
Newer Older
1 2
cimport cython

3

4 5 6 7 8
def generator():
    yield 2
    yield 1
    yield 3

9

10
def returns_set():
11
    return {"foo", "bar", "baz"}
12

13

14 15 16
def returns_tuple():
    return (1, 2, 3, 0)

17

18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
@cython.test_fail_if_path_exists("//SimpleCallNode")
def sorted_arg(x):
    """
    >>> a = [3, 2, 1]
    >>> sorted_arg(a)
    [1, 2, 3]
    >>> a
    [3, 2, 1]
    >>> sorted(generator())
    [1, 2, 3]
    >>> sorted(returns_set())
    ['bar', 'baz', 'foo']
    >>> sorted(returns_tuple())
    [0, 1, 2, 3]
    >>> sorted(object())
    Traceback (most recent call last):
    TypeError: 'object' object is not iterable
    """
    return sorted(x)

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

@cython.test_assert_path_exists("//GeneralCallNode")
def sorted_arg_with_key(x):
    """
    >>> a = [3, 2, 1]
    >>> sorted_arg_with_key(a)
    [3, 2, 1]
    >>> a
    [3, 2, 1]
    >>> sorted_arg_with_key(generator())
    [3, 2, 1]
    >>> sorted_arg_with_key(returns_tuple())
    [3, 2, 1, 0]
    >>> sorted_arg_with_key(object())
    Traceback (most recent call last):
    TypeError: 'object' object is not iterable
    """
    return sorted(x, key=lambda x: -x)


58 59 60
@cython.test_fail_if_path_exists("//YieldExprNode",
                                 "//NoneCheckNode")
@cython.test_assert_path_exists("//InlinedGeneratorExpressionNode")
61 62 63 64 65 66 67
def sorted_genexp():
    """
    >>> sorted_genexp()
    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    """
    return sorted(i*i for i in range(10,0,-1))

68

Stefan Behnel's avatar
Stefan Behnel committed
69 70
@cython.test_fail_if_path_exists("//SimpleCallNode//SimpleCallNode")
@cython.test_assert_path_exists("//SimpleCallNode/NameNode[@name = 'range']")
71
def sorted_list_of_range():
72
    """
73
    >>> sorted_list_of_range()
74 75 76
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    """
    return sorted(list(range(10,0,-1)))
77

78

79 80 81 82 83 84 85 86
@cython.test_fail_if_path_exists("//SimpleCallNode")
def sorted_list_literal():
    """
    >>> sorted_list_literal()
    [1, 1, 2, 2, 3, 3]
    """
    return sorted([3, 1, 2] * 2)

87

88 89 90 91 92 93 94
@cython.test_fail_if_path_exists("//SimpleCallNode")
def sorted_tuple_literal():
    """
    >>> sorted_tuple_literal()
    [1, 1, 2, 2, 3, 3]
    """
    return sorted((1, 3, 2) * 2)