-4

For a password creation program I need to be able to check if any two consecutive numbers in a list are the same. I would like it to work in such a way that when you input a number and it is appended to the list, it checks the previously appended number to see if they are the same.

For example, I enter the 6th number to a list and it checks to see if it's the same as the 5th number.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
James Brightman
  • 857
  • 2
  • 13
  • 23
  • 1
    Have you tried anything so far? With what results? – jonrsharpe Oct 19 '15 at 13:04
  • 1
    Have you read any documentation about `list` access (particularly negative indices)? – TigerhawkT3 Oct 19 '15 at 13:05
  • The problem is I haven't tried anything as I am pretty stuck, also I have tried googling / looking up how to do this but have only found methods for finding a number in a list, not comparing two consecutive numbers. – James Brightman Oct 19 '15 at 13:06
  • 1
    Check [Detecting consecutive integers in a list](http://stackoverflow.com/questions/2361945/detecting-consecutive-integers-in-a-list) – sam Oct 19 '15 at 13:09
  • please post your code – KingMak Oct 19 '15 at 13:14
  • I would If I could get this darn formatting working – James Brightman Oct 19 '15 at 13:22
  • [The official tutorial's section on `list`s](https://docs.python.org/3.4/tutorial/introduction.html#lists) has something useful for you in the second code block. – TigerhawkT3 Oct 19 '15 at 13:23
  • Dupe of http://stackoverflow.com/questions/33116880/how-do-i-check-if-two-consecutive-numbers-integers-in-a-list-have-the-same-val ? – pR0Ps Oct 19 '15 at 14:27

1 Answers1

0

In Example 3.7 from this link (dive into python) you can find that You should call -1 element from the list to get the last element:

 l = [0, 1, 2]
 print l[-1]

For solving your problem, you can try something like this:

class PasswordChecker:
    def __init__(self):
        self.passwd = list()

    def appendNumber(self,numberToAppend):
        if(len(self.passwd)>0):
            if(self.passwd[-1] + 1 == numberToAppend):
                # here i'm raising an exception
                # but You can apply any other logic You want
                raise Exception("Cannot use two consecutive numbers!!!")

        self.passwd.append(numberToAppend)

    def getPassword(self):
        return self.passwd


pc = PasswordChecker()

# read (keyboard/file) first number
r = 0

pc.appendNumber(r)

# read next number
r = 3

pc.appendNumber(r)

# read next number
r = 4

pc.appendNumber(r)
wasiek
  • 66
  • 3