如何将排名分配给Haskell中的元组列表(考虑到关系)?理想情况下,想要一个给出元组列表的函数,会返回一个带有排名的元组列表.
样本输入(假设基于每个元组的snd以升序排序):
results1 = [("a",12),("b",56),("c",61),("d",73),("e",75),("f",75),("g",81),("h",82),("i",91),("j",97)]
Run Code Online (Sandbox Code Playgroud)
样本输出:
[("a",1),("b",2),("c",3),("d",4),("e",5.5),("f",5.5),("g",7),("h",8),("i",9),("j",10)]
Run Code Online (Sandbox Code Playgroud)
注意"e"和"f"绑定,所以他们将他们的等级(5和6)加在一起并除以2.更一般地说,特定行列[i..j]的任何n个关系都将被接收sum [i..j]/n的相同等级.
注意:我今天刚刚开始学习Haskell(来自Python和Java),所以我更愿意提供有用的提示而不是揭示答案.足以让我找到合适的解决方案.谢谢!
编辑/第2部分问题:好的,所以感谢jamshidh,chunksof50,并且左右我想出了
sortStudents xs = sortBy (compare `on` snd) xs
prerankStudents xs = groupBy ((==) `on` (snd.fst)) (zip (sortStudents xs) [1..])
rankStudents xs = concat [ [if length ys > 1 then (a, fromIntegral (sum (map snd ys)) / fromIntegral (length ys)) else (a,fromIntegral c) | ((a,b),c) <- ys] | ys <- (prerankStudents . sortStudents) xs ]
Run Code Online (Sandbox Code Playgroud)
我对sortStudents和prerankStudents相对满意,但是rankStudents感觉有点像我正在再次编写python(list comprehension),虽然我不确定在这种情况下它是好还是坏.我尝试使用case..of递归地实现rankStudents,然而平滑的错误似乎超出了我的脑海.这是代码,如果有人要向我解释为什么它不起作用. …
怎么不能做到
fst . fst (("Bob",12),10)
Run Code Online (Sandbox Code Playgroud)
在哈斯克尔?
:t fst . fst
Prelude> ((c,b),b1) -> c
Run Code Online (Sandbox Code Playgroud)
这不会使(("Bob",12),10)成为fst的一个很好的候选人.fst,因为它
(([Char],Integer),Integer)
Run Code Online (Sandbox Code Playgroud) 我需要在python中模拟超几何分布(用于替换的采样元素的花哨字).
设置:有充满袋人口多的大理石.有两种类型的大理石,红色和绿色(在以下实施中,大理石表示为True和False).从袋子中拉出的弹珠数量是样品.
以下是我为此问题提出的两个实现,但是它们都在人口> 10 ^ 8时开始降级速度
def pull_marbles(sample, population=100):
assert population % 2 == 0
marbles = [x < population / 2 for x in range(0,population)]
chosen = []
for i in range(0,sample):
choice = random.randint(0, population - i - 1)
chosen.append(marbles[choice])
del marbles[choice]
return marbles
Run Code Online (Sandbox Code Playgroud)
此实现非常易读,并且可以清楚地跟踪问题的设置.但是,它必须创建一个大小人口列表,这似乎是瓶颈.
def pull_marbles2(sample, population=100):
assert population % 2 == 0
return random.sample([x < population / 2 for x in range(0, population)], sample)
Run Code Online (Sandbox Code Playgroud)
这个实现使用了random.sample函数,希望能加快速度.不幸的是,它没有解决生成长度人口列表的潜在瓶颈.
编辑:错误地,第一个代码示例返回大理石,这使得这个问题模糊不清.毫无疑问,我希望代码能够返回被"拉动"的红色大理石和绿色大理石的数量.很抱歉这个混乱 - …