Python/sage: can lists start at index 1?

后端 未结 5 1089
逝去的感伤
逝去的感伤 2021-01-04 13:25

I\'ve downloaded from a supposedly serious source a sage script. It doesn\'t work on my computer, and a quick debugging showed that a problem came from the fact that at some

5条回答
  •  说谎
    说谎 (楼主)
    2021-01-04 14:04

    A simple class that shifts the index for you provides a clean interface to something reusable.

    class Array(object):
    
        def __init__(self, items: list) -> None:
            self.items = items
    
        def __repr__(self) -> str:
            return '{}({})'.format(self.__class__.__name__, self.items)
    
        def __len__(self) -> int:
            return len(self.items)
    
        def __contains__(self, item: any) -> bool:
            return item in self.items
    
        def __getitem__(self, key: int) -> any:
            return self.items[key - 1]
    
        def __setitem__(self, key: int, value: any) -> None:
            self.items[key - 1] = value
    
        def __delitem__(self, key: int) -> None:
            del self.items[key - 1]
    

提交回复
热议问题