3 回答
TA贡献1836条经验 获得超13个赞
如果你的意思是职位
random = random.randint(1000, 9999)
guess = int(input("Enter your guess: "))
while guess != random:
right = 0
index = 0
for char in str(guess):
if char == str(random)[index]:
index += 1
right += 1
print(f'{right} were right')
guess = int(input("That was incorrect! Enter your guess: "))
TA贡献1804条经验 获得超8个赞
如果您确实想将这两个数字保留为 int,则可以使用 %(模运算符)来查找整数除以其以 10 为基数的值后的余数。
例如。
correctnum = 0
random = 1234
guess = 1111
if ((((random-(random % 1000 )) /1000) == (((guess-(guess % 1000 )) /1000)):
correctnum++
对 100/10/1 重复的公式应该全部比较该“位置”中的数字,而无需转换数据类型。接下来输出 Correctnum 的值,您应该得到您需要的内容。
TA贡献1963条经验 获得超6个赞
random = 1234
random = str(random)
#guess = str(input('enter your guess'))
guess = '1222'
correct = 0
for i in range(len(guess)):
if guess[i] == random[i]:
correct += 1
print(correct)
ouput: 2
或者简单地:
correct = sum(guess[i] == random[i] for i in range(len(guess)))
添加回答
举报