哈希函数中的错误

时间:2018-03-13 10:20:03

标签: python hash

我遇到了这个功能的问题。我对哈希没有任何了解,但仍然收到有关它的错误。 我的函数的目的是给出活动数量最多的人的名字(活动是名为&#34的集合中的str; Groupes&#34 ;,该函数返回一个名称和数量的集合您可以看到成员名称在字典中给出" membres_nom"并且数字用于调用它们。  这是功能:

@account.assign_attributes({ :images => @images })

2 个答案:

答案 0 :(得分:1)

您正在尝试使用集合作为元素。在final_set = {temp_set,nb_maximal}行中。设置元素应该是可以清除的,但是设置不可清除。

您可以改为返回元组或列表:final_list = [temp_set, nb_maximal]。事实上,只是将return temp_set, nb_maximal隐含地构建一个元组。我认为是要走的路,更明确的返回类型,更干净等等。有关 hashability 的更多信息,有很多SO问题,例如:what-do-you-mean-by-hashable-in-python

顺便说一句,您似乎有一个错误,因为您的示例中的'Elfriede''Clovis'涉及4个活动,并且您的函数正在返回'Bachir'和{{1}这涉及2项活动。

这里有一个替代的函数实现:

'Amina'

使用def suractifs(names, group): # build a list of tuples with the name in the first coordinate and # the number of appearances in activities in the second coordinate act_list= [(n, len([a for a, s in group.iteritems() if i in s])) for i, n in names.iteritems()] # sort the list in decresing order of the activities act_list.sort(key=lambda t : -t[1]) # get one of the names with most activities a = act_list[0] # return only the filtered list of names that have the maximum #number of activities return set( t[0] for t in act_list if t[1] == a[1]), a[1] 作为Pitto建议的替代实现:

Counter

答案 1 :(得分:0)

我不确定我是否理解您的代码,所以我试图自己实施。

这是一种可行/简单/详细的解决方案。 一个更加pythonic的可能涉及使用Counter(https://pymotw.com/2/collections/counter.html

如果您需要任何详细信息,请提出问题。

# membres_nom:dict{int:str}
membres_nom = {'Dimitri':538,'Elfriede':802,'Bachir':147, \
               'Amina':125,'Clovis':153}

# groupes : dict[str:set[int]]
groupes = {'cinephiles':{802,125,147,153}, \
'travaux manuels':{125,802,153}, \
'cuisine':{153,147,802}, \
'sport':{153,538,802}}

def highest_activity_numbers(names, group):
    # Here I create a dictionary that will contain names / activity number
    activity_count_per_name = {}
    # Using iteritems we can access the key / value in a dictionary
    # In here I access category_name and user_ids from groupes
    for category_name, user_ids in groupes.iteritems():
        # Here I access user_name and user_id from membres_nom
        # I've clearly decided for the variables name that
        # made more sense to me but you can use anything you prefer
        for user_name, user_id in membres_nom.iteritems():
            # At this point, for example, at the 1st round of the loop I
            # access 'Dimitri' and I check if he is in the users of
            # 'cinephiles'
            if user_id in user_ids:
                # If 'Dimitri' is in the list I get his current activity
                # counter and add a unit to it
                ac = activity_count_per_name.get(user_name, 0)
                activity_count_per_name[user_name] = ac + 1
    # Time to return the loot :)
    return activity_count_per_name

print highest_activity_numbers(membres_nom,groupes)