Created
June 28, 2016 19:08
-
-
Save rjurney/d7913221dd38bee9708716f50c3c002e to your computer and use it in GitHub Desktop.
A hashable python list that maintains order when hashed
This file contains 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 FrozenSortedList: | |
'''A frozenset that cares about order of tuples. And is not actually frozen.''' | |
def __init__(self, vals): | |
if type(vals) not in [list, set, tuple]: | |
raise Exception('Value not a list or set') | |
self.vals = vals | |
def __len__(self): | |
return len(self.vals) | |
def __iter__(self): | |
return iter(self.vals) | |
def __getitem__(self, key): | |
return list(self.vals)[key] | |
def __eq__(self, other): | |
if len(self) != len(other): | |
print "len(self)" | |
return False | |
for i,item in enumerate(self.vals): | |
if item != other[i]: | |
return False | |
return True | |
def __str__(self): | |
str_val = '[' | |
for val in self: | |
if(type(val) == str): | |
str_val += '\'' | |
str_val += val | |
str_val += '\'' | |
else: | |
str_val += str(val) | |
str_val += ',' | |
if len(str_val) > 2: | |
str_val = str_val[:-1] | |
str_val += ']' | |
return str_val | |
def __hash__(self): | |
return hash(str(self)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment