Last active
November 20, 2015 18:38
-
-
Save zsrinivas/c0c2ee1e7c6535ef8c3d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class defaultlist(object): | |
def __init__(self, factory, data=None): | |
self.factory = factory | |
self.list = [] | |
self.data = data | |
def __getitem__(self, x): | |
if x >= len(self.list): | |
self.list.extend([self.factory() for _ in range(len(self.list), x + 1)]) | |
return self.list[x] | |
def __repr__(self): | |
return str(self) | |
def __str__(self): | |
if len(self.list) == 0: | |
return '(' + str(self.data) + ')[...]' | |
return ''.join(['(', str(self.data), ')[', ', '.join(map(str, self.list)), ', ...]']) | |
def __setitem__(self, x, v): | |
if x >= len(self.list): | |
self.list.extend([self.factory() for _ in range(len(self.list), x + 1)]) | |
self.list[x] = v | |
def main(): | |
factory = lambda: defaultlist(factory) | |
list_of_lists = defaultlist(factory) | |
print (list_of_lists[0]) | |
list_of_lists[0][3].data = 20 | |
print (list_of_lists[0]) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment