100以内数学题自动出题
家有小朋友,天天放学就去外面玩,简单的加减法已经阻止不了他的脚步了,所以自己写了个程序自动出题,并且获得答案
[Python] 纯文本查看 复制代码 import random
mathlist = []
keylist = []
while len(mathlist) < 99:
flag = ['+', '-']
flag1 = []
for i in range(random.randint(1, 4)):
flag1.append(random.choice(flag))
nums = []
for i in range(len(flag1) + 1):
num = random.randint(1, 100)
nums.append(num)
new = []
for i, f in enumerate(flag1):
new.append(str(nums[random.randint(0, (len(nums) - 1))]))
new.append(f)
new.append(str(nums[random.randint(0, (len(nums) - 1))]))
# print(new)
sum1 = int(new[0])
for i in range(1, len(flag1) + 1):
if new[2 * i - 1] == '-':
sum1 = sum1 - int(new[2 * i])
else:
sum1 = sum1 + int(new[2 * i])
if sum1 > 0 and sum1 < 100:
str1 = (''.join(new) + '=').ljust(35)
str2 = (''.join(new) + '=' + str(sum1)).ljust(35)
mathlist.append(str1)
keylist.append(str2)
str5 = ''
str6 = ''
for i, v1 in enumerate(mathlist):
if (i + 1) % 3 == 0:
str5 = str5 + v1 + '\n'
else:
str5 = str5 + v1 + '\t'
for i, v in enumerate(keylist):
if (i + 1) % 3 == 0:
str6 = str6 + v + '\n'
else:
str6 = str6 + v + '\t'
with open('math1.txt', 'w', encoding='utf-8') as f:
f.write(str5)
with open('key1.txt', 'w', encoding='utf-8') as f:
f.write(str6)
结果是这样的
|