[PAT-Advanced] A1009 Product of Polynomials (25)

总题解目录

[PAT- Advanced Level] 甲级题解目录(Advanced Level)

A1009 Product of Polynomials (25point(s))

This time, you are supposed to find A×B where A and B are two polynomials.

Input Specification:

Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:

K N​1​​ a​N​1​​ ​​ N​2​​ a​N​2​​ … N​K​​ a​N​K​​
​​
where K is the number of nonzero terms in the polynomial, N​i​​ and a​N​i​​ (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1 ≤ K ≤ 10, 0 ≤ N​K​​ <⋯< N​2​​ < N​1​​ ≤1000.

Output Specification:

For each test case you should output the product of A and B in one line, with the same format as the input. Notice that there must be NO extra space at the end of each line. Please be accurate up to 1 decimal place.

Sample Input:

2 1 2.4 0 3.2
2 2 1.5 1 0.5

Sample Output:

3 3 3.6 2 6.0 1 1.6

Analysis

  • 已知两个多项式的非零项个数k。依次给出k组数据(形式:次数 该次数前系数)。
  • 求两个多项式的乘积。输出格式与输入格式相同。
  • 分别处理第一个多项式和第二个多项式。按照指数相加,系数相乘,将结果存入结果数组。并计算非零项个数。注意系数需要保留一位小数。

  • 对比1002,给出python version

C++ Code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const int maxn = 1010;
int main(){
	double data1[maxn], data2[maxn], data3[2 * maxn];	// 乘积的长度最多翻倍(19、20 408)
	int k, exponent, count = 0;
	double coefficient;
	memset(data1, 0, sizeof(data1));	// data[i]存x^i前的系数
	memset(data2, 0, sizeof(data2));
	memset(data3, 0, sizeof(data3));
	scanf("%d", &k);		// 处理第一个多项式的数据
	for (int i = 0; i < k; i++){
		scanf("%d %lf", &exponent, &coefficient);
		data1[exponent] = coefficient;
	}
	scanf("%d", &k);		// 处理第二个多项式的数据
	for (int i = 0; i < k; i++){
		scanf("%d %lf", &exponent, &coefficient);
		data2[exponent] = coefficient;
	}
	for (int i = 0; i < maxn; i++){	// 对应项相乘,存储结果
		for (int j = 0; j < maxn; j++)
			data3[i + j] += data1[i] * data2[j];	// 次数相加,系数相乘
	}
	for (int i = 2 * maxn - 1; i >= 0; i--) {	// 计算非零项个数
		if (data3[i] != 0.0)
			count++;
	}
	printf("%d", count);
	for (int i = 2 * maxn - 1; i >= 0; i--) {
		if (data3[i])
			printf(" %d %.1f", i, data3[i]);
	}
	printf("\n");
	return 0;
}

Python Code

from collections import defaultdict
from copy import deepcopy


class polynomial:
    def __init__(self, items) -> None:
        self.items = items

    def __str__(self):
        msg = f"{len(self.items)}"
        # 本题注意点,系数要求从高到低排序,注意哦~
        sortedkeys = sorted(self.items.keys(), reverse=True)
        for k in sortedkeys:
            msg += f" {k:d} {self.items[k]:.1f}"	# 注意系数要保留一位小数
        return msg

    def __mul__(self, other):
        # 本题注意点。系数为0的项不用保存(打印),注意规避哦~
        res = defaultdict(float)
        for other_k, other_v in other.items.items():
            for self_k, self_v in self.items.items():
                res[self_k+other_k] += self_v * other_v
        res2 = deepcopy(res)	# 必须使用deepcopy,简单的=会再后面的操作中将两个字典中的内容一并更改
        for k, v in res2.items():
            if v == 0.0:
                res.pop(k)
        return type(self)(res)
        

def main():
    polynomials = []
    for _ in range(2):
        data = input().split()
        # 下面这行验证代码瞎写的,大家请不要在意:)
        assert int(data[0]) == int((len(data)-1)/2), "impossible, unless the test case is wrong"

        items = defaultdict(float)	# 这里的float使得默认新key对应的value是0.0
        for i in range(1, len(data)):
            if i % 2 == 0:
                items[int(data[i-1])] += float(data[i])

        p = polynomial(items)
        polynomials.append(p)
    
    print(polynomials[0] * polynomials[1])


if __name__ == "__main__":
    main()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值