1. 程式人生 > >PAT程式設計練習——甲級1002(兩個多項式的解析與合併)

PAT程式設計練習——甲級1002(兩個多項式的解析與合併)

翻譯題目要求:

程式輸入為兩行:均為一個多項式,按 K N1 An1 N2 An2......Nk Ank,K代表的是多項式的非零項數,範圍閉區間是[1,10],N1到Nk的範圍區間是 1<= Nk <= ......<= N1 <= 1000;

Nk是指數,Ank是係數,遇到相同的指數,係數進行累加,從而合併成一個多項式。

例子輸入:

2 1 2.4 0 3.2
2 2 1.5 1 0.5

可以解析成:

第一行: 2個子項---1*2.4 + 0*3.2

第二行: 2個子項---2*1.5 + 1*0.5

其中指數部分,二者有重合,可以累加,結果有 1*(2.4 + 0.5)

輸出:

3 2 1.5 1 2.9 0 3.2

可以理解成: 3個子項---2*1.5 + 1*2.9 + 0*3.2

設計思路如下:

在控制檯情況下輸入兩行,按照格式解析出多項式後,用結構體儲存每一項係數和指數:

typedef struct
{
	int exponents;                                          //係數
	float coeffients;                                       //指數
}Polynomials;

再使用歸併排序的類似實現把兩個多項式合併在一起,完整程式碼如下:
#include <stdio.h>
#include <string.h>

typedef struct
{
	int exponents;
	float coeffients;
}Polynomials;

int size1 = 0;
int size2 = 0;
int size3 = 0;
Polynomials poly1[10] = {0};
Polynomials poly2[10] = {0};
Polynomials poly3[20] = {0};
// 把scanf輸入儲存到多項式結構體中
int save( char* input, Polynomials* poly, int& size )
{
	int expo = 0;
	float coeff = 0;
	char* p = NULL;
	char* q = NULL;
	char szbuffer[100] = {0};

	sscanf(input, "%d %s", &size, szbuffer );
	p = input;

	for ( int i = 0; i < size; i++ )
	{
		memset(szbuffer, 0, sizeof(szbuffer) );
		while( *p != ' ') p++;
		q = p + 1 ;
		while( *q != ' ') q++;
		q++;
		while( *q != ' ') 
		{
			q++;
			if ( (q - input) == strlen(input) )//the end case
				break;
		}
		q--;

		strncpy( szbuffer, p, q-p+1 );
		sscanf( szbuffer, "%d %f",&expo, &coeff );
		poly[i].coeffients = coeff;
		poly[i].exponents = expo;
		p = q+1;
	}
	return 0;
}
// 仿照歸併排序的思路合併多項式
int sort()
{
	int poly_index1 = 0, poly_index2 = 0;
	int result_size = size1 + size2;

	for ( int i = 0; i < result_size; i++ )
	{
		int expo1 = -1;
		int expo2 = -1;
		if ( poly_index1 != size1 )
		{
			expo1 = poly1[poly_index1].exponents;
		}
		if ( poly_index2 != size2 )
		{
			expo2 = poly2[poly_index2].exponents;
		}
		if ( expo1 > expo2 )
		{
			poly3[i].exponents = expo1;
			poly3[i].coeffients = poly1[poly_index1].coeffients;
			poly_index1++;
		}
		else if ( expo1 < expo2 )
		{
			poly3[i].exponents = expo2;
			poly3[i].coeffients = poly2[poly_index2].coeffients;
			poly_index2++;
		}
		else
		{
			poly3[i].exponents = expo1;
			poly3[i].coeffients = poly1[poly_index1].coeffients + poly2[poly_index2].coeffients;
			poly_index1++;
			poly_index2++;

			result_size--;                                     //出現重複可以累加的合併項,總長度減一
		}
	}
	size3 = result_size;
	return 0;
}
// 列印多項式結果
int print()
{
	char szResult[200] = {0};
	sprintf_s(szResult,"%d",size3);

	for ( int i = 0; i < size3; i++ )
	{
		char buffer[20] = {0};
		sprintf_s(buffer, " %d %.1f", poly3[i].exponents, poly3[i].coeffients );
		strcat(szResult, buffer);
	}
	printf( "%s\n", szResult );
	return 0;
}
/************************************************************************/
//Input
//2 1 2.4 0 3.2
//2 2 1.5 1 0.5

//Output
//3 2 1.5 1 2.9 0 3.2
/************************************************************************/
int main()
{
	char szInput[100] = {0};
	printf("Please input first Polynomials:\n");
	scanf("%[^\n]",szInput);
	save(szInput,poly1,size1);

	memset(szInput, 0, sizeof(szInput));
	printf("Please input second Polynomials:\n");
	getchar();
	scanf("%[^\n]",szInput);
	save(szInput,poly2,size2);

	sort();

	print();
	return 0;
}

Python程式碼如下:
#the struct definition
class Polynomials:
 def __init__(self,exponents,coeffients):
  self.exponents = int(exponents) 
  self.coeffients = float(coeffients)

#the list array
poly1=[]
poly2=[]
poly_result=[]
poly_size1 = []
poly_size2 = []
poly_size3 = [] 

#main function 
def __main():
 str_input = raw_input("Please input the first polynomials:\n")
 print("the input is:",str_input)
 parse( str_input, poly1, poly_size1 )
 str_input = raw_input("Please input the second polynomials:\n")
 print("the input is:",str_input)
 parse( str_input, poly2, poly_size2 )
 calc()
 output()

#parse the polynomials from the parameters
def parse( str_input, poly_list, poly_size ):
 poly_size.append(str_input.split(' ',1)[0])
 str_input = str_input.split(' ',1)[1]
 str_input = str_input.split(' ')
 #print( str_input[0], len(str_input), str_input[1] )
 for i in range(0,len(str_input),2):
  tmp = Polynomials( str_input[i],str_input[i+1] )
  poly_list.append(tmp) 

#calculate the combination of 2 polynomials
def calc():
 poly_index1 = 0
 poly_index2 = 0
 result_size = int(poly_size1[0]) + int(poly_size2[0])
 print( "calc, result_size:", poly_size1[0], poly_size2[0], result_size )
 print( "poly1,poly2", poly1[0].exponents,poly2[0].exponents )
 print( "poly1, poly2", poly1[1].exponents, poly2[1].exponents )
 for i in range(0,result_size):
  expo1 = -1; expo2 = -1
  if( poly_index1 != int(poly_size1[0]) ):
   expo1 = poly1[poly_index1].exponents
  if( poly_index2 != int(poly_size2[0]) ):
   expo2 = poly2[poly_index2].exponents
  if( expo1 is -1 and expo2 is -1 ):
   break;
  if( expo1 > expo2 ):
   tmp = Polynomials( expo1, poly1[poly_index1].coeffients )
   poly_result.append(tmp)
   poly_index1 += 1
   print( ">>1<<")
  elif( expo1 < expo2 ):
   tmp = Polynomials( expo2, poly2[poly_index2].coeffients )
   poly_result.append(tmp)
   poly_index2 += 1
   print( ">> 2<<")
  else:
   tmp = Polynomials( expo1, poly1[poly_index1].coeffients + poly2[poly_index2].coeffients )
   poly_result.append(tmp)
   poly_index1 += 1
   poly_index2 += 1
   result_size -= 1
   print(">> 3 <<")
 poly_size3.append(result_size)
 print("poly_size3:",poly_size3[0])
 print("result_size:",result_size )

def output():
 print( "result:", poly_size3[0] )
 print( "content:", poly_result[0].exponents, poly_result[0].coeffients,  poly_result[1].exponents, poly_result[1].coeffients, poly_result[2].exponents, poly_result[2].coeffients )
 for i in range(0,poly_size3[0] ):
  print("exponents:coeffients",poly_result[i].exponents,poly_result[i].coeffients )
#run the main function
__main()


可能還有其他更優化的辦法,正在考慮當中。。。