我有一个喜欢的电影列表,我想根据我的口味从最好的电影(有最多的点数)到最差的电影(只有1点)进行排序。在列表中确定位置的正确实施
比方说,该列表包含已排序的300部电影,并且您想确定新电影的分数。您可以将新电影与排序列表中的每部电影进行比较,也可以利用列表排序的知识。
我试图将它作为二进制搜索来实现,因此每个插入(新电影)都具有对数复杂性。 二进制搜索实现很容易对我来说:
def binSearch(lst, number):
left = 0
right = len(lst) - 1
while left <= right:
middle = left + ((right - left)/2)
if number == lst[middle]:
return True
else:
if number < lst[middle]:
right = middle - 1
else:
left = middle + 1
return False
但要确定点是相当困难的我。我已经调试了几个小时,但仍然出现了一些错误。我多次改变了实现,但没有任何帮助。 这是我最后的解决方案(也许该算法是在最坏的状态,那么它是在开头)
def determinePoints(lst, new):
# lst is a list of tuples with movies
# new is a tuple with new movie (has no point associated yet)
if not lst: # no movie has points so far
return 1 # now exists only one movie with associated points
newTitle = new[0]
newGenre = new[1]
atMost = len(lst)
atLeast = 0
while atLeast < atMost - 1: # algorithm doesn't work
# if only two movies have associated points
center = twoPointsCenter(atLeast, atMost)
(title, genre) = lst[center]
os.system("clear")
competitionStrings = [ newTitle, newGenre, "\n" * 10, title, genre ]
print "\n".join([ x.center(150) for x in competitionStrings ])
c = getch()
if c == "j": # new movie is worse than this
atMost = center - 1
if atMost <= 1:
return 1
else: # new movie is better than this
atLeast = center + 1
if atLeast >= len(lst):
return max(atLeast, 1)
return max(twoPointsCenter(atLeast, atMost), 1)
def twoPointsCenter(left, right):
return left + ((right - left)/2)
你能纠正我的解决方案(或更好的实现它)转变和正确的结果结束?
它应该从0,1,2,等等的长度开始工作。它不应该返回小于1的值。在电影列表中不应该有两个具有相同数量的电影点。
当函数determinePoints
返回点时,我将更新此影片的数据库,并且每个影片的点数大于此新影片的增量点数1。
谢谢
为什么不使用Python二进制搜索的“bisect”模块? – Amber 2012-03-04 18:36:06
@Amber二进制搜索仅用于更好地理解问题。问题在于'determinPoints',你可以随意使用任何你想要的解决方案。 – xralf 2012-03-04 18:38:51
为什么不添加一个电影之后,并给当前电影的当前点? – 2012-03-04 18:43:11