0

There is a recursive selection sort in the upcoming question that has to be done.

def selsort(l):
    """
    sorts l in-place.
    PRE: l is a list.
    POST: l is a sorted list with the same elements; no return value.
    """                    

l1 = list("sloppy joe's hamburger place")
vl1 = l1

print l1    # should be: """['s', 'l', 'o', 'p', 'p', 'y', ' ', 'j', 'o', 'e', "'", 's', ' ', 'h', 'a', 'm', 'b', 'u', 'r', 'g', 'e', 'r', ' ', 'p', 'l', 'a', 'c', 'e']"""

ret = selsort(l1)

print l1    # should be """[' ', ' ', ' ', "'", 'a', 'a', 'b', 'c', 'e', 'e', 'e', 'g', 'h', 'j', 'l', 'l', 'm', 'o', 'o', 'p', 'p', 'p', 'r', 'r', 's', 's', 'u', 'y']"""
print vl1   # should be """[' ', ' ', ' ', "'", 'a', 'a', 'b', 'c', 'e', 'e', 'e', 'g', 'h', 'j', 'l', 'l', 'm', 'o', 'o', 'p', 'p', 'p', 'r', 'r', 's', 's', 'u', 'y']"""

print ret   # should be "None"

I know how to get this by using key → l.sort(key=str.lower). But the question wants me to extract the maximum element, instead of the minimum, only to .append(...) it on to a recursively sorted sublist.

If I could get any help I would greatly appreciate it.

4
  • Note you can format lines as code by indenting them four spaces. The "101\n010" button in the editor toolbar does this for you. You can edit your question with the edit link at the bottom of it and format your sample code now. Click the orange question mark in the editor toolbar for more information and tips on formatting. Commented Dec 3, 2010 at 2:55
  • 2
    You are most likely not allowed to use the built-in list.sort() method. Commented Dec 3, 2010 at 3:00
  • What do you mean "to extract the maximum element, instead of the minimum"? A reversed list? Commented Dec 3, 2010 at 3:03
  • I have to complete a recursive version of the selection sort algorithm. The difference is that I need to extract the maximum element, instead of the minimum, only to .append(...) it on to a recursively sorted sublist. Commented Dec 3, 2010 at 3:05

3 Answers 3

2

So. Do you understand the problem?

Let's look at what you were asked to do:

extract the maximum element, instead of the minimum, only to .append(...) it on to a recursively sorted sublist.

So, we do the following things:

1) Extract the maximum element. Do you understand what "extract" means here? Do you know how to find the maximum element?

2) Recursively sort the sublist. Here, "the sublist" consists of everything else after we extract the maximum element. Do you know how recursion works? You just call your sort function again with the sublist, relying on it to do the sorting. After all, the purpose of your function is to sort lists, so this is supposed to work, right? :)

3) .append() the maximum element onto the result of sorting the sublist. This should not require any explanation.

Of course, we need a base case for the recursion. When do we have a base case? When we can't follow the steps exactly as written. When does that happen? Well, why would it happen? Answer: we can't extract the maximum element if there are no elements, because then there is no maximum element to extract.

Thus, at the beginning of the function we check if we were passed an empty list. If we were, we just return an empty list, because sorting an empty list results in an empty list. (Do you see why?) Otherwise, we go through the other steps.

Sign up to request clarification or add additional context in comments.

Comments

0

the sort method should do what you want. If you want the reverse, just use list.reverse()

If your job is to make your own sort method, that can be done.

Maybe try something like this:

def sort(l):
    li=l[:]                                        #to make new copy
    newlist = []                                   #sorted list will be stored here
    while len(li) != 0:                            #while there is stuff to be sorted
        bestindex = -1                             #the index of the highest element
        bestchar = -1                              #the ord value of the highest character
        bestcharrep = -1                           #a string representation of the best character
        i = 0
        for v in li:
            if ord(v) < bestchar or bestchar == -1:#check if string is lower than old best
                bestindex = i                      #Update best records
                bestchar = ord(v)
                bestcharrep = v
            i += 1
        del li[bestindex]                          #delete retrieved element from list
        newlist.append(bestcharrep)                #add element to new list
    return newlist                                 #return the sorted list

Comments

0

You need to remove the current max from the list and then recurse with the now shorter list. Again remove the largest until the list is empty, percolate back out appending the items from smallest to largest to the growing list. If reverse is True we remove the smallest item so when the list is reassembled it is in reverse order.:

def selsort(l,reverse=False):
    """
    sorts l in-place.
    PRE: l is a list.
    POST: l is a sorted list with the same elements; no return value.
    """      
    if len(l) <= 1: return # One left  
    x = min(l) if reverse else max(l) 
    l.remove(x) # Remove largest or smallest for later
    selsort(l,reverse) # keep going until list is used up
    l.append(x) # put this back in order as we percolate

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.