编写一个以奇数为参数(n)并显示打印奇数三角形的lisp函数三角形

时间:2019-10-24 16:06:45

标签: lisp common-lisp

Lisp编程 您将需要创建一个代码,该代码将遍历整数,并使用提供的整数创建一个三角形。同样,问题是“编写一个以奇数为参数(n)的lisp函数三角形,并显示一个打印的奇数三角形,如以下示例所示。如果输入为偶数,十进制或字符串,则应打印一个适当的消息”。对于十进制数字(我确实这样做)和偶数,它应该显示一个错误,但不能确定在我的代码中进行计算。

此代码可以工作并创建一个三角形,但仅对奇数不起作用。 例如: 1

1 3

1 3 5

1 3 5 7

1 3 5 7 9

我的代码输出(三角形3):

1

12

123

(defun triangle (n)
    (if (typep n'integer)
        (loop for i from 1 to n
              do (loop for j from 1 to i
                       do (write j)
                       )
              (write-line "")
        )
    (write-line "Decimal numbers are not valid input, Please enter an integer"))
    )
(triangle 3)

除了out之外,我只有奇数,并为小数和偶数给出错误。

2 个答案:

答案 0 :(得分:3)

提示:

  • 是否有一个谓词来告诉您数字是否为奇数(请查看下面的代码以获取线索)?
  • 您能算出如何使loop以非1的间隔进行计数吗,因为如果可以以2进行计数,则可以枚举奇数。

但是有时我只是无法拒绝一个您不能(也不应该)提交的答案:

(defun triangle (n)
  (assert (typep n '(and (integer 1)
                         (satisfies oddp)))
      (n) "~S is not a positive odd integer" n)
  ((lambda (c) (funcall c c n))
   (lambda (c m)
     (when (> m 1)
       (funcall c c (- m 2)))
     (format t "~{~D~^ ~}~%"
             ((lambda (c) (funcall c c m '()))
              (lambda (c i a)
                (if (< i 1)
                    a
                  (funcall c c (- i 2) (cons i a))))))
     m)))

答案 1 :(得分:0)

我不太确定我是否理解您的问题,但是这是一个解决方案,可以将1到N的奇数打印为三角形。您需要在循环中使用BY关键字作为数字之间的一步,然后一切正常。同样,您可以在执行任何其他操作之前使用ASSERT函数进行任何声明:

(defun triangle (N)
  ;; Use ASSERT for checking prerequisites before the opration starts
  ;; More on ASSERT here: http://clhs.lisp.se/Body/m_assert.htm
  (assert (and (integerp 8) (oddp N)) (N) "~A is not an odd integer" N)
  ;; You should add the steps to keep numbers odd with BY
  (loop for i from 1 to N by 2
     do (loop for j from 1 to i by 2
       do (princ j))
    (terpri))) 

现在这会打印您想要的内容:

(triangle 9)
; 1
; 13
; 135
; 1357
; 13579
;  => NIL

您还可以检查我对基本相同的问题的答案,这是递归解决的: Trying to print a triangle recursively in lisp