From db9ce1dbfc525d48d4255025fe4c1209e03328a8 Mon Sep 17 00:00:00 2001 From: blueloveTH Date: Fri, 9 Dec 2022 00:48:00 +0800 Subject: [PATCH] add reversed&pop --- src/builtins.h | 11 +++++++++++ src/pocketpy.h | 9 --------- tests/listcomp.py | 24 +++++++++++++++++++++++- 3 files changed, 34 insertions(+), 10 deletions(-) diff --git a/src/builtins.h b/src/builtins.h index d26142c0..3c6fe6e0 100644 --- a/src/builtins.h +++ b/src/builtins.h @@ -64,6 +64,13 @@ def __list4index(self, value): list.index = __list4index del __list4index +def __list4pop(self, i=-1): + res = self[i] + del self[i] + return res +list.pop = __list4pop +del __list4pop + def __list4__mul__(self, n): a = [] for i in range(n): @@ -222,6 +229,10 @@ def map(f, iterable): def zip(a, b): return [(a[i], b[i]) for i in range(min(len(a), len(b)))] +def reversed(iterable): + a = list(iterable) + return [a[i] for i in range(len(a)-1, -1, -1)] + def sorted(iterable, key=None, reverse=False): if key is None: key = lambda x: x diff --git a/src/pocketpy.h b/src/pocketpy.h index 0ad26c5f..a6dce770 100644 --- a/src/pocketpy.h +++ b/src/pocketpy.h @@ -461,15 +461,6 @@ void __initializeBuiltinFunctions(VM* _vm) { return vm->PyList(vm->PyList_AS_C(args[0])); }); - _vm->bindMethod("list", "pop", [](VM* vm, const pkpy::ArgList& args) { - vm->__checkArgSize(args, 1, true); - PyVarList& _self = vm->PyList_AS_C(args[0]); - if(_self.empty()) vm->indexError("pop from empty list"); - PyVar ret = _self.back(); - _self.pop_back(); - return ret; - }); - _vm->bindMethod("list", "__add__", [](VM* vm, const pkpy::ArgList& args) { const PyVarList& _self = vm->PyList_AS_C(args[0]); const PyVarList& _obj = vm->PyList_AS_C(args[1]); diff --git a/tests/listcomp.py b/tests/listcomp.py index 22554eeb..f1ca1e85 100644 --- a/tests/listcomp.py +++ b/tests/listcomp.py @@ -5,4 +5,26 @@ a = [i for i in range(10) if i % 2 == 0] assert a == [0, 2, 4, 6, 8] a = [i**3 for i in range(10) if i % 2 == 0] -assert a == [0, 8, 64, 216, 512] \ No newline at end of file +assert a == [0, 8, 64, 216, 512] + +a = [1, 2, 3, 4] +assert a.pop() == 4 +assert a == [1, 2, 3] +assert a.pop(0) == 1 +assert a == [2, 3] +assert a.pop(-2) == 2 +assert a == [3] + +a = [1, 2, 3, 4] +assert reversed(a) == [4, 3, 2, 1] +assert a == [1, 2, 3, 4] +a = (1, 2, 3, 4) +assert reversed(a) == [4, 3, 2, 1] +assert a == (1, 2, 3, 4) +a = '1234' +assert reversed(a) == ['4', '3', '2', '1'] +assert a == '1234' + +assert reversed([]) == [] +assert reversed('') == [] +assert reversed('测试') == ['试', '测'] \ No newline at end of file