优化了int和strs之间的求和


print("ax^2 + bx + c = d what is your values for them? ")
a = int(input(">a = "))
b = int(input(">b = "))
c = int(input(">c = "))
d = int(input(">d = "))
given_parabola = str(a) + "x^2 + " + str(b) + "x + " + (str(c)) + " = " + str(d)

有没有其他方法可以将整数变量与字符串合并?

;最好的";方法真的取决于你们想做什么。

1.连接具有可变项目数(数字和字符串(的列表

如果你只是想从数字和字符串中形成一个字符串,我会首先用generator表达式创建一个生成器,然后用join()方法连接字符串。

In [1]: a = [2, 'a', 3, 'x', 'foo', 8, 55]
In [2]: g = (str(x) for x in a)
In [3]: ' '.join(g)
Out[3]: '2 a 3 x foo 8 55'

脉冲

  • 可以用于连接任意数量的字符串和数字,这些字符串和数字可以按任何顺序排列

地雷

  • 如果您了解更多关于要连接的变量的,可能不是速度优化最多的

2.文本字符串插值

如果您知道要将多少数字变量与哪些字符串连接,则该问题称为字符串插值

在Python3.6+中,您可以使用所谓的f-string来使用字符串模板和固定数量的变量形成字符串。例如:

In [1]: a, b, c, d = 3, 2, 1, 5
In [2]: f"{a}x^2 + {b}x + {c} = {d}"
Out[2]: '3x^2 + 2x + 1 = 5'

脉冲

  • 可能是从模板创建字符串的最快速优化的方法

地雷

  • 这不是";sum"/连接任意数量的字符串和数字

3.使用sympy生成表达式

由于您的问题看起来非常具体:您想从数学公式中创建字符串,您可能需要查看sympy。

安装

pip install sympy

简单示例

In [1]: from sympy import symbols, Eq, mathematica_code
In [2]: x, a, b, c, d = symbols('x a b c d')
In [3]: expr = Eq(a*(x**2) + b*x + c, d)
In [4]: var_dict = dict(a=3, b=2, c=1, d=5)
In [5]: expr_with_numbers = expr.subs(var_dict)
In [6]: mathematica_code(expr_with_numbers).replace('==', '=')
Out[6]: '3*x^2 + 2*x + 1 = 5'

你也可以很容易地求解表达式:

In [7]: solve(expr_with_numbers, x)
Out[7]: [-1/3 + sqrt(13)/3, -sqrt(13)/3 - 1/3]

你可以打印任何类型的方程。例如

In [1]: from sympy import symbols, Eq, mathematica_code, sqrt, pretty, solve
In [2]: expr = Eq(a*(x**2)/(sqrt(x-c)), d)
In [3]: var_dict = dict(a=3, b=2, c=1, d=5)
In [4]: expr_with_numbers = expr.subs(var_dict)
In [5]: print(pretty(expr_with_numbers, use_unicode=False))
2
3*x
--------- = 5
_______
/ x - 1

优点

  • 如果你想创建复杂的数学表达式,这很有用
  • 还可以输出漂亮的多行输出,甚至LaTeX输出
  • 如果你想真正求解方程,这也很有用

缺点

  • 不是针对简单字符串形成进行速度优化的

您可以避免使用python建议的字符串格式连接多个字符串。

使用Format strings vs concatenation列出性能较高到性能较差的

  • f-string作为f"{a}x^2 + {b}x + {c} = {d}"
  • "%sx^2 + %sx + %s = %s" % (a,b,c,d)
  • "{}x^2 + {}x + {} = {}".format(a,b,c,d)

我可以建议字符串插值吗?

given_parabola = "%sx^2 + %sx + %s = %s" % (a, b, c, d)

或者

given_parabola = f"{a}x^2 + {b}x + {c} = {d}"

是的,希望这就是你的意思:

# This way the integer 10 will convert to a string automatically. Works in Print as well!
x = 10
y = "lemons"
z = "In the basket are %s %s" % (x, y)
print(z)

输出:

篮子里有10个柠檬

最新更新