0

如何编写一个函数,该函数将评分函数(我已经写过)和字符串对列表作为输入(我对如何编写感到困惑),并返回修改后的字符串对列表,其中返回的列表应包含输入中的所有最佳字符串对,根据输入函数评分。

示例输入:

'( ("hello" "b_low") ("hello_" "b_l_ow") ("hello" "_blow") ("hello" "blow") ("h_e_llo" "bl_o__w") )

示例输出:

( ("hello" "b_low") ("hello_" "b_l_ow") ("hello" "_blow") )

该函数采用如上所示的字符串对列表。它还接受一个函数。它使用这个函数作为评估字符串对列表的一种手段。然后,它返回一个字符串对列表,其中包含所有匹配分数最高的字符串对,这些字符串对基于它被赋予的用于评估它们的函数。换句话说,(("hello" "b_low") ("hello_" "b_l_ow") ("hello" "_blow")) 的分数都相同,都是 -3,但是 ("h_e_llo" "bl_o__w"))得分为-12,因此从列表中删除。

计算alignemt的函数:

(define (char-scorer char1 char2)
  (cond 
    ((char=? char1 char2) 2)
    ((or (char=? char1 #\_ ) (char=? #\_ char2)) -2)
    (else -1)))

(define (alignment-score s1 s2)
  (define min-length (min (string-length s1) (string-length s2)))
  (let loop ((score 0) (index 0))
    (if (= index min-length)
      score
      (loop (+ score (char-scorer (string-ref s1 index) (string-ref s2 index)))(+ index 1))))) 
4

1 回答 1

0

我会将操作分为两个步骤。

  1. 计算最高分。这是一个可以做到这一点的函数。

    (define (get-maximum-score lst scoring-func)
     (apply max (map (lambda (x) (scoring-func (car x) (cadr x))) lst)))
    
  2. 通过选择与最高分匹配的项目并删除其余项目来过滤列表。

    (define (get-maximum-score-items lst scoring-func)
    
      (define max-score (get-maximum-score lst scoring-func))
    
      (define (helper in out)
        (if (null? in)
          out
          (if (eq? max-score (scoring-func (caar in) (cadar in)))
            (helper (cdr in) (append out (list (car in))))
            (helper (cdr in) out))))
    
      (helper lst '())
      )
    

现在得到结果。

(print
 (get-maximum-score-items
  '(("hello" "b_low") ("hello_" "b_l_ow") ("hello" "_blow") ("hello" "blow") ("h_e_llo" "bl_o__w"))
     alignment-score))
于 2014-04-21T20:02:08.897 回答