Mar*_*erk -2 lisp scheme racket python-2.7
我目前正在尝试翻译这个 python 2 代码:
import math
def worstCaseArrayOfSize(n):
if n == 1:
return [1]
else:
top = worstCaseArrayOfSize(int(math.floor(float(n) / 2)))
bottom = worstCaseArrayOfSize(int(math.ceil(float(n) / 2)))
return map(lambda x: x * 2, top) + map(lambda x: x * 2 - 1, bottom)
Run Code Online (Sandbox Code Playgroud)
进入球拍/方案代码,并且遇到困难。
这是我到目前为止:
(define (msortWorstCase n)
(cond
[(equal? 1 n) 1]
[else (let* ([top (msortWorstCase(floor (/ n 2)))] [bottom (msortWorstCase (ceiling (/ n 2)))])
(append (map (lambda (x) (* x 2)) (list top)) (map (lambda (x) (- (* x 2) 1)) (list bottom))))]
)
)
Run Code Online (Sandbox Code Playgroud)
谁能告诉我我哪里出错了?
我收到以下错误:
*: contract violation
expected: number?
given: '(2 1)
argument position: 1st
other arguments...:
Run Code Online (Sandbox Code Playgroud)
您的递归正在制作列表列表的列表......使用(list top)和(list bottom)。
你应该在 Racket 中做与在 Python 中一样的事情;基本情况应该是一个单元素列表,并且您不应该在递归情况下将结果包装在列表中。
(define (msortWorstCase n)
(cond
[(equal? 1 n) '(1)]
[else (let* ([top (msortWorstCase(floor (/ n 2)))]
[bottom (msortWorstCase (ceiling (/ n 2)))])
(append (map (lambda (x) (* x 2)) top)
(map (lambda (x) (- (* x 2) 1)) bottom)))]))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
749 次 |
| 最近记录: |