list 计算一个数字在列表中出现的次数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9088062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:46:33  来源:igfitidea点击:

Count the number of occurrences of a number in a list

listprolog

提问by Ratzo

I'm writing a program in prolog that count the number of occurrences of a number in a list

我正在用 prolog 编写一个程序,它计算列表中某个数字的出现次数

count([],X,0).
count([X|T],X,Y):- count(T,X,Z), Y is 1+Z.
count([_|T],X,Z):- count(T,X,Z).

and this is the output

这是输出

?- 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.

it's count the same number several times

它多次计算相同的数字

Any help is appreciated

任何帮助表示赞赏

回答by sumx

Instead of the dummy variable _ just use another variable X1 and ensure it does not unify with X.

而不是虚拟变量 _ 只需使用另一个变量 X1 并确保它不与 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).

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

但是请注意,第二个参数 X 应该被实例化。因此,例如 count([2,23,3,45,23,44,-20],23,C) 会将 C 与 2 统一。如果您想要每个元素的计数,请使用

:- 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).

Then you get

然后你得到

 ?- 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

回答by Bj?rn Lindqvist

You can also use the includepredicate:

您还可以使用include谓词:

count(L, E, N) :-
    include(=(E), L, L2), length(L2, N).

回答by Andrei

ocr(X,[],0):- !.
ocr(X,[Element|Rs],V):- X = Element -> ocr(X,Rs,Ocr), V is 1+ Ocr; ocr(X,Rs,V).

I did it like that. That gives you only one answer and finishes.

我就是这样做的。那只给你一个答案并完成。