【问题标题】:Pascal's Triangle in Racket球拍中的帕斯卡三角形
【发布时间】:2020-10-11 00:15:53
【问题描述】:

我正在尝试使用递归创建帕斯卡三角。我的代码是:

(define (pascal n)

(cond
 ( (= n 1)
   list '(1))
 (else (append (list (pascal (- n 1))) (list(add '1 (coresublist (last (pascal (- n 1))))))
)))) ;appends the list from pascal n-1 to the new generated list

(define (add s lst) ;adds 1 to the beginning and end of the list  
(append (list s) lst (list s))
)

(define (coresublist lst) ;adds the subsequent numbers, takes in n-1 list

  (cond ((= (length lst) 1) empty)
        (else 
       (cons (+ (first lst) (second lst)) (coresublist (cdr lst)))

  )))

当我尝试运行它时: (display(pascal 3)) 我收到一条错误消息:

长度:违反合同 预期:列表? 给定:1

我正在寻找帮助我修复此代码的人(不要为我编写执行 Pascal 三角形的全新代码)。提前致谢! pascal 3 的输出应该是: (1) (1 1) (1 2 1)

【问题讨论】:

  • 我使用(display (add '1 (coresublist (last '((1)(1 1)))))) 自己测试了较小的函数,得到了正确的输出。
  • “正在寻找帮助我修复此代码的人(不是为我编写全新的代码)”。但恐怕当前的代码需要大量重写。它有语法错误,而且算法一开始就不正确。好像没救了,反正你得从头开始。
  • 这能回答你的问题吗? Pascal's Triangle Row Sequence

标签: recursion racket pascals-triangle


【解决方案1】:

我们应该从帕斯卡三角形内的值的递归定义开始,它通常用两个参数(行和列)表示:

(define (pascal x y) 
  (if (or (zero? y) (= x y))
      1
      (+ (pascal (sub1 x) y)
         (pascal (sub1 x) (sub1 y)))))

有更有效的方法来实现它(请参阅Wikipedia),但它适用于小值。之后,我们只需要构建子列表。在 Racket 中,使用迭代很简单,但如果您愿意,可以使用显式递归来实现它:

(define (pascal-triangle n)
  (for/list ([x (in-range 0 n)])
    (for/list ([y (in-range 0 (add1 x))])
      (pascal x y))))

它会按预期工作:

(pascal-triangle 3)
=> '((1) (1 1) (1 2 1))

【讨论】:

    猜你喜欢
    • 2012-10-24
    • 1970-01-01
    • 2014-11-12
    • 2015-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多