What it is about
I created an application where you need to push invisible buttons in a certain order to unlock the advanced mode. To handle this, I wanted to use a queue (FIFO) of my own, adapted to my problem.
Every time I click a button, its ID is added to the queue with addItem
, and the password gets checked with checkCorrect
. It is meant to work similarly to digicode doors. The size
attribute determines how many values the queue can remember, hence the maximum length of the password.
What I'd like to know
Do you think this is a good code? In which ways can it be improved? Are there other ways (with smaller / more elegant code) to implement this?
The code
class MyQueue():
def __init__(self, size, default_value=None):
self.size = size
self.content = [default_value]*size
self.end = self.size-1
def addItem(self, value):
self.end = (self.end+1) % self.size
self.content[self.end] = value
def printQueue(self):
print 'end='+str(self.end)+' - '+str(self.content)
def checkCorrect(self, password):
pw = list(reversed(password))
i = 0
j = self.end
if len(pw) > self.size:
return False
while True:
if pw[i] <> self.content[j]:
return False
else:
i += 1
j = (j-1) % self.size
if i == len(pw):
return True
if __name__=='__main__':
q = MyQueue(size=4, default_value=0)
q.addItem(1)
q.addItem(8)
q.addItem(8)
q.addItem(5)
q.addItem(7)
q.addItem(3)
print q.checkCorrect([5, 7, 3])
print q.checkCorrect([2, 7, 3])
defaultValue
? You meantdefault_value
I guess? More, do NOT use<>
operator. It's kind of unusual and unsupported in Python 3.5 (even if you're using python 2.7). Use!=
instead. You're code as it is, it's off-topic. Please edit it. \$\endgroup\$ – Grajdeanu Alex Jul 8 '16 at 12:08<>
and!=
, do you want to make it an answer ? Besides, please how can I make this less off-topic ? I don't understand how it is off-topic in the first place... \$\endgroup\$ – BusyAnt Jul 8 '16 at 12:09