【问题标题】:Translating Python into Scheme/Racket将 Python 翻译成 Scheme/Racket
【发布时间】:2018-12-12 03:25:26
【问题描述】:

我目前正在尝试翻译这个 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)

进入球拍/方案代码,并遇到困难。

这是我目前所拥有的:

(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))))]
    )
  )

谁能告诉我哪里出了问题?

我收到以下错误:

*: contract violation
  expected: number?
  given: '(2 1)
  argument position: 1st
  other arguments...:

【问题讨论】:

    标签: python-2.7 scheme lisp racket


    【解决方案1】:

    您的递归正在使用(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)))]))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-07
      • 2017-10-12
      • 1970-01-01
      • 1970-01-01
      • 2018-02-25
      • 2012-10-24
      • 2020-08-11
      • 2020-03-12
      相关资源
      最近更新 更多