python实现四则运算题库
#主函数(main.py)
from generator import Ari_Expression
from infixTosuffix import infix_to_suffix
import Calculate
def main():
max_num = int(input('请输入操作数的最大值:'))
problem = int(input('请输入需要的题目数量:'))
i = 1
correct = []
wrong = []
p = open('Exercises.txt', 'w')
r = open('Answer.txt', 'w')
while i < problem + 1:
ari = Ari_Expression(max_num)
inf = infix_to_suffix()
real_res = Calculate.getResult(inf.str_to_fraction(inf.to_suffix_expression(ari.str)))
if real_res >= 0:
real_res = ari.str_num(real_res)
print(str(i)+'. ' + ari.str, end = '')
p.write(str(i)+'. ' + ari.str + '\n')
r.write(str(i)+'. ' + real_res + '\n')
res = input()
if res == real_res:
correct.append(i)
else:
wrong.append(i)
i += 1
p.close()
r.close()
print('题目正确率:' + str(len(correct)/problem))
g = open('Grade.txt','w')
g.write('Correct:' + str(len(correct))+'(')
for x in correct:
g.write(str(x)+', ')
g.write(')\n')
g.write('Wrong:' + str(len(wrong))+'(')
for x in wrong:
g.write(str(x)+', ')
g.write(')\n')
if __name__ == '__main__':
main()
#模块一(Calculate.py)
from fractions import Fraction
import Stack
def getResult(expression):
stackValue = []
for item in expression:
if item in ["+", "-", "×", "÷"]:
n2 = stackValue.pop()
n1 = stackValue.pop()
result = cal(n1, n2, item)
if result < 0:
return -1
stackValue.append(result)
else:
stackValue.append(item)
return stackValue[0]
def cal(n1, n2, op):
if op == "+":
return n1 + n2
if op == "-":
return n1 - n2
if op == "×":
return n1 * n2
if op == "÷":
return n1 / n2
#模块二(generator.py)
from fractions import Fraction
import random
class Ari_Expression():
'''算术表达式的生成'''
def __init__(self, max_num):
self.init_operators()
self.init_nums(max_num)
self.init_expression()
def init_num(self, max_num):
'''随机生成数'''
denominator = random.randint(1, max_num)
numerator = random.randint(0, max_num)
return Fraction(numerator, denominator)
def insert_bracket(self):
'''插入括号'''
bracket = ['(', 'null', ')']
if len(self.operators) > 1:
x = random.randint(0, len(self.operators))
while x < len(self.operators):
y = random.randint(x, len(self.operators))
low = False
for a in self.operators[x:y + 1]:
if a in ['+', '-']:
low = True
break
try:
if self.operators[y + 1] in ['×', '÷'] and low:
self.operators.insert(x, '(')
self.operators.insert(y + 2, ')')
except IndexError:
pass
x = y + 2
def init_operators(self):
'''随机生成一个运算符并随机插入括号'''
self.operators = []
operator = ['+', '-', '×', '÷', 'null']
for x in range(3):
if x == 1:
self.operators.append(random.choice(operator[:-2]))
else:
y = random.choice(operator)
if y != 'null':
self.operators.append(y)
self.insert_bracket()
def init_nums(self, max_num):
self.nums = []
self.nums.append(self.init_num(max_num))
for x in range(len(self.operators)):
y = self.init_num(max_num)
if self.operators[x] == '÷':
while y.numerator == 0:
y = self.init_num(max_num)
self.nums.append(y)
def str_num(self, num):
'''字符串化一个分数'''
inter = int(num.numerator / num.denominator)
numerator = int(num.numerator % num.denominator)
str_num = ''
if numerator != 0:
str_num += str(numerator) + '/' + str(num.denominator)
if not str_num:
'''如果为空'''
str_num += str(inter)
else:
if inter == 0:
return str_num
else:
str_num = str(inter) + '`' + str_num
return str_num
def init_expression(self):
'''生成一个算术表达式的字符串形式'''
self.str = ''
i = 0
self.exp = []
again = False
for x in self.operators:
if again:
self.str += x + ' '
elif x == '(':
self.str += x + ' '
elif x == ')':
self.str += self.str_num(self.nums[i]) + ' '
i += 1
self.str += x + ' '
again = True
else:
self.str += self.str_num(self.nums[i]) + ' '
self.str += x + ' '
i += 1
self.str += self.str_num(self.nums[-1]) + ' ='
#模块三(infixTosuffix.py)
import Stack
from fractions import Fraction
class infix_to_suffix:
def __init__(self):
self.list_operators = ["+", "-", "×", "÷", "(", ")", "="]
self.pri_operators = {"+": 0, "-": 0, "×": 1, "÷": 1}
def to_suffix_expression(self, expression):
'''生成逆波兰表达式'''
stack_operator = Stack.Stack()
suffix_expression = []
list_temp = []
expression = expression + "="
for element in expression:
if element not in self.list_operators:
list_temp.append(element)
elif element == "=":
if len(list_temp) != 0:
str_temp = ""
for i in range(0, len(list_temp)):
str_temp = str_temp+list_temp.pop(0)
suffix_expression.append(str_temp)
else:
if len(list_temp) != 0:
str_temp = ""
for i in range(0, len(list_temp)):
str_temp = str_temp+list_temp.pop(0)
suffix_expression.append(str_temp)
if stack_operator.isEmpty() or element == "(":
stack_operator.push(element)
elif element != "(" and element != ")":
if stack_operator.peek() != "(" and self.pri_operators[element] > self.pri_operators[
stack_operator.peek()]:
stack_operator.push(element)
else:
while True:
if stack_operator.peek() == "(":
stack_operator.push(element)
break
elif self.pri_operators[element] < self.pri_operators[stack_operator.peek()]:
while not stack_operator.isEmpty() and True:
str_operator = stack_operator.peek()
if str_operator == "(" or self.pri_operators[str_operator] < self.pri_operators[
element]:
break
else:
stack_operator.pop()
suffix_expression.append(str_operator)
else:
suffix_expression.append(stack_operator.pop())
if stack_operator.isEmpty():
stack_operator.push(element)
break
elif element == ")":
while True:
if stack_operator.peek() != "(":
suffix_expression.append(stack_operator.pop())
else:
stack_operator.pop()
break
else:
stack_operator.push(element)
if not stack_operator.isEmpty():
while not stack_operator.isEmpty():
suffix_expression.append(stack_operator.pop())
return suffix_expression
def str_to_fraction(self, suf):
'''字符串转换为fraction类'''
for x in range(len(suf)):
if suf[x] not in self.list_operators:
y = suf[x].strip()
if y.find('`') == -1:
if y.find('/') == -1:
numerator = int(y)
denominator = 1
else:
a = y.split('/')
numerator = int(a[0])
denominator = int(a[1])
else:
a = y.split('`')
inter = int(a[0])
b = a[1].split('/')
denominator = int(b[1])
numerator = int(b[0]) + inter * denominator
new_num = Fraction(numerator,denominator)
suf[x] = new_num
return suf
#模块四(Stack.py)
class Stack:
"""模拟栈"""
def __init__(self):
self.items = []
def isEmpty(self):
return len(self.items) == 0
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
if not self.isEmpty():
return self.items[len(self.items) - 1]
def size(self):
return len(self.items)
代码搬运自python结对编程实现小学生四则运算生成器_aokui4738的博客-CSDN博客
python实现四则运算题库的更多相关文章
- 小学生噩梦——四则运算题库(python 全功能实现)
Github: https://github.com/holidaysss 小组:龙天尧(代码实现),林毓植(浮点转分数函数,代码审查) PSP2.1 Personal Software Proces ...
- Python基础语法题库
引言: 语法练习包括Python基础语法.数据类型.字符编码和简单文件操作等内容. 正文(参考答案附录在题目下方): 1.Python 里用来告知解释器跳过当前循环中的剩余语句,然后继续进行下一轮循环 ...
- 『Python题库 - 填空题』151道Python笔试填空题
『Python题库 - 填空题』Python笔试填空题 part 1. Python语言概述和Python开发环境配置 part 2. Python语言基本语法元素(变量,基本数据类型, 基础运算) ...
- 『Python题库 - 简答题』 Python中的基本概念 (121道)
## 『Python题库 - 简答题』 Python中的基本概念 1. Python和Java.PHP.C.C#.C++等其他语言的对比? 2. 简述解释型和编译型编程语言? 3. 代码中要修改不可变 ...
- Python解答力扣网站题库简单版----第三讲
1041. 困于环中的机器人 题库链接: 1041. 困于环中的机器人. 题干 在无限的平面上,机器人最初位于 (0, 0) 处,面朝北方.机器人可以接受下列三条指令之一: "G" ...
- Python面试真题答案或案例
Python面试真题答案或案例如下: 请等待. #coding=utf-8 #1.一行代码实现1--100之和 print(sum(range(1,101))) #2.如何在一个函数内部修改全局变量 ...
- 猿题库 iOS 客户端架构设计
原文: http://mp.weixin.qq.com/s?__biz=MjM5NTIyNTUyMQ==&mid=444322139&idx=1&sn=c7bef4d439f4 ...
- NOI题库刷题日志 (贪心篇题解)
这段时间在NOI题库上刷了刷题,来写点心得和题解 一.寻找平面上的极大点 2704:寻找平面上的极大点 总时间限制: 1000ms 内存限制: 65536kB 描述 在一个平面上,如果有两个点( ...
- NOI题库 1768最大子矩阵 题解
NOI题库 1768最大子矩阵 题解 总时间限制: 1000ms 内存限制: 65536kB 描述 已知矩阵的大小定义为矩阵中所有元素的和.给定一个矩阵,你的任务是找到最大的非空(大 ...
随机推荐
- 新一代Python包管理工具来了
1 简介 说起Python的包管理工具,大家第一时间想到的肯定是pip.conda等经典工具.但最近我发现了一款新颖的Python包管理工具--pdm,它受到PEP582(https://www.py ...
- ARC-124 部分题解
E 直接统计原式不好做,注意到首先我们应该知道怎样的 \(x\) 序列是合法的,那么不妨首先来统计一下合法的 \(x\) 序列数量. 令 \(b_i\) 为 \(i\) 向右给的球数,那么有(\(i ...
- linux .h文件
转载请注明来源:https://www.cnblogs.com/hookjc/ c++ #include <sys/types.h> #include <unistd.h> ...
- ARC基本概念
1.什么是ARC Automatic Reference Counting,自动引用计数,即ARC,可以说是WWDC2011和iOS5所引入 的最大的变革和最激动人心的变化.ARC是新的LLVM 3. ...
- FileOutStream
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import ja ...
- linux_17
nginx负载均衡中常见的算法及原理有哪些? 用rewrite规则实现将所有到a域名的访问rewrite到b域名 实现反向代理客户端IP透传 利用LNMP实现wordpress站点搭建
- linxu 查看运行日志
journalctl - 检索 systemd 日志 journalctl 可用于检索 systemd(1) 日志(由 systemd-journald.service(8) 记录). 如果不带任何参 ...
- 如何通过pid定位是哪个容器
此时,我有一个pid为28117的进程,通过pdwx命令,无法找到他所在的目录,此时我判定他是docker容器 pwdx 28117 输出如下 28117: / 通过docker ps -q命令,获取 ...
- ios开发 Rsa签名 base64转码
因为公司要求做了一个加密 网上的资料少有可用的 于是我看到了一位大神的曙光 但是未介绍使用方法 然后另一位大神给予了使用方法 但是没有把库给出来 我整理了一下 希望大家看的有些启发 证书生成 ...
- python处理图像矩阵--值转为int
1. 在用python处理图像数字矩阵时,若对矩阵进行了加减乘除等运算,可能会造成矩阵元素值溢出,然后某些元素值可能都被赋为255:之后若重新显示图像,可能会没有什么变化,此时,可以将运算后的矩阵值转 ...