【问题标题】:Prolog Count Occurrences in 2 listsProlog 计数出现在 2 个列表中
【发布时间】:2017-12-05 21:31:47
【问题描述】:
  • 我想为每个元素比较 2 个列表。
  • 计算相等元素的数量。

我很近,请帮帮我:

%list vs list%
count2([],[],0).
count2([H1|T1],[H2|T2],S):-
    count(H1,[H2|T2],N),
    count2(T1,[H2|T2],M),
    S is N+M.

%1 element vs 1 list%
count(_, [], 0).
count(X, [X | T], N) :-
  !, count(X, T, N1),
  N is N1 + 1.
count(X, [_ | T], N) :-
  count(X, T, N).

A test:
1 ?- count2([2],[1,2,3],S).
false.

追踪:

2 ?- count2([2],[1,2,3],S).

   Redo: (5) read_history(h, '!h', [trace, end_of_file], '~! ?- ', _G154, _G155) ? creep
Correct to: "count2([2],[1,2,3],S)"? 
Please answer 'y' or 'n'? yes
   Call: (7) count2([2], [1, 2, 3], _G306) ? creep
   Call: (8) count(2, [1, 2, 3], _G631) ? creep
   Call: (9) count(2, [2, 3], _G631) ? creep
   Call: (10) count(2, [3], _G631) ? creep
   Call: (11) count(2, [], _G631) ? creep
   Exit: (11) count(2, [], 0) ? creep
   Exit: (10) count(2, [3], 0) ? creep
   Call: (10) _G632 is 0+1 ? creep
   Exit: (10) 1 is 0+1 ? creep
   Exit: (9) count(2, [2, 3], 1) ? creep
   Exit: (8) count(2, [1, 2, 3], 1) ? creep
   Call: (8) count2([], [1, 2, 3], _G637) ? creep
   Fail: (8) count2([], [1, 2, 3], _G637) ? creep
   Redo: (11) count(2, [], _G631) ? creep
   Fail: (11) count(2, [], _G631) ? creep
   Fail: (10) count(2, [3], _G631) ? creep
   Fail: (9) count(2, [2, 3], _G631) ? creep
   Fail: (8) count(2, [1, 2, 3], _G631) ? creep
   Fail: (7) count2([2], [1, 2, 3], _G306) ? creep
false.

(返回解决方案,但递归有问题)

请求的输出 #1:

?- count2([2],[1,2,3],S).
S = 1.

(2 是列表中的 1 次)。

请求的输出 #2:

?- count2([1,2],[1,2,3],S).
S = 2

(1 是列表中的 1 次)。 (2 是列表中的 1 次)。 总计 = 2 个相等的元素。

【问题讨论】:

  • 什么不起作用?请提供一个示例查询,其中包含您获得的输出和请求的输出...
  • 好的编辑,等一下
  • 关于列表的假设是什么?查询count2([1,2], [3,2,1], S). 会产生什么结果?
  • (1 是列表中的 1 次)。 (2 是列表中的 1 次)。总计 = 2 个相等的元素。

标签: list recursion count prolog


【解决方案1】:

答案:

count2([],[_|_],0).
count2([H1|T1],[H2|T2],S):-
    count(H1,[H2|T2],N),
    count2(T1,[H2|T2],M),
    S is N+M.


count(_, [], 0).
count(X, [X | T], N) :-
  !, count(X, T, N1),
  N is N1 + 1.
count(X, [_ | T], N) :-
  count(X, T, N).

Solved!

【讨论】:

  • 不需要[H2|T2]。你可以叫它L
【解决方案2】:

一个更简单的解决方案是递归主列表的元素并检查每个元素是否是测试列表的成员:

count(_, [], 0).
count(Xs, [H|T], C) :-
    (   member(H, Xs)
    ->  C #= C1 + 1
    ;   C1 = C
    ),
    count(Xs, T, C1).

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 2015-01-18
    • 1970-01-01
    • 2016-03-15
    相关资源
    最近更新 更多