Getting the third largest word in a string/list in python -


for code below can't seem 3rd largest word. splitting string user input , putting in "words" var, make 2 lists - 1 of includes words sorted in terms of length.

then length of longest word (in maxlist) , second longest word (in maxlist2) , remove them. that's left should third longest word original list , shorter words. find doesn't quite work right.

the second , third "for" statements below don't seem remove instances of wordlength represented "maxlist"

for example, if represent words letter "e" , use different numbers of e's different wordlength (ie. ee, eeee, eeeee) of these instances removed "for" statement , not. input: "e ee eee eeee eeee eeee eeee eeee eeee eeee eeee" should expect "eeee" words removed code:

 if len(word) == maxlist:             sort2.remove(word) 

if repeat code again next longest word (which done third "for" statement) should remove "eee" instance. not removed though, , final list remains "'e', 'ee', 'eee', 'eeee', 'eeee'"

the second "for" statement seems remove 6 instances of "eeee" not 8 instances. wrong here? please help!!

my final output should third longest word of original list + shorter words.

def thirdgreatest(strarr):      words = strarr.split()     sort=[] # length of words     sort2=[] # actual words     word in words:         sort2.append(word)         sort.append(len(word))         sort2.sort()      maxlist= len(max(sort2, key=len))      word in sort2:         if len(word) == maxlist:             sort2.remove(word)      maxlist2 = len(max(sort2, key=len))     word in sort2:         if len(word) == maxlist2:             sort2.remove(word)      maxlist3 = (max(sort2, key=len))      print      print "biggest word {} char long ".format(maxlist)      print sort     print "3rd biggest word {}: ".format(maxlist3)     print "3rd biggest word {}: ".format(sort2) # list of words remaining            #after first 2 longest have been removed   thirdgreatest(raw_input("enter string: "))  

you should use heapq finding third largest:

third_largest = heapq.nlargest(3, set(words))[-1] 

after that, can use sorts of stuff, e.g. list comprehension:

[word word in words if word != third_largest] 

Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -