1010 一元多项式求导
题目:
设计函数求一元多项式的导数。(注: x n x^n xn (n为整数)的一阶导数为 n x n − 1 nx^{n-1} nxn−1 。)
输入格式:
以指数递降方式输入多项式非零项系数和指数(绝对值均为不超过 1000 的整数)。数字间以空格分隔。
输出格式:
以与输入相同的格式输出导数多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。注意“零多项式”的指数和系数都是 0,但是表示为 0 0
。
输入样例:
3 4 -5 2 6 1 -2 0
输出样例:
12 3 -10 1 6 0
1.0答案及分析
n = input().split()
poly_list = list(map(int, n))
i = 0
m = []
while i <= len(poly_list):
if poly_list[i+1] == 0:
break
else:
value = poly_list[i] * poly_list[i+1]
if poly_list[i+1] != 0:
m.append(value)
m.append(poly_list[i+1] - 1)
i = i + 2
result = ' '.join(map(str, m))
print(result)
编译通过,但是数据测试部分正确。
与参考答案对比分析:
本题的关键点在于
- 如果多项式是 A x 0 Ax^0 Ax0,输出应该是
0 0 #而不是直接pass,没有
- 如果多项式是 0 x 0 0x^0 0x0,输出应该是
0 0
- 如果多项式是 6 x 3 + 2 x 0 6x^3+2x^0 6x3+2x0,输出应该是
18 2 #不再有0 0
而1.0代码问题就在于直接判断指数是否为0(代码第6行),如果为0直接break,因此测试点1,2会报错
参考答案
n=input().split()
a=list(map(int,n))
i=0
c=[]
while not i==len(a):
m=a[i]*a[i+1]
b=a[i+1]-1
if m:
if a[i+1]==0 and not (a[i]==0):
pass
elif b==-1 and a[i]==0:
m=0
b=0
c.append(str(m))
c.append(str(b))
else:
c.append(str(m))
c.append(str(b))
i+=2
if not(len(c)):
print('0 0')
else:
print(' '.join(c).strip())
补充知识
- 在输入一系列数时,将str 转换为int 类型可以用
map()
,以下代码
a = list(map(int,n))
append()
方法可以直接改变列表的值,不用再赋值了