计算一个数字在列表中出现的次数 [英] Count the number of occurrences of a number in a list

查看:19
本文介绍了计算一个数字在列表中出现的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆