I have been running in circles on some basic stuff. My idea is the following: I want to write a simple def , to do partial derivatives. I know there are tools out there already, but I happen to be an egotist with presumably bad antiquated python skills. without further ado, here is the situation. First the strategy: I want to split something like 2x + 3y into [2x , 3y]; then act on 2x , thus [0] and 3y, [1] with a derivative operation which I have not written yet. I plan on doing this symbolically. I have decided not to look into too much detail on how others have done it without trying a few dirty attempts. Here is my non working implentation
我一直在一些基本的东西上兜圈子。我的想法是这样的:我想写一个简单的def,来做偏导数。我知道已经有了一些工具,但我碰巧是一个自负的人,可能有一些过时的python技巧。事不宜迟,情况是这样的。首先,我想把2x + 3y分成[2x, 3y];然后对2x,[0]和3y,[1]进行导数运算我还没写出来。我打算象征性地做这件事。我已经决定,在不做一些卑鄙的尝试的情况下,不要去研究别人是如何做到这一点的细节。这是我的非工作恳求
def partialderivative(f, a):
import re
L = list(f)
re.split('[+ -]', L)
derivative (L[0],x)
derivative (L[0],y)
derivative (L[1],x)
derivative (L[1],y)
print(some results)
打印(结果)
Now there are many things going on that I don't fully understand. If I run the first part above via command line carefully ensuring that f --> 'f' and proceeding as re.split('[+ -]',f) , then I will have it split, but that is about it The part below the " ------------------ " is more or less pseudo code.
现在有很多事情我还不完全明白。如果我通过命令行仔细地运行上面的第一部分,确保f——> 'f',并以re.split('[+ -]',f)的形式继续运行,那么我将把它拆分,但这就是下面“———————————”的部分几乎是伪代码。
This is probably going to be the dumbest question posted here. . .
这可能是最愚蠢的问题了…
1 个解决方案
#1
1
re.split()
just accept string type so you couldn't pass a list to it . also in your pattern you have a space that is extra you need r'[+-]'
:
split()只接受字符串类型,因此不能将列表传递给它。同样在你的模式中你有一个额外的空间你需要r'[+-]
>>> s="2x + 3y"
>>> s1="2x + 3y"
>>> s2="2x - 3y"
>>> re.split(r'[+-]',s1)
['2x ', ' 3y']
>>> re.split(r'[+-]',s2)
['2x ', ' 3y']
also you can remove spaces from your splited elements with str.strip
:
你也可以用str.strip从你分割的元素中移除空间:
>>> [i.strip() for i in re.split(r'[+-]',s2)]
['2x', '3y']
And within a function :
在一个函数内:
>>> def spliter(s):
... return [i.strip() for i in re.split(r'[+-]',s)]
...
>>> spliter(s1)
['2x', '3y']
>>> s3="4x + 12z - 18k"
>>> spliter(s3)
['4x', '12z', '18k']
#1
1
re.split()
just accept string type so you couldn't pass a list to it . also in your pattern you have a space that is extra you need r'[+-]'
:
split()只接受字符串类型,因此不能将列表传递给它。同样在你的模式中你有一个额外的空间你需要r'[+-]
>>> s="2x + 3y"
>>> s1="2x + 3y"
>>> s2="2x - 3y"
>>> re.split(r'[+-]',s1)
['2x ', ' 3y']
>>> re.split(r'[+-]',s2)
['2x ', ' 3y']
also you can remove spaces from your splited elements with str.strip
:
你也可以用str.strip从你分割的元素中移除空间:
>>> [i.strip() for i in re.split(r'[+-]',s2)]
['2x', '3y']
And within a function :
在一个函数内:
>>> def spliter(s):
... return [i.strip() for i in re.split(r'[+-]',s)]
...
>>> spliter(s1)
['2x', '3y']
>>> s3="4x + 12z - 18k"
>>> spliter(s3)
['4x', '12z', '18k']