我正试图用Python构建一个线性方程计算器。在通过询问用户问题来收集信息之后,我开始计算公式。如果用户说他们有两个点,通过这条线,我用这个信息来创建一个等式。方程的不同部分(例如斜率、y截距、操作、x和y)存储在一个列表中。在计算了这个方程之后,我想把这个列表加入到一个字符串中;但是,我得到了一个类型错误。以下是回溯的一部分:
File "/Users/matthewschell/PycharmProjects/Linear Equation Calculator/main.py", line 19, in slope_intercept
final_equation = solve_slopeint(**arg_dict)
File "/Users/matthewschell/PycharmProjects/Linear Equation Calculator/solve_functions.py", line 52, in solve_slopeint
final_equation = ''.join(equation)
TypeError: sequence item 0: expected str instance, int found下面是计算方程的函数的完整代码:
def solve_slopeint(**kwargs):
if kwargs['point1'] is not None and kwargs['point2'] is not None:
equation = [None, '= ']
point1 = kwargs['point1']
point2 = kwargs['point2']
slope = (point2[1] - point1[1]) / (point2[0] - point1[0])
slope = str(slope)
if slope[-2:] == ".0":
slope = str(int(float(slope)))
num = 0 # Variable that lets program know the type of num the slope is. 0 = whole num and 1 = fraction
else:
num = point2[1] - point1[1]
denom = point2[0] - point1[0]
common_divisor = gcd(num, denom)
numerator = num / common_divisor
denominator = denom / common_divisor
slope = [int(numerator), int(denominator)]
num = 1
equation.append(slope)
equation.append(None)
equation.append('+ ')
equation.append(0)
equation[0] = point1[1]
equation[3] = point1[0]
if num == 0:
check = slope * equation[3]
while check + equation[5] != equation[0]:
if check + equation[5] < equation[0]:
equation[5] += 1
elif check + equation[5] > equation[0]:
equation[5] -= 1
else:
check = (slope[0] * equation[3]) / slope[1]
while check + equation[5] != equation[0]:
if check + equation[5] < equation[0]:
equation[5] = equation[0] - (check + equation[5])
elif check + equation[5] > equation[0]:
equation[5] = (check + equation[5]) - equation[0]
for item in equation:
item = str(item)
print(item)
final_equation = ''.join(equation)
return final_equation有人知道我为什么会出现类型错误吗?
发布于 2021-02-26 15:48:56
在这个片段的这一部分:
for item in equation:
item = str(item)
print(item)您只对循环中存在的新项进行str(),而不是将它们保存在等式中。
newequation = []
for item in equation:
newequation.append(str(item))
equation = newequation也许有更干净的方法来解决这个问题,但我不是很好
https://stackoverflow.com/questions/66388765
复制相似问题