-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_polynomial_feature.py
72 lines (69 loc) · 2.65 KB
/
get_polynomial_feature.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
def get_polynomial(*n):
"""生成多项式。第一个形参为次数,其他形参为系数"""
power, coefficients = n[0], {}
for i in range(power+1):
coefficients['a' + str(i+1)] = n[i+1] # 存储系数的字典
counter = 0
polynomial = ""
while counter <= power:
poly = coefficients[f'a{counter+1}']
if abs(poly) != 1: # 判断系数绝对值是否为1
if counter != 0: # 判断是否为最高次项
if power-counter != 1: # 判断是否为一次项
if counter != power: # 判断是否为常数项
if poly > 0:
polynomial += f"+{poly}*x**{power-counter}"
elif poly < 0:
polynomial += f"{poly}*x**{power-counter}"
else:
pass
else:
if poly > 0:
polynomial += '+' + str(poly)
elif poly < 0:
polynomial += '-' + str(poly)
else:
pass
else:
if poly > 0:
polynomial += "+" + str(poly) + "*x"
elif poly < 0:
polynomial += "-" + str(poly) + "*x"
else:
pass
else:
if poly > 0:
polynomial += f"{poly}*x**{power-counter}"
elif poly < 0:
polynomial += f"{poly}*x**{power-counter}"
else:
pass
else:
if counter != 0:
if power-counter != 1:
if counter != power:
if poly > 0:
polynomial += f"+x**{power-counter}"
else:
polynomial += f"-x**{power-counter}"
else:
if poly > 0:
polynomial += '+1'
else:
polynomial += '-1'
else:
if poly > 0:
polynomial += "+x"
else:
polynomial += "-x"
else:
if poly > 0:
polynomial += f"x**{power-counter}"
elif poly < 0:
polynomial += f"-x**{power-counter}"
else:
pass
counter += 1
return polynomial
if __name__ == '__main__':
print(get_polynomial(3, 5, -1, 0, 11))