【问题标题】:Racket function that returns all numbers whose sum is <= given number?球拍函数返回总和<=给定数字的所有数字?
【发布时间】:2016-11-22 09:14:01
【问题描述】:

我正在学习计算机科学课程的介绍,一个问题需要我编写一个函数,该函数接受一个数字列表和一个数字,并返回列表中总和小于给定数字的数字。我已经编写了函数签名、定义和检查预期,但我被卡住了。该函数需要假设具有 lambda 的中级学生。我不想在这里得到任何直接的答案;只是帮助我自己找到答案。

我知道它需要使用递归。也许需要一个辅助函数。

;; sum-up-to: lon, number -> lon
;; consumes a list of numbers and a number and
;; returns the numbers in the list whose sum is
;; less than or equal to the given number

(define the-numbers (list 1 2 3 4 5 6 7 8 9))

(check-expect (sum-up-to the-numbers 7) (list 1 2 3))
(check-expect (sum-up-to the-numbers 18) (list 1 2 3 4 5))
(check-expect (sum-up-to the-numbers 45) the-numbers)

【问题讨论】:

  • 我们可以假设输入列表是按升序排序的吗?如果没有,我们可以使用现有的排序程序吗?
  • 是的,升序。它只返回列表中总和小于或等于给定数字的第一个数字。
  • 好的,那我的回答是对的:)。忘记排序输入列表,因为我们可以假设列表已经排序。

标签: racket


【解决方案1】:

如果我们首先对列表进行排序,并且如果我们定义一个跟踪累积和的辅助函数,则可以简化此问题。这是一个骨架,用缺少的表达式填空,你就会得到解决方案:

(define (sum-up-to lst n)
  (helper <???> n 0)) ; sort the input list, pass it to the helper

(define (helper lst n sum)
  (cond (<???> '())       ; if the list is empty, end the recursion
        ((> <???> n) '()) ; also end recursion if sum + current element > n
        (else
         (cons <???>         ; otherwise cons current element
               (helper <???> ; advance recursion over list
                       n
                       (+ <???> <???>)))))) ; update sum

【讨论】:

  • 非常感谢!我想通了。
【解决方案2】:

以下递归方法不断将列表中的数字按顺序添加到最初为空的 outlist 中,直到达到总和:

(define the-numbers (list 1 2 3 4 5 6 7 8 9))

(define (f lst sum)
  (let loop ((lst lst)
             (ol '()))
    (if (or (..ENTER CONDITION FOR EMPTY LIST..)
            (..ENTER CONDITION WHEN SUM IS REACHED..)
        (..ENTER HOW TO PUT THE NEW LIST OUT..)
        (loop (..ENTER ARGUMENTS TO BE SENT TO NEXT LOOP..)
        ))))

(f the-numbers 7)
(f the-numbers 18)
(f the-numbers 45)

输出:

'(1 2 3)
'(1 2 3 4 5)
'(1 2 3 4 5 6 7 8 9)

【讨论】:

  • 我已经修改了上面的答案。
猜你喜欢
  • 1970-01-01
  • 2016-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-23
  • 2018-01-02
  • 1970-01-01
  • 2016-07-05
相关资源
最近更新 更多