Using Python 3.4
I've got a way that works, but I think there might be a better way.
I want to have a list with a method expand() which chooses a random element from the list, but every time that element is chosen, a counter is incremented. I tried subclassing str to be able to add attributes but it didn't work.
My main problem with what I've got is that the expression random.randint(0,len(self)-1) and using a local variable doesn't seem very Pythonic. Before I added the counter, I could just type random.choice(self)
class clauses(list):
def __init__(self):
self.uses = []
def __setitem__(self,key,value):
self.uses[key]=value
super().__setitem__(self,key,value)
def __delitem__(self,key):
del(self.uses[key])
super().__delitem__(key)
def append(self,value):
self.uses.append(0)
super().append(value)
def extend(self,sequence):
for x in sequence:
self.uses.append(0)
super().append(x)
def expand(self):
n = random.randint(0,len(self)-1)
self.uses[n] += 1
return(self[n])
random.randint(0, len(self) - 1)userandom.randrange(0, len(self)), which has existed ever since Python 1.5.2self.uses[key]=valuebe insteadself.uses[key] = 0? Seems that otherwise you're setting the counter to the value in the list...listsupports slice indexing (i.e. thekeyin__setitem__and__delitem__could be a slice object).myDict[element] = 0when added andmyDict[element]+=1when chosen...