[英]Pretty printing polynomials with dictionary python
我正在努力创建具有多项式的__ str __
函数(又名漂亮打印),其中使用字典将幂包含为键,将元素包含为系数。 我已经完成了列表操作,但是还没有掌握字典。 有什么需要改进的吗?
您可以在第二个多项式中看到,如果我的最后一个常数不是常数,则在使用reverse()
函数排列键之后,加号始终存在,我该怎么做才能防止这种情况? 顺便说一下,我尝试重载运算符,完成此操作后,我将尝试执行__ add__
__ mul__
, __ sub__
__ mul__
, __ sub__
和__ call__
……尽管我会先完成此操作:P
class Polynomial(object):
def __init__(self, coefficients):
self.coefficients = coefficients
def __str__(self):
polyd = self.coefficients
exponent = polyd.keys()
exponent.reverse()
polytostring = ' '
for i in exponent:
exponent = i
coefficient = polyd[i]
if i == 0:
polytostring += '%s' % coefficient
break
polytostring += '%sx^%s + ' % (coefficient, exponent)
return polytostring
dict1 = {0:1,1:-1}
p1 = Polynomial(dict1)
dict2 = {1:1,4:-6,5:-1, 3:2}
p2 = Polynomial(dict2)
print p1
print p2
如果我了解您的问题,则类似的事情似乎可行:
def format_term(coef, exp):
if exp == 0:
return "%d" % coef
else:
return "%dx^%d" % (coef, exp)
def format_poly(d):
items = sorted(d.items(), reverse=True)
terms = [format_term(v,k) for (k,v) in items]
return " + ".join(terms)
dict1 = {0:1,1:-1}
print(format_poly(dict1)) # -1x^1 + 1
dict2 = {1:1,4:-6,5:-1, 3:2}
print(format_poly(dict2)) # -1x^5 + -6x^4 + 2x^3 + 1x^1
它只是按键对(key,val)对进行排序,然后格式化每个术语,并将这些术语连接到单个字符串中。
0
时, for
循环将结束(break)。 码:
class Polynomial(object):
def __init__(self, coefficients):
self.coefficients = coefficients
def __str__(self):
polytostring = ' '
for exponent, coefficient in self.coefficients.iteritems():
if exponent == 0:
polytostring += '%s + ' % coefficient
else:
polytostring += '%sx^%s + ' % (coefficient, exponent)
polytostring = polytostring.strip(" + ")
return polytostring
dict1 = {0:1, 1:-1}
p1 = Polynomial(dict1)
dict2 = {1:1, 4:-6, 5:-1, 3:2}
p2 = Polynomial(dict2)
print "First:-", p1
print "Second:-", p2
输出:
$ python poly.py
First:- 1 + -1x^1
Second:- 1x^1 + 2x^3 + -6x^4 + -1x^5
这很紧凑
def __str__(self):return"".join("%+gx^%d"%(self.coefficients[e],e)for e in sorted(self.coefficients.keys(),reverse=1))
和工作...
让我们来看一次return
ed表达式
"".join(...)
字符串方法之一是.join()
,它接受一系列字符串并将它们与(在这种情况下)空字符串连接起来,例如
" + ".join(["a", "b", "c"] => "a + b + c"
在我们的例子中, join
的参数是
"%+gx^%d"%(self.coefficients[e],e)for e in sorted(self.coefficients.keys(),reverse=1)
带括号的是生成器表达式 ,顺便说一句,类似于隐式的for
循环。
在右边有
for e in sorted(self.coefficients.keys(),reverse=1))
依次将分配给局部变量e
的self.coefficients
的keys
排序和反转
左侧是生成器表达式的结果,针对e
每个可能值进行评估
"%+gx^%d"%(self.coefficients[e],e)
上面的表达式称为字符串格式或插值 ,其工作原理如下:
左边的字符串是格式字符串,并且其中以%
开头的部分是_format说明符,此处%+g
表示始终以符号开头的 通用格式, %d
表示整数digit ,外面是什么(此处为'x ^``)被原样复制到结果中,
中间的%
是格式运算符本身
元组(self.coefficients[e], e)
是格式字符串的参数,您必须在格式说明符和参数之间具有1到1的对应关系
在这一点上,我们已经准备好了所有的组件……以通俗易懂的形式
def __str__(self):
# generated a correctly sorted list of exponents
exps = sorted(self.coefficients.keys(),reverse=True)
# generate a corretctly sorted list of coefficients
coefs = [self.coefficients[e] for e in exps]
# generate a list of formatted strings, one for each term
reps = [ "%+gx^%d" % (c, e) for c, e in zip(coefs, exps)]
# join the formatted strings
poly_rep = "".join(reps)
# let's end this story
return poly_rep
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.