我只需要编写一个将返回多项式中的项列表的函数,因此例如:例如,我们有3x ^ 4 + 2x ^ 3 + x ^ 2 + x +10,它将以以下形式返回输出: [coef变量指数]
到目前为止,我的功能:
(defn terms-of-poly [poly]
for [x (poly :coefficients)]
for [y(poly :variables)]
[x y])
输入:
(let [poly {:variable "y"
:coefficients [3 2 1 10]}]
(vec (terms-of-poly poly)))
输出:[[3“ x” 4] [2“ x” 3] [1“ x” 2] [10“ x” 0]]
解决方案可能看起来像这样:
(let [poly {:variable "y"
:coefficients [3 2 1 0 10]}]
(mapv vector
(rseq (:coefficients poly))
(repeat (:variable poly))
(range)))
;;=> [[10 "y" 0] [0 "y" 1] [1 "y" 2] [2 "y" 3] [3 "y" 4]]
它是反向的,但是您可以使用rseq
/反向reverse
(注意,我更改了输入,因为还有一个成员,即0x^1
)
与列表理解方法大致相同:
(let [poly {:variable "y"
:coefficients [3 2 1 0 10]}]
(for [[pow coeff] (map-indexed vector (rseq (:coefficients poly)))]
[coeff (:variable poly) pow]))
;;=> ([10 "y" 0] [0 "y" 1] [1 "y" 2] [2 "y" 3] [3 "y" 4])
您还可以使用零乘数过滤掉系数:
(let [poly {:variable "y"
:coefficients [3 2 1 0 10]}]
(for [[pow coeff] (map-indexed vector (rseq (:coefficients poly)))
:when (pos? coeff)]
[coeff (:variable poly) pow]))
;;=> ([10 "y" 0] [1 "y" 2] [2 "y" 3] [3 "y" 4])
更新
如果顺序很重要(虽然我想倒序应该没问题,因为每个元素都由它的力量来确定),则可以执行以下操作:
(defn terms-of-poly [{:keys [variable coefficients]}]
(map vector
coefficients
(repeat variable)
(range (dec (count coefficients)) -1 -1)))
(let [poly {:variable "y"
:coefficients [3 2 1 0 10]}]
(terms-of-poly poly))
;;=> ([3 "y" 4] [2 "y" 3] [1 "y" 2] [0 "y" 1] [10 "y" 0])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句