如何从创建类多项式的新实例的三种不同方法中获取系数列表?
class Polynomial(object)
def __init__(self,*args)
self.coeffs=[]
...
pol1 = Polynomial([1,-3,0,2])
pol2 = Polynomial(1,-3,0,2)
pol3 = Polynomial(x0=1,x3=2,x1=-3)
我期待例如:pol2 = Polynomial(1,-3,0,2)
,输出为2x^3-3x+1
。但是我需要获得要列出的系数才能与它们一起工作。
答案 0 :(得分:0)
假设始终使用三种方法中的一种,您可以执行以下操作(无需任何验证):
class Polynomial(object):
def __init__(self, *args, **kwargs):
if args and isinstance(args[0], list): # Polynomial([1,-3,0,2])
self.coeffs=args[0]
elif args: # Polynomial(1,-3,0,2)
self.coeffs=args
else: # Polynomial(x0=1,x3=2,x1=-3)
self.coeffs=[kwargs.get(x, 0) for x in ('x0', 'x1', 'x2', 'x3')]
def __str__(self):
s = ''
for i, x in reversed(list(enumerate(self.coeffs))):
if x:
if x > 0:
s += '+'
s += str(x)
if i > 0:
s += 'x'
if i > 1:
s += '^' + str(i)
return '0' if not s else s.lstrip('+')
pol1 = Polynomial([1,-3,0,2])
pol2 = Polynomial(1,-3,0,2)
pol3 = Polynomial(x0=1, x1=-3, x3=2)
print(pol1) # 2x^3-3x+1
print(pol2) # 2x^3-3x+1
print(pol3) # 2x^3-3x+1
答案 1 :(得分:0)
除了schwobaseggl的回复,我还要添加这种检查:
if type(args[0]) == list:
self.coeffs=args
# ...
else:
self.coeffs=[kwargs.get(x, 0) for x in ['x'+i for i in range(len(kwargs))]]