如何计算Prolog中列表中的元素出现次数 [英] How to count number of element occurrences in a list in Prolog
问题描述
i m new in prolog that s为什么可能是这个问题很容易为你,但我couldnt找到答案。可以有人请帮助我。
i m new in prolog that s why may be the question is easy for you but i couldnt find the answer. Can someone please help me.
我只想要
一个计数函数st
count([c,c,a,a,b,b,d,a,c,b,d,d,a], O).
它将返回列表成员的发生次数。
it will returns the number of occurences of the list members.
O = [[a, 4], [b, 3], [c, 3], [d, 3]]
推荐答案
以下是基于我的上一个答案更改为删除列表中的重复项(Prolog) 和此前的回答问题 Prolog union for AUBUC 。
The following is based on my previous answer to "Remove duplicates in list (Prolog)" and on this previous answer to the question "Prolog union for A U B U C".
list_item_subtracted_count0_count / code>派生自
list_item_subtracted / 3
。
list_counts / 2
是从 list_setB / 2
派生的在此定义。
list_item_subtracted_count0_count([], _, [], N,N).
list_item_subtracted_count0_count([A|As], E, Bs1, N0,N) :-
if_(A = E,
( Bs1 = Bs , N1 is N0+1 ),
( Bs1 = [A|Bs], N1 = N0 )),
list_item_subtracted_count0_count(As, E, Bs, N1,N).
list_counts([], []).
list_counts([X|Xs], [X-N|Ys]) :-
list_item_subtracted_count0_count(Xs, X, Xs0, 1,N),
list_counts(Xs0, Ys).
以下是OP提供的查询:
Here's the query the OP gave:
?- list_counts([c,c,a,a,b,b,d,a,c,b,d,d,a], Xss).
Xss = [c-3,a-4,b-3,d-3]. % succeeds deterministically
注意对的顺序 XN
in Counts
对应于 Xs
X >:
Note the order of pairs X-N
in Counts
corresponds to the first occurrence of X
in Xs
:
?- list_counts([a,b,c,d], Xss).
Xss = [a-1,b-1,c-1,d-1].
?- list_counts([d,c,b,a], Xss).
Xss = [d-1,c-1,b-1,a-1].
最后,让我们考虑所有可能的列表 Es
— :
Last, let's consider all possible lists Es
—enumerated fairly with ascending lengths:
?- length(Es, N), list_counts(Es, Xss).
N = 0, Es = [], Xss = []
; N = 1, Es = [A], Xss = [A-1]
; N = 2, Es = [A,A], Xss = [A-2]
; N = 2, Es = [A,B], Xss = [A-1,B-1], dif(B,A)
; N = 3, Es = [A,A,A], Xss = [A-3]
; N = 3, Es = [A,A,B], Xss = [A-2,B-1], dif(B,A)
; N = 3, Es = [A,B,A], Xss = [A-2,B-1], dif(B,A)
; N = 3, Es = [B,A,A], Xss = [B-1,A-2], dif(A,B), dif(A,B)
; N = 3, Es = [A,B,C], Xss = [A-1,B-1,C-1], dif(C,A), dif(C,B), dif(B,A)
...
这篇关于如何计算Prolog中列表中的元素出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!