我正在努力优化下面的功能。
它将字符串值的列表作为输入“公牛”、“公牛”、“熊市”,并必须达成“多数共识”。输出str值“bull”。
我怎样才能提高速度?
consensus_type = "majority"
activeIndicators = ["bull","bull","bear"]
def consensus(
activeIndicators
):
counterBull = activeIndicators.count("bull")
counterBear = activeIndicators.count("bear")
counterNeutral = activeIndicators.count("neutral")
lists = [counterBull,counterBear,counterNeutral]
max_value_from_list = max(lists)
count_of_max_value_in_list = lists.count(max_value_from_list)
if consensus_type == "majority":
if count_of_max_value_in_list == 1:
d = {'bull':counterBull,'bear':counterBear,'neutral':counterNeutral}
consensus = max(d, key=d.get)
else:
consensus = "neutral"
elif consensus_type == "unanimity":
if max_value_from_list == len(activeIndicators):
d = {'bull':counterBull,'bear':counterBear,'neutral':counterNeutral}
consensus = max(d, key=d.get)
else:
consensus = "neutral"
return consensus编辑:下面的代码和原来版本一样简单,运行速度是原始版本的两倍。如果有人有其他建议,请插话。
def consensus(
activeIndicators
):
counterBull = activeIndicators.count("bull")
counterBear = activeIndicators.count("bear")
counterNeutral = len(activeIndicators) - counterBull - counterBear
consensus = "neutral"
if counterBull >= counterBear and counterBull >= counterNeutral:
if consensus_type == 'unanimity' and counterBull == len(activeIndicators):
consensus = "bull"
elif consensus_type == 'majority' and (counterBull != counterBear and counterBull != counterNeutral):
consensus = "bull"
elif counterBear >= counterBull and counterBear >= counterNeutral:
if consensus_type == 'unanimity' and counterBear == len(activeIndicators):
consensus = "bear"
elif consensus_type == 'majority' and (counterBear != counterBull and counterBear != counterNeutral):
consensus = "bear"
return consensus发布于 2022-08-31 07:31:13
如果您想加快计算速度,我建议尽可能少地使用函数和方法的调用(max,count)。您可以创建一个自己的函数,对列表中的所有元素进行计数,并返回一个可以直接用于计算协商一致类型的排名。
此外,将返回的值命名为与函数(consensus)相同的名称也不是一个好主意。
下面的代码将有效。我不知道它对很长的列表有多高的效率。
def ranking(l):
d={}
for e in l:
try:
d[e]+=1
except:
d[e]=1
order = []
for i in d.items():
order.append((i[1],i[0]))
return sorted(order,reverse=True)
def consensus(activeIndicators, consensus_type="majority"):
r = ranking(activeIndicators)
if consensus_type=="majority":
if len(r)==1:
cons = r[0][1]
elif r[0][0]>r[1][0]:
cons = r[0][1]
else:
cons = "neutral"
elif consensus_type=="unanimity":
if len(r)==1:
cons = r[0][1]
else:
cons = "neutral"
return conshttps://stackoverflow.com/questions/73550707
复制相似问题