检查是否在组合列表中找到数字组合

check if a number combination is found in a list of combinations

我正在 Python 中创建一个程序来模拟乘法闪存卡。我已经走得很远了,但我不知道如何不重复数字组合。如何检查一对数字是否已经出现?

from __future__ import division
from itertools import combinations
import random
amountCorrect = 0
amountMissed = 0
comb = combinations([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 2)

print("Type 0 at any time to exit and see your score.")
while True:
  firstNumber = random.randint(1,12)
  secondNumber = random.randint(1,12)
  ans = int(input("What is " + str(firstNumber) + " x " + str(secondNumber) + ": "))
  if ans == 0:
    break
  elif ans == firstNumber * secondNumber:
    amountCorrect += 1
  else:
    amountMissed += 1

totalProblems = amountCorrect + amountMissed
percentCorrect = amountCorrect/totalProblems

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("Keeping practicing, you will be a master one day.")

简而言之,用一个集合来存储你已经使用过的数字对。这是一些代码。你从不在你的代码中使用 combinations 所以我删除了它。

from __future__ import division
import random
amountCorrect = 0
amountMissed = 0
highestNumber = 12

print("Type 0 at any time to exit and see your score.")
used = set()
while True:
  if len(used) == highestNumber ** 2:
      break
  while True:
    firstNumber = random.randint(1,highestNumber)
    secondNumber = random.randint(1,highestNumber)
    pair = (firstNumber, secondNumber)
    if pair not in used:
      used.add(pair)
      break
  ans = int(input("What is " + str(firstNumber) + " x " + str(secondNumber) + ": "))
  if ans == 0:
    break
  elif ans == firstNumber * secondNumber:
    amountCorrect += 1
  else:
    amountMissed += 1

totalProblems = amountCorrect + amountMissed
percentCorrect = amountCorrect/totalProblems

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("Keeping practicing, you will be a master one day.")

我刚刚创建了一个名为 used 的空集,并添加了一个新的内部循环。该循环测试这对数字是否已被使用。如果是这样,它只是再次循环并尝试一对新的数字。我还添加了一个变量来存储最大可能的数字,并且 used 集合的测试已满。如果测验已满,我将结束测验。否则,当尝试所有可能性时,程序将进入无限循环。

请注意,此代码将允许 1,22,1。如果您只想允许其中一个,请将 (firstNumber, secondNumber)(secondNumber, firstNumber) 添加到 used 集。