python播放列表解决方案,如何完成is_repeating_playlist函数?

Ily*_*rov 3 python algorithm

class Song:
    def __init__(self, name):
        self.name = name
        self.next = None

    def next_song(self, song):
        self.next = song 

    def is_repeating_playlist(self):
        """
        :returns: (bool) True if the playlist is repeating, False if not.
        """
        return None

first = Song("Hello")
second = Song("Eye of the tiger")

first.next_song(second);
second.next_song(first);
Run Code Online (Sandbox Code Playgroud)

小智 5

class Song:
def __init__(self, name):
    self.name = name
    self.next = None

def next_song(self, song):
    self.next = song 

def is_repeating_playlist(self):
    """
    :returns: (bool) True if the playlist is repeating, False if not.
    """
    songs = set()
    next_song = self
    while next_song:
        if next_song.name in songs:
            return True
        else:
            songs.add(next_song.name)
            next_song = next_song.next or None

    return False

first = Song("Anam Nesis - Contemplare")
second = Song("Petre Inspirescu - Anima")
third = Song("VOLK - Cântul Ielelor")

first.next_song(second);
second.next_song(third);


print(first.is_repeating_playlist())
Run Code Online (Sandbox Code Playgroud)

请确保使用set()来提高速度。

函数“ is_repeating_playlist”的工作分为两个步骤:

  • 通过(下一首)歌曲进行迭代
  • 如果它在已添加的歌曲列表中找到下一首歌曲,则该列表正在重复


Sim*_*nas -1

您应该使用一个队列,其中最后一个元素链接到第一个元素。要实现此更新你的类self.previous

那么你的队列看起来像(为了清楚起见添加了第三个):

first = Song("Hello")
second = Song("Eye of the tiger")
third = Song("We are the champions")

first.next_song(second)
first.prev_song(third)

second.next_song(third)
second.prev_song(first)

third.next_song(first)
third.prev_song(second)
Run Code Online (Sandbox Code Playgroud)