2012-02-08 30 views
0
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 

數據,主題是一個字典,它將6.00,7.01等課程映射到值爲1-10的元組,其值爲類和工作負荷1-20一個問題應該花費很多時間。那麼它開始在一個文本文件,我把它變成一個字典,只是花花公子。問題從mit ocw介紹到編程問題8,文本位於名爲subjects.txt的文件中。我希望這解決了你對數據的擔憂。python是否認爲10小於9

我遇到的問題是主題字典的類值高達10,但greedy_dictionary始終認爲最大值爲9.參數中的比較函數返回True,如果第一個tuple[VALUE]大於第二個tuple[VALUE]

+1

請提供數據,以便人們可以運行它,如果他們想。 – 2012-02-08 02:40:48

回答

10

這是...如果你比較字符串。

>>> '10' < '9' 
True 

嘗試先將它們轉換爲數字。

+0

ohhh謝謝soo soo。一小時一小時。現在回到實際編碼的樂趣。謝謝!! – cah 2012-02-08 02:58:21