计算列表中数字出现的次数 [英] Count the number of occurrences of a number in a list
本文介绍了计算列表中数字出现的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用序言编写一个程序,该程序计算列表中数字出现的次数
I'm writing a program in prolog that count the number of occurrences of a number in a list
count([],X,0).
count([X|T],X,Y):- count(T,X,Z), Y is 1+Z.
count([_|T],X,Z):- count(T,X,Z).
这是输出
?- count([2,23,3,45,23,44,-20],X,Y).
X = 2,
Y = 1 ;
X = 23,
Y = 2 ;
X = 23,
Y = 1 ;
X = 3,
Y = 1 ;
X = 45,
Y = 1 ;
X = 23,
Y = 1 ;
X = 44,
Y = 1 ;
X = -20,
Y = 1 ;
false.
它多次计数相同的数字
感谢您的帮助
推荐答案
代替虚拟变量_而是使用另一个变量X1并确保它不与X统一.
Instead of the dummy variable _ just use another variable X1 and ensure it does not unify with X.
count([],X,0).
count([X|T],X,Y):- count(T,X,Z), Y is 1+Z.
count([X1|T],X,Z):- X1\=X,count(T,X,Z).
但是请注意,第二个参数X应该被实例化.所以count([2,23,3,45,23,44,-20],23,C)将C与2统一.如果您希望每个元素使用的计数
However note that the second argument X is supposed to be instantiated. So e.g. count([2,23,3,45,23,44,-20],23,C) will unify C with 2. If you want the count for every element use
:- use_module(library(lists)).
count([],X,0).
count([X|T],X,Y):- count(T,X,Z), Y is 1+Z.
count([X1|T],X,Z):- X1\=X,count(T,X,Z).
countall(List,X,C) :-
sort(List,List1),
member(X,List1),
count(List,X,C).
那你得到
?- countall([2,23,3,45,23,44,-20],X,Y).
X = -20,
Y = 1 ? ;
X = 2,
Y = 1 ? ;
X = 3,
Y = 1 ? ;
X = 23,
Y = 2 ? ;
X = 44,
Y = 1 ? ;
X = 45,
Y = 1 ? ;
no
这篇关于计算列表中数字出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文