【问题标题】:Find minimum pairwise product in two lists在两个列表中查找最小成对积
【发布时间】:2021-07-01 21:44:00
【问题描述】:

我需要编写一个执行以下操作的函数:给定[ 2 6 3 ] 和[ 4 6 2 ],它们的乘积是[ (2 * 4) (6 * 6) (3 * 2) ],或[ 8 36 6 ], 所以最小的产品是6。

我有一个辅助函数来获取每个列表中的最小整数:

(define ( myListMax Lst )
( if ( null? Lst )
0
( if ( null? ( cdr Lst ) )
( car Lst )
( if ( > ( car Lst ) ( myListMax ( cdr Lst ) ) )
( car Lst )
( myListMax ( cdr Lst ) )
)
)
)
)

我有以下函数调用辅助函数来帮助我实现目标。这是函数:

(define (smallProd LstOne LstTwo)

(* 
(myListLeast(LstOne) (myListLeast(LstTwo)
))))

但是当我运行我的代码时,我收到以下消息:

(smallProd '(1 2 3) '(4 5 6))

; application: not a procedure;
;  expected a procedure that can be applied to arguments
;   given: '(1 2 3)
; [,bt for context]

我将不胜感激。

【问题讨论】:

  • 括号在 lisps 中是有意义的,你不能随意添加它们。我不太确定这应该是什么,但它肯定不会有什么好处:(myListLeast(LstOne) (myListLeast(LstTwo))。这就是您报告错误的原因:(LstOne) --> ((1 2 3)) 正在尝试将列表 (1 2 3) 作为过程调用。
  • 提示 #1:请查看其他 Scheme 或 Racket 代码并注意其格式,然后进行仿真。特别是,不要把括号到处乱扔。提示#2:您解决问题的方法不起作用。它适用于(1 2 3) 和(4 5 6) 的过度简化的测试数据,但不适用于(2 6 3) 和(4 6 2);您的方法产生 4,但(正如您已经指出的)答案是 6。
  • 使用示例所采用的方法——首先将列表元素相乘得到另一个列表,然后取最小的元素。 (您还可以“即时”找到最小值。)
  • 请选择一个可以被有相同问题的人搜索的非通用标题。 “方案编程功能辅助”可能意味着几乎任何东西。 “在两个列表中查找最小成对积”是具体的、有意义的和可搜索的。另见:Why is “Can someone help me?” not an actual question?

标签: list recursion scheme racket


【解决方案1】:

您的代码(具有固定格式)假设两个最小的数字位于同一位置 -

(define (smallProd LstOne LstTwo)
  (* (myListLeast LstOne)      ; fixed parens
     (myListLeast LstTwo)))    ; fixed parens

如果将其应用于'(2 6 3) 和'(4 6 2) 的示例输入,则两个最小的数字将是2 和2,结果为2 * 2 = 4。这是不正确的,因为'((* 2 4) (* 6 6) (* 3 2)) 的最小积 来自3 * 2,即6。

(define (smallest-product a b)
  (if (or (null? a) (null? b))                   ; if either list is empty
      +inf.0                                     ; return base case
      (min (* (car a) (car b))                   ; otherwise min of 1st product
           (smallest-product (cdr a) (cdr b))))) ; and the recursive result
(define (min a b)
  (if (< a b)       ; if a is less than b
      a             ; return a
      b))           ; otherwise b
(smallest-product '(2 6 3) '(4 6 2))
6.0

如果输入一个空列表,则不能有最小乘积。在这种情况下positive infinity,+inf.0,被返回-

(smallest-product '() '(5))
(smallest-product '(5) '())
(smallest-product '() '())
+inf.0
+inf.0
+inf.0

Scheme/Racket 与 C/Java 家族中的语言明显不同。它对初学者非常友好,但是如果您尝试引入从其他语言中获得的练习,您将会遇到困难。花时间学习这种强大的语言提高了我在所有其他语言中的编程技能。把所有东西都放在门口,你会得到最大的好处。

【讨论】:

  • 非常感谢您提供有关学习新语言的建议 - 我非常感谢。我将确保实践您提出的关于将不同语言的实践带给其他人的重要观点。再次感谢您!
猜你喜欢
  • 2021-01-25
  • 2021-07-28
  • 2014-04-09
  • 2012-04-18
  • 2014-02-24
  • 1970-01-01
  • 1970-01-01
  • 2017-03-11
  • 1970-01-01
相关资源
最近更新 更多