我正在尝试通过testdome.com(https://www.testdome.com/d/python-interview-questions/9)的python测试
问题6要求您:
如果任何歌曲包含对播放列表中上一首歌曲的引用,则该播放列表被视为重复播放列表。否则,播放列表将以最后一首指向无的歌曲结尾。
实现一个is_repeating_playlist函数,该函数可以有效地根据使用的时间来重复播放列表,否则返回false。
例如,以下代码在两首歌曲指向彼此时打印“ True”。
first = Song("Hello")
second = Song("Eye of the tiger")
first.next_song(second);
second.next_song(first);
print(first.is_repeating_playlist())
我编写了以下代码,以检查歌曲的“下一首”是否指向一首更早的歌曲,并且此方法有效,但是测试表明我3/4部分都失败了。我希望有人可以解释原因:
class Song:
songs = []
repeats = []
def __init__(self, name):
self.name = name
self.songs.append(self.name)
self.next = None
def next_song(self, song):
self.next = song
try:
self.repeats.append(song.name)
except(AttributeError):
self.repeats.append("invalid song")
def is_repeating_playlist(self):
"""
:returns: (bool) True if the playlist is repeating, False if not.
"""
repeats = False
for i in Song.songs:
if repeats == True:
break
for j in Song.repeats:
if i == j:
print(i,j)
print(Song.repeats.index(j), Song.songs.index(i))
if Song.repeats.index(i) > Song.songs.index(j):
repeats = True
break
return repeats
first = Song("Hello")
second = Song("Eye of the tiger")
first.next_song(second);
second.next_song(first);
print(first.is_repeating_playlist())
代码按预期返回True,如果您输入诸如second.next_song(“ random nonsense);
但是显然我期望更多?
答案 0 :(得分:-1)
只用一套,看看是否见过两次
def is_repeating_playlist(self):
"""
:returns: (bool) True if the playlist is repeating, False if not.
"""
seen = set()
target = self
while 1:
if not target:
# end of list no cycles found
return False
if target in seen:
# this target has already appeared, so it repeats
return True
seen.add(target)
target = target.next
return None