网络编程
位置:首页>> 网络编程>> Python编程>> Python之根据输入参数计算结果案例讲解

Python之根据输入参数计算结果案例讲解

作者:叶庭云  发布时间:2022-08-27 07:44:50 

标签:Python,封装

Python之根据输入参数计算结果案例讲解

一、问题描述

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

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

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

  • 返回计算结果

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

二、Python程序

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


# -*- coding: UTF-8 -*-
"""
@Author  :叶庭云
@公众号  :修炼Python
@CSDN    :https://yetingyun.blog.csdn.net/
"""
import numpy as np
import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s: %(message)s')

生成数据


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")

加载数据并计算,返回结果。


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})")

传入参数,调用函数。


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之根据输入参数计算结果案例讲解

来源:https://blog.csdn.net/fyfugoyfa/article/details/119106936

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com