【问题标题】:Write a lisp function triangle that takes an odd number as the argument (n) and shows a triangle of printed odd numbers编写一个以奇数为参数 (n) 并显示打印奇数的三角形的 lisp 函数三角形
【发布时间】:2019-10-24 16:06:45
【问题描述】:

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)

i 除了 out 只有奇数,并给出十进制和偶数的错误。

【问题讨论】:

    标签: lisp common-lisp


    【解决方案1】:

    提示:

    • 是否有一个谓词可以告诉您一个数字是否为奇数(请查看下面的代码以获取线索)?
    • 您能否计算出如何让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)))
    

    【讨论】:

      【解决方案2】:

      我不太确定我是否理解您的问题,但这是一个将 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

      【讨论】:

        猜你喜欢
        • 2020-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多