[英]How to extract coefficients from a line equation in python without using numpy?
我有 2 个 (x,y) 元组形式的 RED 和 BLUE 列表和 ax+by+c 形式的线方程列表。 我的要求是从每个线方程中提取系数,并根据 2 组点的图来确定这些点是否在线的两侧明显分开。 挑战是我不能使用 numpy。
我的方法是使用 pyplot 压缩 2 个列表 RED 和 BLUE 点。 现在我正在尝试使用正则表达式提取系数,如下所示。
lines = ["1x+1y+0","1x-1y+0","1x+0y-3","0x+1y-0.5"]
for i in lines:
z = re.match('(\d+)?(x)?\+(\d+)?(y)?\+(\d)?', i)
但是,我无法使用“z”,因为它属于“NoneType”。 即使我能够以某种方式使用它,我也不确定如何使用截距和斜率来确定红点和蓝点位于线的两侧。
任何指针都非常感谢。
尝试使用 matplotlib 绘制点
Red_x = [(x,y) for x,y in Red]
Blue_x = [(x,y) for x,y in Blue]
plt.plot(*zip(*Red_x),'or')
plt.scatter(*zip(*Blue_x))
我相信您要使用的是findall 。
您可以从[\\d\\.\\-\\+]+
的简单模式开始。 假设系数格式正确(例如数字中没有双句点),这将捕获所有系数。
>>> lines = ["1x+1y+0", "1x-1y+0", "1x+0y-3", "0x+1y-0.5"]
>>> for i in lines:
... z = re.findall(r'[\d\.\-\+]+', i)
... print(z)
...
['1', '+1', '+0']
['1', '-1', '+0']
['1', '+0', '-3']
['0', '+1', '-0.5']
显然,您必须对结果字符串列表进行一些额外的解析才能将它们转换为数字,但这对您来说将是一个练习:)
import re
s = "1x-2.1y-0.5"
s = [float(i) for i in re.split('[xy]', s)]
print(s)
[ 1.0 , -2.1 , -0.5 ]
import re
str = "112x-12y+0"
res = re.findall(r'[0-9\-\+]+', str)
print(res)
输出: ['112','-12','+0']
此解决方案将处理方程项 x,y,c 的放置顺序。
import re
all_equations = ["1x+1y+2", "-1x+12Y-6", "2-5y-3x", "7y-50+2X", "3.14x-1.5y+9", "11.0x-1.5y+9.8"]
def CoefficientIntercept(equation):
coef_x = re.findall('-?[0-9.]*[Xx]', equation)[0][:-1]
coef_y = re.findall('-?[0-9.]*[Yy]', equation)[0][:-1]
intercept = re.sub("[+-]?\d+[XxYy]|[+-]?\d+\.\d+[XxYy]","", equation)
return float(coef_x), float(coef_y), float(intercept)
for equation in all_equations:
print(CoefficientIntercept(equation))
输出:
(1.0, 1.0, 2.0)
(-1.0, 12.0, -6.0)
(-3.0, -5.0, 2.0)
(2.0, 7.0, -50.0)
(3.14, -1.5, 9.0)
(11.0, -1.5, 9.8)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.