Python认为10小于9吗
def greedyAdvisor(subjects, maxWork, comparator):
'''subjects is a dictionary with keys classes and values of tuples of class value and class work. maxWork is the maximum work a student wants to put in. comparator is a function that takes two tuples of the aforementioned class value/class work variety and returns which one has a higher value. The function returns a dictionary with the most valuable classes to take within the given parameter of the willingness to work. I am supposed to use a greedy algorithem'''
greedy_dict = {}
highest_subjects = []
total_work = 0
while total_work < maxWork:
highest_value = 0, 0
highest_class = 0.0
for i in subjects:
if comparator (subjects[i], highest_value) and i not in highest_subjects and total_work + int(subjects[i][WORK]) <= maxWork:
highest_value = subjects[i]
highest_class = i
print highest_class, highest_value
highest_subjects.append(highest_class)
total_work += int(highest_value[WORK])
greedy_dict[highest_class] = highest_value
print greedy_dict
return greedy_dict
这里的数据,subjects 是一个字典,它把课程,比如 6.00、7.01 等,映射到一个元组上,元组里有两个值:一个是课程的分数,范围是 1 到 10;另一个是工作量,范围是 1 到 20,表示完成这个问题大概需要多少小时。最开始这些数据是在一个文本文件里,我把它转换成了字典,做得还不错。这个问题来自麻省理工学院的编程入门课程第八个问题,文本内容在一个叫 subjects.txt 的文件里。我希望这能解决你对数据的疑问。
我遇到的问题是,subjects 字典里的课程分数最大可以到 10,但 greedy_dictionary 却一直认为最大值是 9。参数里的比较器是一个函数,如果第一个元组的分数大于第二个元组的分数,它就返回 True
。
1 个回答
12
如果你是在比较字符串的话,那就是这样。
>>> '10' < '9'
True
先试着把它们转换成数字再说。