我必须做一个程序,检查4号字符串中是否有重复的数字。 问题是,80%的时间程序将无效的数字分类为无效的数字。
import random
def extraction():
random_number = str(random.randint(1000,9999))
print(random_number)
for number in random_number:
n = 0
print("number1 ",number)
for number2 in random_number:
print("number2 ",number2)
if(number == number2):
n = n + 1
print("n ",n)
if(n == 2):
print("The extracted number is not valid.\n")
extraction()
答案 0 :(得分:4)
为什么不从数字字符串中创建set()
并评估集合的长度?如果有重复的数字,则只有一个条目存储在集合
if len(set(str(random_number))) == 4:
pass #you have 4 unique digits
工作原理示例:
>>> set('1234') set(['1', '3', '2', '4']) >>> set('1123') set(['1', '3', '2'])
答案 1 :(得分:0)
为什么不使用str.count()
功能?
def extraction():
random_number = str(random.randint(1000,9999))
print(random_number)
if any([random_number.count(i)>1 for i in random_number]):
print("The extracted number is not valid.\n")
extraction()