首页 > 解决方案 > 如何求斜率:输出格式 ((A,slope), B)

问题描述

我参加了数据科学课程,我正在尝试解决一些编程问题,我已经很长时间没有使用 Python,但我正在努力提高我对这门语言的了解。

这是我的问题:

问题图片

def find_slope(x1, y1, x2, y2): 
  if (x1) == (x2):
    return "inf"
  else:
    return ((float)(y2-y1)/(x2-x1))

这是我的驱动程序代码:

x1 = 1
y1 = 2
x2 = -7
y2 = -2
print(find_slope(x1, y1, x2, y2))

这是我的输出:

0.5

我不确定如何以正确的格式获取它,例如(((1, 2), .5), (3, 4))

注意:我为驱动程序编写了代码。

标签: python-3.xpysparkdata-science

解决方案


你可以这样做:

def find_slope(input):
  x1 = input[0][0]
  y1 = input[0][1]
  x2 = input[1][0]
  y2 = input[1][1]
  if (x1) == (x2):
    slope = "inf"
  else:
    slope = ((float)(y2-y1)/(x2-x1))
  output = (((x1, y1), slope), (x2, y2))
  return output

我更改了输入以匹配屏幕截图中给出的输入格式。
现在输入是一个元组,包含两个元组。每个内部元组都包含 ax 坐标和 ay 坐标。

您可以使用调用该函数

input = ((1, 2), (-7, -2))
output = find_slope(input)

输出格式为((A, slope), B),其中 A 和 B 是包含 x 和 y 坐标的元组。


推荐阅读