Python:随机猜测4位密码,无法解决1个问题

2024-06-26 12:57:21 发布

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

我是Python新手。我有一个程序,让你猜一个随机的4位密码。例如,如果密码是5530,如果我猜里面有一个5(例如5111),它说我猜对了两个数字。如果密码是5535,它说我正确地猜到了3个数字

但实际上,它解释了我答案中的单个5对于其他5是正确的。我只想说,如果有两个或三个5,我猜对了一个数字;如果我为5530键入了两个5,我猜对了两个;如果我为5535键入了三个5,我猜对了三个

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}.")

p.S.我希望我下面的代码可能会被range之类的东西缩短,但我没有信心这样做,所以有人能帮我吗


Tags: theinifcountrandompasswordprintrandint
2条回答

更改此项:

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中的每个数字进行比较。为此,您必须使用索引访问guess。像这样:

if str(no1) in guess[0]:

    present += 1

相关问题 更多 >