我正在用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.")
答案 0 :(得分:0)
简而言之,使用一组存储已使用的数字对。这是一些代码。您永远不会在代码中使用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,2
和2,1
。如果只允许其中之一,请将(firstNumber, secondNumber)
和(secondNumber, firstNumber)
都添加到used
集中。