簡體   English   中英

如何在不使用numpy的情況下從python中的線方程中提取系數?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM