如何在序言中找到列表的模式? [英] How to find the mode of a list in prolog?

查看:64
本文介绍了如何在序言中找到列表的模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我如何在Prolog中找到列表的模式吗?

Can someone please tell me how to find the mode of a list in Prolog?

我已经尝试过了:

count_elt([], _, 0) :- !. 
count_elt([H|T], H, P) :- 
  count_elt(T, H, P1),
  P is P1 + 1, !. 
count_elt([_|T], E, P) :- count_elt(T, E, P). 

listMode([], 0) :- !. 
listMode([_], 1) :- !. 
listMode([H1|[H2|T]], M) :- 
  count_elt([H1|[H2|T]], H1, C),
  listMode([H2|T], C1),
  C > C1,
  M is C, !. 
listMode([_|[H2|T]], M) :- listMode([H2|T], M).

仅返回列表中出现的最大次数.但是我需要返回出现次数最多的元素(列表中最频繁的值).

which only returns the maximum occurrences in the list. But I need to return the element which has the maximum occurrence (The most frequent value in the list).

推荐答案

希望您已经获得了很多建议.这是适合您的工作代码.

Hope you already got number of suggestions. Here this is working code for you.

count_elt([],_,0):-!.
count_elt([H|T],H,C):-count_elt(T,H,C1),C is C1+1,!.
count_elt([_|T],E,C):-count_elt(T,E,C).

listMode([],0) :- !.
listMode([_],1) :- !.
listMode([H1|[H2|T]], M) :-count_elt([H1|[H2|T]],H1,C),listMode([H2|T],C1),C > C1,M is C,!.
listMode([_|[H2|T]],M) :- listMode([H2|T],M).

get_mode([H|T],M):-listMode([H|T],K),count_elt([H|T],M,K).

这篇关于如何在序言中找到列表的模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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