Python:检测重复和连续的数字

2024-04-19 20:23:20 发布

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

说明: “创建一个python程序来检测10位数字是否有效。数字应该有10位数字,不能包含数字“0”,也不能包含重复的连续数字。“

…我正在使用append请求10个数字,并验证它们是否与0不同,但我仍然不知道如何查看这些数字是否连续。你知道吗

到目前为止,我的情况是:

list=[]
for num in range (1,10): #Request 10 numbers (it can't be zero)
    num=int (input("Add 10 digits:"))
    list.append (num)
    while num != 0:
        print ("The number is valid.")

Tags: in程序forrequest情况rangeit数字
2条回答

提示:

  • 使用str()函数将数字转换为字符串
  • 使用len()函数验证长度
  • 使用in运算符来验证数字是否包含零
  • 使用zip(s, s[1:])作为将连续字符组合在一起的简单方法

使用while,因为如果有重复的数字,for将在结束之前结束循环

mylist=[]
while len(mylist) < 10: #Request 10 numbers (it can't be zero)
    mylistLength = str(len(mylist))
    num=int(input("Add 10 digits [" + mylistLength +"]: "))
    if num not in mylist:
      mylist.append(num)
    else:
      num=int(input("Digit exist, try other: "))
    if len(mylist) == 10:
        print("The number is valid.")

print(mylist)

相关问题 更多 >