3 回答

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超13個(gè)贊
如果你的意思是職位
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貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超8個(gè)贊
如果您確實(shí)想將這兩個(gè)數(shù)字保留為 int,則可以使用 %(模運(yùn)算符)來查找整數(shù)除以其以 10 為基數(shù)的值后的余數(shù)。
例如。
correctnum = 0
random = 1234
guess = 1111
if ((((random-(random % 1000 )) /1000) == (((guess-(guess % 1000 )) /1000)):
correctnum++
對 100/10/1 重復(fù)的公式應(yīng)該全部比較該“位置”中的數(shù)字,而無需轉(zhuǎn)換數(shù)據(jù)類型。接下來輸出 Correctnum 的值,您應(yīng)該得到您需要的內(nèi)容。

TA貢獻(xiàn)1963條經(jīng)驗(yàn) 獲得超6個(gè)贊
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)))
添加回答
舉報(bào)