这是来自Learn Prolog Now的练习3.5 .他们在解释列表之前把它放在一边所以我需要一个不涉及列表的过程.
任务是交换嵌套二叉树的叶子.如果查询是
swap(tree(tree(leaf(1), leaf(2)), leaf(4)), T).
Run Code Online (Sandbox Code Playgroud)
答案应该是
T = (tree(leaf(4), tree(leaf(2), leaf(1))).
Run Code Online (Sandbox Code Playgroud)
同
swap((X, Y), (Y, X)).
swap(tree(X, Y), T) :-
swap((X, Y), (Y, X)),
T = (Y, X).
Run Code Online (Sandbox Code Playgroud)
我明白了
T = (leaf(4), tree(leaf(1), leaf(2))).
Run Code Online (Sandbox Code Playgroud)
如你所见leaf(1),leaf(2)并没有得到交换.我想要一些提示甚至你的程序,它应该适用于任何深度的节点.谢谢.
我在这里读了一些关于print()括号的答案.无论如何我放了它们并得到语法错误.你能说出原因吗?
Python 3.3.2+ (default, Feb 28 2014, 00:52:16)
[GCC 4.8.1] on linux
>>> answer = "no"
>>> while answer == "no":
... answer = input("Are we there? ")
... print("We're there!")
File "<stdin>", line 3
print("We're there!")
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
是的,我可以看到...提示将打印线保持在while循环下.如果我按2次Enter,则从输入中打印字符串.
>>> answer = "no"
>>> while answer == "no":
... answer = input("Are we there? ")
...
Are we there?
Run Code Online (Sandbox Code Playgroud)