Python问题w /代码

时间:2016-11-15 18:51:26

标签: python

我想请求python的一些帮助,因为我是新的,我试图学习它。 编写以下函数。

empty_list()返回一个空的“歌曲列表”。这不一定是Python语义中的列表:函数可以返回列表,元组,字典,字符串,None ......如果您认为这是一个好主意,甚至可以返回一个数字。 (提示:不是。:)返回一些对以下函数有用的东西。

播放(a_list,song)以某种方式将给定的歌曲(字符串)添加到列表中。它是如何做的取决于你的列表是什么(列表,字典......)。

song_plays(a_list,song)返回播放歌曲的次数。

说我们这样做:

new_list = empty_list() 玩(new_list,“昨天”) 玩(new_list,“明天”) 玩(new_list,“昨天”) 玩(new_list,“昨天”)

此后,呼叫song_plays(new_list,“Yesterday”)返回3,呼叫song_plays(new_list,“明天”)返回1,并且呼叫song_plays(new_list,“今天”)返回0.

第一部分已经完成,但现在我需要编写另外4个函数,我不知道从哪里开始。

在以下函数中,我们假设我们有两个列表。

  1. number_of_common(list1,list2)返回两个列表中显示的歌曲数量。

  2. repertoire_size(list1,list2)返回一个(甚至两个)列表中显示的歌曲数量。

  3. 相似度(list1,list2)返回计算为上述两个数的商的相似度。如果两个列表都为空,则相似性为0.

  4. 编写一个函数rang(a_list,n),它返回n个播放次数最多的歌曲列表。如果两首歌曲共享相同数量的播放,请按字母顺序排序。如果列表包含少于n首歌曲,则返回的列表将被缩短(但仍然有序)。

  5. 这就是我现在所拥有的:

        def empty_list():
        list = {}
        return list
    
    def play(list, song):
        if song in list:
            list[song] += 1
        else:
            list[song] = 1
    
    def song_plays(list, song):
        if song not in list:
            return 0
        else:
            return list[song]
    
    def total_songs(list):
        return len(list)
    
    def total_plays(list):
        totalplays = 0
        for name in list:
            a = list[name]
            totalplays += a
        return totalplays
    
    def favourite(list):
        if list == {}:
            return None
        else:
            max_name = ''
            max_a = 0
            for name in list:
                a = list[name]
                if max_a < a:
                    max_a = a
                    max_name = name
            return max_name
    
    def number_of_common(list1,list2):
    
    def repertoire_size(list1,list2):
    
    def similarity(list1,list2):
    
    def rang(list,n):
    

2 个答案:

答案 0 :(得分:1)

对于列表数据类型,我推荐Counter,然后一切都变得非常紧凑:

from collections import Counter as empty_list

def play(a_list, song):
    a_list[song] += 1

def song_plays(a_list, song):
    return a_list[song]

def number_of_common(list1, list2):
    return len(set(list1) & set(list2))

def repertoire_size(list1, list2):
    return len(list1 + list2)

def similarity(list1, list2):
    try:
        return number_of_common(list1, list2) / repertoire_size(list1, list2)
    except ZeroDivisionError:
        return 0

def rang(a_list, n):
    ranks = sorted(a_list.most_common(n), key = lambda x: (-x[1],x[0]))
    return [song for song, times in ranks]

答案 1 :(得分:0)

对于前三个功能,请查看set数据类型。设置并集,交集和长度可以快速解决这些问题。例如:

set1 = set(list1)
set2 = set(list2)
either = set1.union(set2)
both   = set1.intersection(set2)
full_count = len(either)
both_count = len(both)
similarity = float(both_count) / full_count

请注意,在单个函数中,您可以轻松地将计算减少到单行,例如

both_count = len(set(list1).intersection(set(list2)))

按播放频率排序

您应该可以通过this sorting tutorial找到支持代码。该清单是您的主要清单;播放频率是排序键。