进行了一些研究,并询问Stack上的某个人是否可以帮助我使用多项式转换器来获取多项式并将其转换为列表-例如:3x^2 - 8x + 5
--- [3, -8, 5]
。他们在此方面做得非常出色,但是就发生的事情而言,这让我有些头疼。想知道是否有人愿意给我详细的事件细目,并帮助我重新编写它,以确保当我重新了解它时正在发生什么。 (使用regex btw)这是:
poly = ("4x^2 - 3x + 2")
s=re.sub('[xX^]','',poly)
print([int('-'+i[0]) if s[s.index(i)-2]=='-' else int(i[0]) for i in re.split(' [+|-] ',s)])
我尝试将其放在对我来说有意义的术语上,但是我真的不知道该怎么办,因为它不起作用。
if s[s.index(i) - 2]=="-":
int("-" + i[0])
else:
int(i[0])
for i in re.split:
(" [+|-] ", s)
我在哪里错了?
答案 0 :(得分:2)
尝试一下:
for i in re.split(' [+|-] ',s):
if s[s.index(i) - 2]=="-":
x.append(int("-" + i[0]))
else:
x.append(int(i[0]))
print(x)
输出:
[4, -3, 2]
首先,您需要在代码中了解列表理解的工作原理
[ `firstValue` if `condition` else `secondValue` while iterating over list]
所以, 这个小代码遍历for循环(for循环应在外部),以评估每个元素的条件,并将输出附加到主列表中。
答案 1 :(得分:1)
有趣的问题!
Python过度压缩的另一个经典案例!列表理解可能是一场噩梦,我不希望看到它们被初学者抛弃。我还注意到该方法的一些潜在问题,因此我想提供一种替代方法。对于增值,这还将跟踪每个术语的功效。我已经评论了这种方法。
# This is hopefully self-explanatory.
poly = "4x^2 - 3x^3 - 2x + 2"
# We made this regex more complicated in order to capture an entire
# term of a polynomial. Here's how that works:
# ([+-]|) - The first capture group, contain the sign or (|)
# nothing.
# \s* - Allow whitespace between the sign and the term.
# ([0-9]+) - The second capture group, contain the coefficient.
# ([xX]|) - Match the variable or nothing.
# (\^[0-9]+|) - Match the exponent or nothing. Notice we escape the caret.
matches = re.finditer(r'([+-]|)\s*([0-9]+)([xX]|)(\^[0-9]+|)', poly)
# Now we parse the results of the regex...
terms = list() # Create a list to store our processed terms.
for match in matches: # Iterate our matches.
# Step 1: Parse the groups' contents.
negative = match.group(1) == '-' # Check if the sign is negative.
coef = int(match.group(2)) # Retrieve the coefficient as an integer.
has_variable = bool(match.group(3)) # Check whether there's a variable.
exponent_str = match.group(4) # Get the exponent group.
if exponent_str:
# There's an exponent, remove the caret and turn it into an
# integer.
exponent = int(exponent_str[1:])
else:
# There's no exponent, if there's a variable the power of this term
# is 1, otherwise it's 0.
exponent = 1 if has_variable else 0
# Step 2: Create a (coefficient, power) tuple and add it to the list of
# terms.
if negative:
# Make the coefficient negative if the sign was a -.
coef *= -1
# Add a tuple containing the coefficient and exponent to our list of
# terms.
terms.append((coef, exponent))
# Optional: sort the terms in order of power (descending).
terms.sort(key=lambda tpl: -tpl[1])
# Print the output.
print(terms)
这将输出
[(-3, 3), (4, 2), (-2, 1), (2, 0)]