You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python乘法闪卡程序:如何避免重复数字组合并校验已展示数对

解决方案:跟踪已展示的数字组合来避免重复

要解决这个问题,核心思路是维护一个集合来记录已经展示过的数字组合——由于乘法满足交换律(比如2×3和3×2本质是同一个题目),我们需要把组合处理成无序的形式(比如排序后的元组),这样就能统一判断是否重复。

下面是具体的实现步骤和修改后的代码:

关键逻辑说明

  • 用集合shown_pairs存储已展示的组合:集合的特性是自动去重,且检查元素存在性的效率很高。
  • 统一组合的表示形式:每次生成随机数后,将两个数排序并转成元组(比如(3,2)会变成(2,3)),这样交换顺序的组合会被视为同一个。
  • 重复组合跳过:如果生成的组合已经在集合里,就重新生成新的组合;如果不在,就将其加入集合,然后继续提问。
  • 新增全组合完成逻辑:当所有不重复的乘法组合都展示完后,自动退出循环并展示成绩。

修改后的完整代码

from __future__ import division
import random

amountCorrect = 0
amountMissed = 0
# 初始化集合存储已展示的组合
shown_pairs = set()
# 计算总共有多少种不重复的组合:12个自身相乘 + C(12,2)个两两不同的组合
total_possible = 12 + (12 * 11) // 2

print("Type 0 at any time to exit and see your score.")
while True:
    # 检查是否所有组合都已展示
    if len(shown_pairs) >= total_possible:
        print("\nAll possible multiplication pairs have been shown!")
        break
        
    firstNumber = random.randint(1,12)
    secondNumber = random.randint(1,12)
    # 将组合转为排序后的元组,统一交换顺序的情况
    current_pair = tuple(sorted((firstNumber, secondNumber)))
    
    # 如果这个组合已经展示过,跳过本次循环重新生成
    if current_pair in shown_pairs:
        continue
    
    # 标记该组合已展示
    shown_pairs.add(current_pair)
    
    ans = input(f"What is {firstNumber} x {secondNumber}: ")
    # 处理用户输入,先判断是否是0(退出)
    if ans.strip() == "0":
        break
    # 尝试转换为整数,处理非数字输入的情况(可选优化)
    try:
        ans = int(ans)
    except ValueError:
        print("Please enter a valid number or 0 to exit.")
        continue
        
    if ans == firstNumber * secondNumber:
        amountCorrect += 1
        print("Correct! 🎉")
    else:
        amountMissed += 1
        print(f"Oops, the right answer is {firstNumber * secondNumber}.")

if amountCorrect + amountMissed > 0:
    totalProblems = amountCorrect + amountMissed
    percentCorrect = amountCorrect / totalProblems
    print("\n--- Your Score ---")
    print(f"Correct: {amountCorrect}, Missed: {amountMissed}")
    print(f"Accuracy: {percentCorrect:.2%}")
    
    if .9 < percentCorrect <= 1:
        print("Great job, you are doing awesome!")
    elif .7 <= percentCorrect <= .89:
        print("You are doing well, keep it up.")
    elif .5 <= percentCorrect <= .69:
        print("You are half way to becoming a master.")
    else:
        print("Keep practicing, you will be a master one day.")
else:
    print("You didn't attempt any problems.")

额外优化点

  1. 输入合法性校验:如果用户输入非数字内容,会提示重新输入,避免程序崩溃。
  2. 完成反馈:当所有不重复的乘法组合都展示过之后,自动退出并显示分数。
  3. 代码可读性提升:使用f-string简化字符串拼接,逻辑更清晰。
  4. 即时反馈:答题后立刻给出正确/错误提示,提升用户练习体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 06:29:04