Skip to content

Instantly share code, notes, and snippets.

@Kautenja
Created February 19, 2018 20:23
Show Gist options
  • Save Kautenja/f45bb890639c44133a672193afbf5e42 to your computer and use it in GitHub Desktop.
Save Kautenja/f45bb890639c44133a672193afbf5e42 to your computer and use it in GitHub Desktop.
A simple conversion of a Python list to an array indexed from 1 for algorithm analysis
class Array(object):
"""A list that indexes like an array [1...n] (for algorithm analysis)."""
def __init__(self, items: list) -> None:
"""Create a new array from a list."""
self.items = items
def __repr__(self) -> str:
"""Return an executable string represention of `self`."""
return '{}({})'.format(self.__class__.__name__, self.items)
def __len__(self) -> int:
"""Return the length of `self`."""
return len(self.items)
def __contains__(self, item: any) -> bool:
"""Return a boolean determining if `item` is in `self`."""
return item in self.items
def __getitem__(self, index: int) -> any:
"""Return the item at the given `index`."""
return self.items[index - 1]
def __setitem__(self, index: int, value: any) -> None:
"""Set a new item at the given `index`."""
self.items[index - 1] = value
def __delitem__(self, index: int) -> None:
"""Delete the item at the given `index`."""
del self.items[index - 1]
def __add__(self, other: 'Array') -> 'Array':
"""Return a new array of `self` concatenated with `other`."""
return Array(self.items + other.items)
def __mul__(self, scalar: int) -> 'Array':
"""Return a new array of `self` repeated `scalar` times."""
return Array(scalar * self.items)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment