You need to enable JavaScript to run this app. Python 4位随机密码猜数字程序重复数字计数异常问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Python 4位随机密码猜数字程序重复数字计数异常问题求助

问题原因

现有代码的计数逻辑是逐个校验密码每一位数字是否在猜测输入中存在,只要存在就计数+1。当密码包含重复数字时,只要猜测输入出现1次对应数字,密码中所有该数字的位置都会命中计数,就会出现重复多算的问题。

优化后完整代码

import random

# 用range循环生成4位密码,不用单独定义4个变量
password = ''.join(str(random.randint(0,9)) for _ in range(4))
# 统计偶数个数
even_count = sum(1 for c in password if int(c) % 2 == 0)

print(password)
print(f"Hint: The password consists of {even_count} even number(s)")

guess = input("Guess the 4 numbers: ")
present = 0
# 转成可变列表方便匹配后删除,避免重复计数
guess_list = list(guess)

for num in password:
    if num in guess_list:
        present += 1
        guess_list.remove(num)

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

核心调整说明

  • 生成密码、统计偶数个数都用range配合生成式完成,删除了重复的4个变量定义和4次单独判断逻辑,代码更简洁易维护
  • 计数匹配数字时,将猜测输入转成列表,每匹配到一个数字就从列表中删除该元素,确保每个猜测的数字只能被匹配一次,完全符合你要求的计数规则:密码有N个重复数字时,只有猜测输入也有至少N个对应数字才会计数N次

如果你更喜欢更简洁的计数写法,也可以用collections.Counter实现相同逻辑:

from collections import Counter

pwd_counter = Counter(password)
guess_counter = Counter(guess)
present = sum(min(pwd_counter[d], guess_counter[d]) for d in pwd_counter)

内容的提问来源于stack exchange,提问作者Thac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 19:27:04