【问题标题】:Difficulty trying to take the n-th root of a product of n numbers尝试对 n 个数字的乘积求 n 次根的难度
【发布时间】:2019-02-09 18:38:35
【问题描述】:

我正在尝试创建一个递归函数,它接收 n 个数字的列表。这个函数应该做的是取 n 个数字的乘积,然后取 n 个根。我得到了 n 个数字的乘积,但不知道如何实现第 n 个根。

我尝试做的是实现 expt x y 函数,但无法在 中正确使用它。此外,在尝试实现此功能时,我也不知道如何将 expt 功能提供给第 n 个根。 (y=1/n)

(define (nth-root-of-product-of-numbers lst)
  (cond [(empty? lst) 1]
        [else (* (first lst) (nth-root-of-product-of-numbers (rest lst)))]))

因此,上面的代码正确地生成了 n 数列表中的乘积,但是它不能补偿 n 次根问题。示例输入为:

(check-within
(nth-root-of-product-of-numbers (cons 9 (cons 14 (cons 2 empty)))) 6.316359598 0.0001)

【问题讨论】:

  • 请使用示例输入和预期输出编辑问题。
  • 好的。我已经在示例输入和预期输出中进行了编辑。

标签: recursion recursion scheme racket


【解决方案1】:

您需要在递归结束时计算第 n 个根。有几种方法可以做到这一点 - 例如,定义一个帮助程序来查找产品并在计算后获取根:

(define (nth-root-of-product-of-numbers lst)
  (define (product lst)
    (cond [(empty? lst) 1]
          [else (* (first lst) (product (rest lst)))]))
  (expt (product lst) (/ 1 (length lst))))

一个更有效的解决方案是编写一个尾递归过程,并传递元素的数量以避免在末尾计算length。下面是如何使用named let

(define (nth-root-of-product-of-numbers lst)
  (let loop ((lst lst) (acc 1) (n 0))
    (cond [(empty? lst)
           (expt acc (/ 1 n))]
          [else
           (loop (rest lst) (* (first lst) acc) (add1 n))])))

更惯用的解决方案是使用内置程序来计算乘积:

(define (nth-root-of-product-of-numbers lst)
  (expt (apply * lst) (/ 1 (length lst))))

无论如何,它按预期工作:

(nth-root-of-product-of-numbers (list 9 14 2))
=> 6.316359597656378

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-27
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 2017-04-13
    • 2014-08-04
    相关资源
    最近更新 更多