问题描述
我是 Python 新手。我有一个程序可以让你猜测一个随机的 4 位密码。例如,如果密码是5530
,如果我猜到里面有一个5
(例如5111
),它说我猜对了2个数字。如果密码是 5535
,则表示我猜对了 3 个数字。
但实际上,它将我的答案中的单个 5
解释为对其他 5
是正确的。我希望它只说我猜对了一个数字,如果有两个或三个 5
,如果我为 5
输入两个 5530
,则两个正确,如果我输入三个 5
,则三个正确{1}} 代表 5535
。
import random
no1 = random.randint(0,9)
no2 = random.randint(0,9)
no3 = random.randint(0,9)
no4 = random.randint(0,9)
password = str(no1) + str(no2) + str(no3) + str(no4)
count = 0
if no1 % 2 == 0:
count += 1
if no2 % 2 == 0:
count += 1
if no3 % 2 == 0:
count += 1
if no4 % 2 == 0:
count += 1
print(password)
print(f"Hint: The password consists of {count} even number(s)")
guess = input("Guess the 4 numbers: ")
present = 0
if str(no1) in guess:
present += 1
if str(no2) in guess:
present += 1
if str(no3) in guess:
present += 1
if str(no4) in guess:
present += 1
if present == 4:
if guess == password:
print("Congrats! You have guessed the password correctly.")
else:
print("All the numbers are present but not in the correct sequence.")
print(f"You did not make it! The password is {password}.")
else:
print(f"{present} number(s) of your guess are present in the password.")
print(f"You did not make it! The password is {password}.")
PS 我希望我下面的代码可以用 range
和其他东西缩短,但我对此没有信心,所以有人可以帮我解决这个问题吗?
解决方法
改变这个:
if str(no1) in guess:
present += 1
if str(no2) in guess:
present += 1
if str(no3) in guess:
present += 1
if str(no4) in guess:
present += 1
到:
present += guess[0] == str(no1)
present += guess[1] == str(no2)
present += guess[2] == str(no3)
present += guess[3] == str(no4)
另一种方式:
rand_nums = [no1,no2,no3,no4]
for i in range(4)
if (int(guess[i]) == rand_nums[i]):
present += 1
,
您必须将密码中的每个数字与猜测中的每个数字进行比较。为此,您必须使用索引访问guess。像这样:
if str(no1) in guess[0]:
present += 1