Recursion 查找数字在列表中的位置
嘿,伙计们,我有一个家庭作业问题一直困扰着我!我应该创建一个最小值的索引,它将接受一个非空列表,并返回列表中最小值的索引。(car ls)的索引=0,(car(cdr ls))的索引=1,依此类推 需要创建一个助手来跟踪当前位置、最小位置、最小值和列表。到目前为止,我有一个程序(不加载)显示了基本算法。。但我很难跟踪每件事,并将其放入chez方案代码中Recursion 查找数字在列表中的位置,recursion,scheme,Recursion,Scheme,嘿,伙计们,我有一个家庭作业问题一直困扰着我!我应该创建一个最小值的索引,它将接受一个非空列表,并返回列表中最小值的索引。(car ls)的索引=0,(car(cdr ls))的索引=1,依此类推 需要创建一个助手来跟踪当前位置、最小位置、最小值和列表。到目前为止,我有一个程序(不加载)显示了基本算法。。但我很难跟踪每件事,并将其放入chez方案代码中 (define index-helper (lambda (ls current-position least-position least
(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
如果有人能给我一个提示,我将非常感激 您需要两个函数。第一个函数查找最小的元素
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)))
测试:
或者,一次性:
(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 do
helper函数中,首先检查中间列表是否为空;这是一个基本情况,当列表中只有一个元素,并返回其索引时
下一个条件检查中间列表的下一个元素是否大于当前的least
值,如果大于,则使用least
的新值及其索引调用helper
选择最后一个条件,当下一个元素不大于最小值
,它调用具有相同值最小值
和ind最小值
的helper函数,中间列表移除head元素,直到列表中没有元素,我们接近基本情况,当列表中没有元素时。命名let的一个好例子:
(定义(最少xs的索引)
(让循环((i0)(p0)(x(carxs))(xs(cdrxs)))
(cond((null?xs)p)
(<(汽车xs)x)(环路(+i 1)(+i 1)(汽车xs)(cdr xs)))
(else(循环(+i1)px(cdr-xs()()())))
(最小的索引(列表5 8 4 9 1 3 7 2))=>4
改为询问方案如何?我认为老师们不希望他们的作业问题像这样出现在谷歌上。@erjiang:IRC车队也被记录了吗?;-)@亚西尔:哈哈,是的,但搜索引擎优化也一直如此。
(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
(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