简体   繁体   中英

How to extract coefficients from a line equation in python without using numpy?

I have 2 lists RED and BLUE in the form of (x,y) tuples and a list of line equations in the form of ax+by+c. My requirement is to extract the coefficients from each line equation and determine based on the plots for the 2 set of points whether the points are clearly separated on both sides of the line. Challenge is that I cannot use numpy.

My approach has been to zip the 2 lists RED and BLUE points using pyplot. Now I am trying to extract the coefficients using regular expression as below.

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)

However, Im not able to use 'z' as it is of 'NoneType'. Even if I am able to use it somehow, I am not sure how to use the intercept and slope to determine that the RED and BLUE points are on either side of the line.

Any pointers are hugely appreciated.

Tried plotting the points using 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))

I believe what you want to use is findall .

You can start with a simple pattern of [\\d\\.\\-\\+]+ . This will catch all coefficients assuming the coefficients are properly formatted (eg no double periods in digits).

>>> 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']

Obviously, you'll have to do some additional parsing of the resulting list of strings to convert them to numbers, but that will be an exercise for you :)

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)

output: ['112', '-12', '+0']

This solution will take care of the order in which the equation's terms x,y,c are placed.

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

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM