gpt4 book ai didi

list - Erlang - 来自两个列表的常见项目

转载 作者:行者123 更新时间:2023-12-02 15:07:48 25 4
gpt4 key购买 nike

这里是 Erlang 新手。假设我有两个这样的列表。

   L1= [{'Lady in the Water',2.5},
{'Snakes on a Plane',3.5},
{'Just My Luck',3.0},
{'Superman Returns',3.5},
{'You, Me and Dupree',2.5},
{'The Night Listener',3.0}]

L2 = [{'Lady in the Water',3.0},
{'Snakes on a Plane',3.5},
{'Just My Luck',1.5},
{'Superman Returns',5.0},
{'You, Me and Dupree',3.5}]

我想要像这样的元组列表中的常见评级

[{2.5,3.0},{3.5,3.5},{3.0,1.5},{3.5,5.0},{2.5,3.5}]

我的代码是这样的

common_rating(R1,R2)->common_rating(R1,R2,0,0).

common_rating(_X,[],M,N) ->{M,N};



common_rating(X,[Y|Y1],A,B)->
{M,R}=X,
{N,K }= Y,
case M=/=N of
true -> common_rating(X,Y1,A,B);
false -> common_rating(X,[],A+R,B+K)
end.

common_rating_final([],_R2,J) ->J;
common_rating_final([X|X1],R2,J)->
common_rating_final(X1,R2,J++[common_rating(X,R2)]).

为了更好的理解代码common_rating 函数需要一个 {movie,rating} 的元组,并从另一个列表 (B) 中找到相同的电影和评级并返回 {rating,rating_B}

现在 common_rating_final 递归遍历一个列表,比方说 A,并使用 common_rating 为 A 和 B 中常见的所有电影查找 {rating_A,rating_B}

但是当我运行我的代码时

my_module:common_rating_final(L1,L2,[]).

它返回我

[{2.5,3.0},{3.5,3.5},{3.0,1.5},{3.5,5.0},{2.5,3.5},{0,0}]

我可以过滤 {0,0} 部分,但我认为我的逻辑有缺陷,但无法编写只返回没有 {0,0} 部分的常见评级的代码。请协助。

最佳答案

长话短说

[{X2, Y2} || {X1, X2} <- L1, {Y1, Y2} <- L2, X1 =:= Y1].


也许这里的“裂缝”可以找到更好(更高效等)的解决方案,但这个可行。基本上它模式匹配(“解构”)L s 并比较元组的第一个元素,如果第一个元素恰好相等,则返回第二个元素。

整个东西/证明:

gorre@uplink:~$ erl
Erlang/OTP 19 [erts-8.3] [source] [64-bit] [smp:4:4] [async-threads:10] [kernel-poll:false]

Eshell V8.3 (abort with ^G)
1> L1= [{"Lady in the Water",2.5}, {"Snakes on a Plane",3.5}, {"Just My Luck",3.0}, {"Superman Returns",3.5}, {"You, Me and Dupree",2.5}, {"The Night Listener",3.0}].
[{"Lady in the Water",2.5},
{"Snakes on a Plane",3.5},
{"Just My Luck",3.0},
{"Superman Returns",3.5},
{"You, Me and Dupree",2.5},
{"The Night Listener",3.0}]
2> L2 = [{"Lady in the Water",3.0}, {"Snakes on a Plane",3.5}, {"Just My Luck",1.5}, {"Superman Returns",5.0}, {"You, Me and Dupree",3.5}].
[{"Lady in the Water",3.0},
{"Snakes on a Plane",3.5},
{"Just My Luck",1.5},
{"Superman Returns",5.0},
{"You, Me and Dupree",3.5}]
3> [{X2, Y2} || {X1, X2} <- L1, {Y1, Y2} <- L2, X1 =:= Y1].
[{2.5,3.0},{3.5,3.5},{3.0,1.5},{3.5,5.0},{2.5,3.5}]
4>

Notice that I changed the atoms into strings (it works the same way though).

关于list - Erlang - 来自两个列表的常见项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46133568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com