【问题标题】:how can I change the function or avoid the error如何更改功能或避免错误
【发布时间】:2021-07-09 19:40:29
【问题描述】:

我不知道是我写错了“line”函数还是“for”后面的最后语句中的其他内容,请帮助我。该程序是关于斜率并在这些值之间进行比较,但首先我需要找到它们,但有些东西不起作用。代码如下:

import math

N = int(input("Number of points: "))

def line(x0,y0,x1,y1):
  if(x0==x1):
    print("\nThe slope doesn't exist\n")
    return None
  if((x0-x1)!=0):
    m = (y1-y0)/(x1-x0)
    return m

for i in range(N):
  for j in range(N):
    ind = None
    for ind in range(N):
      x_ind = {}
      y_ind = {}
      x_ind[i] = float(input("Enter x_" + str(ind) + ": "))
      y_ind[j] = float(input("Enter y_" + str(ind) + ": "))
    for _ in range(math.factorial(N-1)):
      line(x_ind[i], y_ind[j], x_ind[i+1], y_ind[j+1])
      

【问题讨论】:

  • 什么不起作用?
  • 请通过一些示例测试提供您的错误
  • 啊,我可以看到您经常会点击KeyError,因为您迭代了列表的末尾(实际上是一本字典)。这段代码甚至试图做什么?为什么它不对line的返回值做任何事情,为什么它要求N^3个值然后迭代它们中的阶乘(N-1)?
  • 感谢回答,好吧我不知道为什么line函数不起作用,阶乘(N-1)是我处理的问题
  • 请接受左侧带有绿色复选标记的答案...如果它是您正在寻找的。​​span>

标签: python function count keyerror


【解决方案1】:

TL;DR - 您在 for 循环中声明您的字典,因此每次新迭代都会重置它们。


我认为你正在尝试这样做 -

N = int(input("Number of points: "))

def line(x0,y0,x1,y1):
  # calculate slope for (x0,y0) and (x1,y1)
  if x0 == x1:            # it will be a vertical line, it has 'undefined' slope
    # print("The slope doesn't exist\n")
    return None           # Slope Undefined
  else:                   # this is implied, no need to put extra check --> x0-x1 != 0:
    return (y1-y0)/(x1-x0)
  pass

# declare variables
x_ind = {}
y_ind = {}
for i in range(N):
  # read inputs and update the existing variables
  x_ind[i] = float(input("Enter x_" + str(i) + ": "))
  y_ind[i] = float(input("Enter y_" + str(i) + ": "))
  print(x_ind, '\n', y_ind)

# calculate slope for every pair of points
for j in range(N):
  for k in range(j+1,N):
    m = line(x_ind[j], y_ind[j], x_ind[k], y_ind[k])
    print(f'slope of line made using points: ({x_ind[j]}, {y_ind[j]}) and ({x_ind[k]}, {y_ind[k]}) is {m}')

示例输入:

Number of points: 3

Enter x_0: 3
Enter y_0: 0

Enter x_1: 0
Enter y_1: 4

Enter x_2: 0
Enter y_2: 0

样本输出:

slope of line made using points: (3.0, 0.0) and (0.0, 4.0) is -1.3333333333333333
slope of line made using points: (3.0, 0.0) and (0.0, 0.0) is -0.0
slope of line made using points: (0.0, 4.0) and (0.0, 0.0) is None

【讨论】:

  • 非常感谢,我明白我的问题所在了。
  • 您可以考虑返回Nonemath.nan,而不是返回字符串'Undefined'。
【解决方案2】:

尝试使用列表而不是字典以正确使用索引值:

x_ind = []
y_ind = []

由于列表为空,您可以使用append() 方法将元素推送到列表中,我可以看到这是您打算做的。

【讨论】:

  • 使用列表不会有任何好处。问题是它们已在循环内声明。
  • 好的,我更改了索引值并使用了 append() 方法,但现在问题是下一个: SyntaxError: can't assign to function call I change like this: x_ind = [] then I写了 x_ind.append(i) = "同一件事" 谢谢
猜你喜欢
  • 1970-01-01
  • 2015-06-26
  • 2021-05-22
  • 1970-01-01
  • 2015-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-11
相关资源
最近更新 更多