根据符号和指数对多项式进行排序 [英] Sort Polynomial based on Symbol and Exponent

查看:146
本文介绍了根据符号和指数对多项式进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Lisp写多项式算术,目前正在从事加法运算.我需要按指数和符号对多项式进行排序的帮助.我的多项式表示如下:

I'm writing writing polynomial arithmetic in lisp, and currently working on addition. I need help sorting a polynomial by the exponent and symbol. My polynomials are represented as follows:

((3 ((1 x)(1 y))) (1 ((3 y)))) ; == 3xy + 1y^3

我需要指导的功能有一个类似的术语

The function I need guidance with is given a term like

((5 ((3 x))) (3 ((3 y))) (4 ((2 z)))) ((6 ((3 x))) (1 ((3 y))) (9 ((2 z)))))

我想要:

((4 ((2 Z))) (9 ((2 Z))) (5 ((3 X))) (6 ((3 X))) (3 ((3 Y))) (1 ((3 Y))))

返回,以便所有z ^ 2和z ^ 2都在一起.

returned, so that all So all z^2 and z^2 are together.

推荐答案

您的初始示例显示了带有两个变量(例如3xy)的字词,但后面的示例却没有.此解决方案不会处理多变量术语的情况(您也没有说过如何在这种情况下进行分组),但是它将处理您的示例.

Your initial example shows terms with two variables (e.g., 3xy), but your example later on doesn't. This solution won't handle the multiple variable term case (and you haven't said how you'd want grouping in that case anyhow), but it will handle your example.

首先,定义一些用于处理多项式项的抽象,因为它们目前很不方便.以下三个函数使从每个项中提取系数,度和变量变得更加容易:

First, define some abstractions for working with your polynomial terms, because they're rather inconvenient at the moment. Here are three functions that make it much easier to extract the coefficient, degree, and variable from each term:

(defun polynomial-term-coefficient (term)
  (destructuring-bind (coefficient ((degree variable))) term
    (declare (ignore degree variable))
    coefficient))

(defun polynomial-term-degree (term)
  (destructuring-bind (coefficient ((degree variable))) term
    (declare (ignore coefficient variable))
    degree))

(defun polynomial-term-variable (term)
  (destructuring-bind (coefficient ((degree variable))) term
    (declare (ignore coefficient degree))
    variable))

然后,据我所知,您实际上是从两个多项式开始:5x 3 + 3y 3 + 4z 2 和6x 3 + y 3 + 9z 2 .您可以先将它们 add 一起添加,只需附加它们的术语列表即可.然后,您可以对字符串> 谓词(使用字符串指示符,因此符号就可以)进行排序,并具有键功能>多项式项变量.也就是说,您可以使用键功能提取您实际想要排序的值.

Then, as I understand your question, you're actually starting with two polynomials 5x3 + 3y3 + 4z2 and 6x3 + y3 + 9z2. You'd add those together first, just by appending the list of their terms. Then you can sort that on the predicate string> (which takes string designators, so symbols are OK), with a key function of polynomial-term-variable. That is, you use the key function to extract the value that you actually want to sort by.

(let ((p1 '((5 ((3 x))) (3 ((3 y))) (4 ((2 z)))))
      (p2 '((6 ((3 x))) (1 ((3 y))) (9 ((2 z))))))
  (let ((unsimplified-sum (append p1 p2)))
    (sort (copy-list unsimplified-sum) 'string> :key 'polynomial-term-variable)))
;=> ((4 ((2 Z))) (9 ((2 Z))) (3 ((3 Y))) (1 ((3 Y))) (5 ((3 X))) (6 ((3 X))))

这篇关于根据符号和指数对多项式进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆