読者です 読者をやめる 読者になる 読者になる

毎日Learning

学んだことを共有します

P18 (**)リストをスライスして要素を抽出する。

def slicer(l, start, end):
    if not isinstance(l, list) or not start or not end or start > end or start > len(l) or end > len(l):
        return None
    return l[start-1:end]

if __name__ == "__main__":
    print slicer("a", 3, 5) == None
    print slicer(["a"], 0, 0) == None
    print slicer(["a"], 0, 1) == None
    print slicer(["a"], 0, 2) == None
    print slicer(["a"], 1, 0) == None
    print slicer(["a"], 1, 1) == ["a"]
    print slicer(["a"], 1, 2) == None
    print slicer(["a"], 2, 0) == None
    print slicer(["a"], 2, 1) == None
    print slicer(["a"], 2, 2) == None
    print slicer(["a", "b"], 0, 0) == None
    print slicer(["a", "b"], 0, 1) == None
    print slicer(["a", "b"], 0, 2) == None
    print slicer(["a", "b"], 0, 3) == None
    print slicer(["a", "b"], 1, 0) == None
    print slicer(["a", "b"], 1, 1) == ["a"]
    print slicer(["a", "b"], 1, 2) == ["a", "b"]
    print slicer(["a", "b"], 1, 3) == None
    print slicer(["a", "b"], 2, 0) == None
    print slicer(["a", "b"], 2, 1) == None
    print slicer(["a", "b"], 2, 2) == ["b"]
    print slicer(["a", "b"], 2, 3) == None
    print slicer(["a", "b", "c", "d", "e", "f", "g", "h", "i", "k"], 3, 7) == ["c", "d", "e", "f", "g"]