然后统计和归类
归类分行
归类方法
算术符号归类
数字大小排序
算术符号归类
import random
def generate_expression(num_range, num_count, operators):
nums = random.sample(range(num_range[0], num_range[1]+1), num_count)
ops = random.choices(operators, k=num_count-1)
expression = str(nums[0])
for i in range(1, num_count):
expression += ' ' + ops[i-1] + ' ' + str(nums[i])
try:
result = eval(expression)
if int(result) == result: # 判断结果是否为整数
return {
'expression': expression,
'result': int(result),
'operator': ops,
'numbers': nums
}
except ZeroDivisionError:
return None
num_range = (1, 20)
num_count = 2
operators = ['+', '-', '*', '/']
expressions = []
for i in range(10):
expression = generate_expression(num_range, num_count, operators)
if expression:
expressions.append(expression)
# 按照算术符号进行归类
classified_expressions = {}
for expression in expressions:
operator = ''.join(expression['operator'])
if operator not in classified_expressions:
classified_expressions[operator] = []
classified_expressions[operator].append(expression)
# 输出归类结果
print("按照算术符号进行归类:")
for operator, exp_list in classified_expressions.items():
print(f"算术符号: {operator}")
for exp in exp_list:
print(f"表达式: {exp['expression']}")
print(f"结果: {exp['result']}")
print()
# 按照数字大小进行排序
sorted_expressions = sorted(expressions, key=lambda x: max(x['numbers']), reverse=True)
# 输出排序结果
print("按照数字大小排序:")
for exp in sorted_expressions:
print(f"表达式: {exp['expression']}")
print(f"结果: {exp['result']}")
print()
python/自由计算3.2.2.1.py" && exit < 按照算术符号进行归类:
算术符号: +
表达式: 2 + 1
结果: 3
表达式: 20 + 19
结果: 39
表达式: 1 + 10
结果: 11
表达式: 16 + 5
结果: 21
算术符号: -
表达式: 2 - 5
结果: -3
表达式: 4 - 17
结果: -13
算术符号: *
表达式: 4 * 9
结果: 36
表达式: 14 * 15
结果: 210
表达式: 12 * 1
结果: 12
按照数字大小排序:
表达式: 20 + 19
结果: 39
表达式: 4 - 17
结果: -13
表达式: 16 + 5
结果: 21
表达式: 14 * 15
结果: 210
表达式: 12 * 1
结果: 12
表达式: 1 + 10
结果: 11
表达式: 4 * 9
结果: 36
表达式: 2 - 5
结果: -3
表达式: 2 + 1
结果: 3
#[QPython] Press enter to exit ...