用python字典打印多项式

用python字典打印多项式,python,dictionary,polynomials,Python,Dictionary,Polynomials,我正在努力用多项式创建\uuu__函数(又名pretty print),其中字典用于包含幂作为键,元素作为系数。我已经用列表完成了,但我还没有掌握字典。有什么需要改进的吗 您可以在第二个多项式中看到,如果我的最后一个常数不是常数,在使用reverse()函数排列键之后,加号总是存在的,我该怎么做才能防止出现这种情况?顺便说一句,我正在尝试重载运算符,在我完成这项工作之后,我将尝试执行\uuuuuuuuuuuuuuuuuuuuu、\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu

我正在努力用多项式创建
\uuu__
函数(又名pretty print),其中字典用于包含幂作为键,元素作为系数。我已经用列表完成了,但我还没有掌握字典。有什么需要改进的吗

您可以在第二个多项式中看到,如果我的最后一个常数不是常数,在使用
reverse()
函数排列键之后,加号总是存在的,我该怎么做才能防止出现这种情况?顺便说一句,我正在尝试重载运算符,在我完成这项工作之后,我将尝试执行
\uuuuuuuuuuuuuuuuuuuuu
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
调用。。。虽然我会先完成这个: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)对进行排序,然后格式化每个术语,并将这些术语合并成一个字符串。

如果我理解您的问题,类似的方法似乎有效:

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)对进行排序,然后格式化每个术语,并将术语合并成单个字符串

  • 删除break语句,因为当指数值等于
    0
    时,for
  • 循环将结束(break) 代码:

    输出:

    $ python poly.py 
    First:- 1 + -1x^1
    Second:- 1x^1 + 2x^3 + -6x^4 + -1x^5
    
  • 删除break语句,因为当指数值等于
    0
    时,for
  • 循环将结束(break) 代码:

    输出:

    $ python poly.py 
    First:- 1 + -1x^1
    Second:- 1x^1 + 2x^3 + -6x^4 + -1x^5
    
    这是紧凑型的

    而且工作


    让我们看看
    return
    ed的表达式,一次一个片段

    "".join(...)
    
    string方法之一是接受字符串序列并将其与空字符串(在本例中)连接,例如

    " + ".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
    ,依次按排序和倒序分配
    自系数的

    左边是生成器表达式的结果,针对
    e

    "%+gx^%d"%(self.coefficients[e],e)
    
    上面的表达式称为 而且是这样工作的,

  • 左边的字符串是一个格式字符串,其中以
    %
    为前缀的部分是格式说明符,这里
    %+g
    表示一般格式总是以符号为前缀,
    %d
    表示整数,外部的内容(这里的`x^``复制到结果中

  • >P>中间的“代码> %”是格式化操作符本身

  • 元组
    (self.coverties[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
    
    这是紧凑型的

    而且工作


    让我们看看
    return
    ed的表达式,一次一个片段

    "".join(...)
    
    string方法之一是接受字符串序列并将其与空字符串(在本例中)连接,例如

    " + ".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
    ,依次按排序和倒序分配
    自系数的

    左边是生成器表达式的结果,针对
    e

    "%+gx^%d"%(self.coefficients[e],e)
    
    上面的表达式称为 而且是这样工作的,

  • 左边的字符串是一个格式字符串,其中以
    %
    为前缀的部分是格式说明符,这里
    %+g
    表示一般格式总是以符号为前缀,
    %d
    表示整数,外部的内容(这里的`x^``复制到结果中

  • >P>中间的“代码> %”是格式化操作符本身

  • 元组
    (self.coverties[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
    

    打印语句应接受哪些输出?(:P)
    exponent.reverse()
    还不够。。。请注意,字典的
    键不会按任何特定顺序返回。您想要的是
    exponent.sort(reverse=true)
    By
    exponent=i
    在循环中,您正在丢弃
    exponent
    列表的内容。。。这是您真正想要的吗?打印语句应该接受哪些输出?(:P)
    exponent.reverse()
    还不够。。。请注意,字典的
    键不会按任何特定顺序返回。您想要的是
    exponent.sort(reverse=true)
    By
    exponent=i
    在循环中,您正在丢弃
    exponent
    列表的内容。。。这是你真正想要的吗?