from random import randint, shuffle
# create some tracks between 2-4 minutes for testing
tracks = { "Track {0}".format(i): "{0}:{1:02d}".format(randint(2, 3), randint(0, 59)) for i in range(20) }
print(tracks)
# covert to a list of elements with the time in seconds
def min_to_sec(x):
m, s = x.split(":")
return int(m) * 60 + int(s)
items = [ (k, min_to_sec(v)) for k, v in tracks.items() ]
# randomise
shuffle(items)
# a function that sums the lengths from an index position till
# it exceeds the max.
def select_tracks(items, index, max_seconds):
total = 0
selected = []
for name, length in items[index:]:
if total + length > max_seconds:
break
total += length
selected.append(name)
return total, selected
# run at each start position
results = [ select_tracks(items, i, 30*60) for i in range(len(items)) ]
# if we sort and select the last that is the best for this randomised order
results.sort()
playlist = results[-1]
print("\nPlaylist: {0} ({1} seconds)".format(", ".join(playlist[1]), playlist[0]))
有几种不同的方法可以做到这一点。有一个最佳的解决方案,让你尽可能接近你的目标,但你希望播放列表是随机的,一切最终得到播放,所以像这样的事情应该做的工作
输出:
相关问题 更多 >
编程相关推荐