【问题标题】:Finding the position of a number in a list在列表中查找数字的位置
【发布时间】:2011-07-03 05:27:13
【问题描述】:

大家好,我有一个家庭作业问题一直让我很沮丧!我应该创建一个最小索引,它将采用一个非空列表并返回列表中最小数字的索引。 (car ls) 的索引 = 0,(car (cdr ls)) 的索引 = 1,依此类推。

需要创建一个助手来跟踪当前位置、最小位置、最小值和列表。到目前为止,我有一个显示基本算法的程序(不加载)。但是我很难跟踪所有内容并将其放入 chez 方案代码中。

(define index-helper
  (lambda (ls current-position least-position least-value)
    (if (> (car ls) least-value)
        (add1 (car ls (cdr ls (add1 current-position))))
        (car ls (cdr ls (add1 current-position))))))

;trace
;ls: (4231) c-pos: 0 least-value: 5 least-pos: 0
;ls: (231) c-pos: 1 least-value: 4 least-pos: 1
;ls: (31) c-pos 2 least-value: 2 least-pos: 2
;ls: 1 c-pos: 3 l-v: 2 l-pos: 2
;ls '() c-pos: 4 l-v: 1 l-pos: 4
;*least-position = current-position

我已经用谷歌搜索了这个并在 python 中找到了类似的问题,但我不明白代码,因为我是编程新手。 :P 如果有人可以给我一个提示,我真的很感激!

【问题讨论】:

  • 用#scheme 询问怎么样?我认为教师不希望他们的作业问题像这样出现在 Google 上。
  • @erjiang:IRC convos 也没有记录吗? ;-)
  • @Yasir:哈哈,是的,但是 SEO 已经这么多了。

标签: recursion scheme


【解决方案1】:

您需要两个功能。第一个函数找到最小元素x。第二个函数在列表中查找元素x 的索引。

类似:

(define (find-least xs)
  (foldl (lambda (e acc) (min e acc)) (car xs) xs))

(define (elem-index x xs)
  (define (elem-index-find x xs ind)
    (cond
      ((empty? xs) ind)
      ((eq? x (car xs))
       ind)
      (else (elem-index-find x (cdr xs) (+ ind 1)))))
  (if (empty? xs)
      (error "empty list")
      (elem-index-find x xs 0)))

(define (index-of-least xs)
  (let ((least (find-least xs)))
    (elem-index least xs)))

测试:

> (index-of-least (list 5 8 4 9 1 3 7 2))
4

或者,一次性完成:

(define (index-of-least-1-pass xs)
  (define (index-do least ind-least ind xs)
    (cond
      ((empty? xs) ind-least)
      ((< (car xs) least)
       (index-do (car xs) (+ ind 1) (+ ind 1) (cdr xs)))
      (else
       (index-do least ind-least (+ ind 1) (cdr xs)))))
  (index-do (car xs) 0 0 (cdr xs)))

测试:

> (index-of-least-1-pass (list 5 8 4 9 1 3 7 2))
4

index-do 辅助函数中,首先检查中间列表是否为空;这是一个基本情况,当我们在列表中只有一个元素并返回它的索引时。

下一个条件检查中间列表的下一个元素是否大于当前的 least 值,如果是,我们使用 least 的新值及其索引调用 helper。

最后一个条件被选中,当下一个元素不大于least时,调用leastind-least的值相同的辅助函数,去掉头元素的中间列表直到列表中没有元素,当列表中没有元素时,我们处理了基本情况。

【讨论】:

    【解决方案2】:

    named let 的一个很好的例子:

    (define (index-of-least xs)
      (let loop ((i 0) (p 0) (x (car xs)) (xs (cdr xs)))
        (cond ((null? xs) p)
              ((< (car xs) x) (loop (+ i 1) (+ i 1) (car xs) (cdr xs)))
              (else (loop (+ i 1) p x (cdr xs))))))
    
    (index-of-least (list 5 8 4 9 1 3 7 2)) => 4
    

    【讨论】:

      猜你喜欢
      • 2018-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多