如果列表中的前一个数字与下一个数字相同,如何签入列表?

2024-04-25 14:44:28 发布

您现在位置:Python中文网/ 问答频道 /正文

对于一个密码创建程序,我需要能够检查是否任何两个连续的数字在一个列表是相同的。我希望它的工作方式是这样的,当您输入一个数字,并将其附加到列表中,它会检查之前附加的数字,看看他们是否相同。你知道吗

例如,我在一个列表中输入第6个数字,它会检查它是否与第5个数字相同。你知道吗


Tags: 程序密码列表方式数字
1条回答
网友
1楼 · 发布于 2024-04-25 14:44:28

在示例3.7中,通过这个链接(dive into python),您可以发现应该从列表中调用-1元素来获取最后一个元素:

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

为了解决您的问题,您可以尝试以下方法:

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)

相关问题 更多 >

    热门问题