ABC学习网

Python根据输入参数计算结果的实例方法

热度:12℃发布时间:2023-12-29 12:07:05

说明

define function,calculate the input parameters and return the result.

数据存放在 txt 里,为 10 行 10 列的矩阵。

编写一个函数,传入参数:文件路径、第一个数据行列索引、第二个数据行列索引和运算符。

返回计算结果

如果没有传入文件路径,随机生成 10*10 的值的范围在 [6, 66] 之间的随机整数数组存入 txt 以供后续读取数据和测试。

1、导入需要的依赖库和日志输出配置

# -*- coding: UTF-8 -*-"""@Author :叶庭云@公众号 :修炼Python@CSDN :https://yetingyun.blog.csdn.net/"""import numpy as npimport logging logging.basicConfig(level=logging.INFO, format=’%(asctime)s - %(levelname)s: %(message)s’)2、生成数据

def generate_fake_data(): """ :params: 无 :return: 无 :function:如果没有传入文件路径 随机生成10*10 值的范围在[6, 66]之间的随机整数数组 存入txt以供后续读取数据和测试 """ # 创建一个 10*10均值为8,标准差为1的正态分布的随机数数组 # data = np.random.normal(8, 1, (10, 10)) # 创建一个 10*10 值的范围在[6, 66]之间的随机整数数组 data = np.random.randint(6, 66, (10, 10)) print(data) with open("./data/random_data.txt", "w") as f: for i in data: for j in i: f.write(str(j) + ’t’) f.write("n")3、加载数据并计算,返回结果。

def load_data_and_calculate(point1, point2, operation, file="./data/random_data.txt"): """ :param file: 文件路径 为缺省参数:在调用函数时可以传 也可以省去的参数,如果不传将使用默认值测试 :param point1: 第一个数据的行列索引 元组类型 :param point2: 第二个数据的行列索引 元组类型 :param operation: 运算符 :return: 运算后的结果 """ if file == "./data/random_data.txt": # 还是默认参数的话 说明没有传入文件路径 generate_fake_data() else: pass data = np.fromfile(file, sep=’t’, dtype=np.float32) # 读取txt数据 numpy的fromfile方法 new_data = data.reshape([10, 10]) # (100,)reshape为(10, 10) 10行10列 print(new_data) # 根据索引获取到二维数组中的两个数据 捕获可能的索引越界异常 num1, num2 = None, None try: num1 = new_data[point1[0]][point1[1]] num2 = new_data[point2[0]][point2[1]] print(f"根据行列索引获取到的两个数为:{num1} {num2}") # 打印查看 except IndexError: logging.info(f"行列索引超出数据集边界,当前数据集形状为:{new_data.shape}") # 进行运算 捕获可能的异常 try: # eval函数 返回传入字符串的表达式的结果 result = eval(f"{num1}{operation}{num2}") print(f"result: {num1} {operation.strip()} {num2} = {result}n") return result except ZeroDivisionError: logging.error(f"除数num2不能为零!") except SyntaxError: if operator in [’x’, ’X’]: logging.error(f"乘法运算时请使用 * 代替 {operation}") else: logging.error(f"输入的运算符非法:({operation})")4、传入参数,调用函数。

file_path = "./data/testData.txt"# 输入第一个数据行列索引x1, y1 = map(int, input("请输入第一个数据行列坐标(如: 6,8):").split(’,’))# 输入第二个数据行列索引x2, y2 = map(int, input("请输入第一个数据行列坐标(如: 3,5):").split(’,’))# 输入运算符号operator = input("请输入运算符(如+、-、*、/、//、%...):") # 传入实参my_result = load_data_and_calculate((x1, y1), (x2, y2), operator, file_path)# 保留两位小数输出print("进行 {} 运算后,结果为:{:.2f}".format(operator, my_result))

到此这篇关于Python根据输入参数计算结果的实例方法的文章就介绍到这了,更多相关Python如何根据输入参数计算结果内容请搜索ABC学习网以前的文章或继续浏览下面的相关文章希望大家以后多多支持ABC学习网!

(window.slotbydup = window.slotbydup || []).push({id: "u6915441",container: "_5rmj5io5v3i",async: true});
网友评论
评论
发 布

更多编程教程
  • 编程教程推荐
更多+