四則運算 (升級版)
阿新 • • 發佈:2019-03-28
img 整理 生成 space mas int() analysis 源代碼 設計文檔
代碼地址:https://github.com/kriswang10/kriswang10.github.io/blob/master/calculate.py
首先拿到題目的思路比較亂,整理了一下分成兩大塊,一塊用於隨機生成一道隨機計算題,另一塊則由用戶自己要求題目數量,由系統隨機生成。
由於是給小學生的題目,將生成函數分為兩類,一類為生成整數型的四則運算為newint()函數,另一類則是分數型的為newfra()函數。其中整數型的數字範圍在0-20,分數型則在
0-10取分數,而且所有運算都先通過比較大小來避免產生負數。
主函數則先由用戶選擇進行哪塊來達成需求,為降低難度,產生的隨機題目會盡量出現更多的整數型計算,也由隨機數來決定,用戶可以在輸入0000後退出程序。
以下為源代碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
import time
def newint():
sym = [ ‘+‘ , ‘-‘ , ‘ב , ‘÷‘ ]
fh = random.randint( 0 , 3 )
n1 = random.randint( 1 , 20 )
n2 = random.randint( 1 , 20 )
result = 0
if fh = = 0 :
result = n1 + n2
elif fh = = 1 :
n1,n2 = max (n1,n2), min (n1,n2)
result = n1 - n2
elif fh = = 2 :
result = n1 * n2
elif fh = = 3 :
n1,n2 = max (n1,n2), min (n1,n2)
while n1 % n2 ! = 0 :
n1 = random.randint( 1 , 10 )
n2 = random.randint( 1 , 10 )
n1,n2 = max (n1,n2), min (n1,n2)
result = int (n1 / n2)
print (n1,sym[fh],n2, ‘=‘ ,end = ‘ ‘ )
return result
def newfra():
sym = [ ‘+‘ , ‘-‘ , ‘ב , ‘÷‘ ]
fh = random.randint( 0 , 3 )
t1 = random.randint( 1 , 10 )
t2 = random.randint(t1, 10 )
n1 = Fraction(t1,t2)
t1 = random.randint( 1 , 10 )
t2 = random.randint(t1, 10 )
n2 = Fraction(t1,t2)
result = 0
if fh = = 0 :
result = n1 + n2
elif fh = = 1 :
n1,n2 = max (n1,n2), min (n1,n2)
result = n1 - n2
elif fh = = 2 :
result = n1 * n2
elif fh = = 3 :
n1,n2 = max (n1,n2), min (n1,n2)
result = n1 / n2
print (n1,sym[fh],n2, ‘=‘ ,end = ‘ ‘ )
return result
def newtest():
sym = [ ‘+‘ , ‘-‘ , ‘ב , ‘÷‘ ]
n = int ( input ())
result = []
m = 0
while m< = (n - 1 ):
fh = random.randint( 0 , 4 )
if fh = = 0 :
print (m + 1 ,end = ‘、‘ )
result.append(newfra())
print ( ‘ ‘ )
else :
print (m + 1 ,end = ‘、‘ )
result.append(newint())
print ( ‘ ‘ )
m = m + 1
m = 0
print ( ‘答案:‘ )
while m < = (n - 1 ):
print (m + 1 , ‘、‘ ,result[m])
m = m + 1
def main():
print ( ‘1、四則運算‘ )
print ( ‘2、制作題庫‘ )
n = int ( input ())
if n = = 1 :
print ( ‘input"0000"to Quit‘ )
while True :
fh = random.randint( 0 , 4 )
if fh = = 0 :
result = newfra()
jg = input ()
if jg = = ‘0000‘ :
break ;
ans = Fraction(jg)
if ans = = result:
print ( ‘right‘ )
else :
print ( ‘error,the right answer is‘ ,result)
else :
result = newint()
jg = input ()
if jg = = ‘0000‘ :
break ;
ans = Fraction(jg)
if ans = = result:
print ( ‘right‘ )
else :
print ( ‘error,the right answer is‘ ,result)
if n = = 2 :
print ( ‘需要制作多少道題目:‘ )
newtest()
if __name__ = = ‘__main__‘ :
main()
|
程序測試:
以上為程序的簡單測試,未出現明顯BUG或錯誤,以下為我用python自帶的cProfile函數做的效能分析
當程序作出10000道題目時也迅速給出了結果,程序中的算法可能還有待提升,但基本滿足要求且迅速。
PSP:
|
|
四則運算 (升級版)