List 球拍:计算兄弟姐妹的数量
以嵌套列表作为输入,我试图找到如何输出元素的“兄弟”数。就树而言,有多少其他叶节点属于同一父节点/根节点 我的代码给出了错误的输出(这是一个非常糟糕的代码),我不知道如何完全解决这个问题List 球拍:计算兄弟姐妹的数量,list,tree,nested,racket,siblings,List,Tree,Nested,Racket,Siblings,以嵌套列表作为输入,我试图找到如何输出元素的“兄弟”数。就树而言,有多少其他叶节点属于同一父节点/根节点 我的代码给出了错误的输出(这是一个非常糟糕的代码),我不知道如何完全解决这个问题 (define (siblings lst n) (cond [(empty? lst) false] [(member? n lst) (sub1 (length lst))] [else (siblings (rest lst) n)])) 样本结果:如果给定(列表(列表2
(define (siblings lst n)
(cond
[(empty? lst) false]
[(member? n lst) (sub1 (length lst))]
[else (siblings (rest lst) n)]))
样本结果:如果给定(列表(列表2 1)3(列表4))和3,则生成0
(list(list 1 2 3)(list(list 4 5 6))和5->2您的代码必须做两件独立的事情:
(define (find-branch root n)
(cond ((empty? root) empty)
((memq n root)
root)
((list? (first root))
(let ((subresult (find-branch (first root) n)))
(if (not (empty? subresult))
subresult
(find-branch (rest root) n))))
(else (find-branch (rest root) n))))
由于您使用的是“初学者”,这就需要从工具箱中取出所有工具。幸运的是,它仍然有number?
,因此,如果可以安全地假设在此作业中不是数字的任何内容都是一个列表,您可以这样定义list?
:
(define (list? n) (not (number? n)))
将示例树作为输入,它将返回:
(4 5 6)
上面的示例不必要地在
使用递归在同一列表上进行迭代后得到的输入列表
这里有一个更有效的版本,但您不能在初学者中实现它:
(define (find-branch root n)
(cond ((empty? root) false)
((memq n root) root)
(else (foldl (λ (a b)
(if (empty? a) b a))
empty
(map (λ (sublist)
(find-branch sublist n))
(filter list? root))))))
(define (count-siblings lst n counter)
(cond
[(empty? lst) counter]
[(and (not (list? (first lst)))
(not (eq? n (first lst))))
(count-siblings (rest lst) n (add1 counter))]
[else (count-siblings (rest lst) n counter)]))
您可以将结果传递给一个函数来计算兄弟姐妹数。我之前提供了一个可以在真实环境中使用的版本,但不是教师使用的初级学生版本:
(define (count-siblings root mem)
(count (λ (sib)
(and (not (eq? sib mem))
(not (list? sib)))) root))
以下是一个与初学者兼容的版本:
(define (find-branch root n)
(cond ((empty? root) false)
((memq n root) root)
(else (foldl (λ (a b)
(if (empty? a) b a))
empty
(map (λ (sublist)
(find-branch sublist n))
(filter list? root))))))
(define (count-siblings lst n counter)
(cond
[(empty? lst) counter]
[(and (not (list? (first lst)))
(not (eq? n (first lst))))
(count-siblings (rest lst) n (add1 counter))]
[else (count-siblings (rest lst) n counter)]))
最后,将两者结合起来:
(define (find/count-siblings root n)
(count-siblings (find-branch root n) n 0))
发布一些示例及其预期输出。
成员?
在中不存在!球拍
语言。有member
、memv
、和memq
。我目前使用的是初学者语言,没有本地定义或列表,有没有办法写出来?(define(list?n)(not(number?n))
,它会给你一个list?
的版本,这个版本应该足够适合这个作业(但如果在包含字符串、符号或初学学生所允许的任何其他内容的作业中使用它,它会给出错误的结果)。我重写了count sides
和find/count sides
,以解释缺乏本地定义的原因。