[PAT-Advanced] A1002 A+B for Polynomials (25)

总题解目录

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

A1002 A+B for 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 K\quad N​_{1}\quad a​_{N​1}\quad N_{​2}\quad a_{​N2}\quad ...\quad N_{​K}\quad a_{​N​K} KN1aN​1N​2aN2...NKaNK
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≤ NK​​ < ⋯ < N​2​​ < N​1​​ ≤1000.

Output Specification:

For each test case you should output the sum 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 to 1 decimal place.

Sample Input:

2 1 2.4 0 3.2
2 2 1.5 1 0.5

Sample Output:

3 2 1.5 1 2.9 0 3.2

Analysis

  • 本题是做多项式加法,我的做法是取一个数组,对应编号即为对应次方。输出非零项即可
  • 注意结果要精确到小数点后1位哦~

  • 突然想吐槽一下为啥我以前这么喜欢写全局变量啊?! 😦
  • 原来的写法挺好的,本题在C++中要把最后的输出控制在一个string中会让程序变得过于丑陋(拿不出手)
  • 所以写一个Python version。面向对象哦 😃
  • 同时贴出AC结果,可以看到时间和空间上两种方法的区别

C++ Code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
double res[1011];
int main(){
	int k, n, cnt = 0;
	double a;
	memset(res, 0, sizeof(res));
	for (int i = 0; i < 2; i++){
		scanf("%d", &k);
		while (k--){
			scanf("%d %lf", &n, &a);
			res[n] += a;		// 第x的n次方前系数相加
		}
	}
	for (int i = 1010; i >= 0; i--)
		if (res[i] != 0)
			cnt++;
	printf("%d", cnt);
	for (int i = 1010; i >= 0; i--){
		if (res[i] == 0) continue;
		printf(" %d %.1f", i, res[i]);
	}
	return 0;
}

在这里插入图片描述

Python Code

from collections import defaultdict


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 __add__(self, other):
        for k, v in other.items.items():
 			# 本题注意点。系数为0的项不用保存(打印),注意规避哦~
            if self.items[k] + v == 0:
                self.items.pop(k)
            else:
                self.items[k] += v
        return type(self)(self.items)
        

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值