PAT (Basic Level) Practice (中文)1010 一元多项式求导 (25 分)
题目
设计函数求一元多项式的导数。(注:xn (n为整数)的一阶导数为nxn−1 。)
输入格式:
以指数递降方式输入多项式非零项系数和指数(绝对值均为不超过 1000 的整数)。数字间以空格分隔。
输出格式:
以与输入相同的格式输出导数多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。注意“零多项式”的指数和系数都是0,但是表示为 0 0。
输入样例:
3 4 -5 2 6 1 -2 0
输出样例:
12 3 -10 1 6 0
C++实现
#include <iostream>
using namespace std;
int main()
{
int a,n,flag=0;
while (cin>>a>>n)
{
if (n!=0)
{
if (flag==1) cout<<' ';
cout<<a*n<<' '<<n-1;
flag=1;
}
}
if (flag==0) cout<<"0 0";
return 0;
}
python实现
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())