如何解决返回Clojure中的多项式的项
我只需要编写一个将返回多项式中的项列表的函数,因此例如:说我们有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])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。