Skip to content

Instantly share code, notes, and snippets.

@maxrothman
Created January 7, 2015 15:38
Show Gist options
  • Save maxrothman/fbc17ca2c99822af7546 to your computer and use it in GitHub Desktop.
Save maxrothman/fbc17ca2c99822af7546 to your computer and use it in GitHub Desktop.
Handy Python datatypes
class Board(list):
'''Interprets board[1,2] as board[1][2]'''
def __getitem__(self, key):
try:
cur = self
key = list(key)
while len(key) > 0:
cur = list.__getitem__(cur, key.pop(0))
return cur
except TypeError:
return list.__getitem__(self, key)
def __setitem__(self, key, val):
try:
self.__getitem__(key[:-1])[key[-1]] = val
except TypeError:
list.__setitem__(self, key, val)
class Vec(tuple):
'''Allows for vector addition, e.g. (1,2) + (3,4) = (4,6)'''
def __add__(self, other):
if len(self) != len(other):
raise ValueError("Cannot add vectors with different numbers of dimensions")
return Vec(i+j for i,j in zip(self, other))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment