0

Here's a code for selection sort but it doesn't print the sorted list. How can I show it?

badlist = input("Enter list: ")  
def select(badlist):  
        l = list[:]  
        sorted = []  
        while len(l):  
            lowest == l[0]  
            for x in l:  
                if x < lowest:  
                    lowest = x  
            sorted.append(lowest)  
            l.remove(lowest)  
        return sorted  
select(badlist)  
4
  • there is no print statement in the code try print select(badlist) Commented Feb 4, 2013 at 11:34
  • 1
    I wonder what is happening here l = list[:]; don't name your variables the same as builtins. sorted = [] and then sorted.append(lowest) is just asking for trouble. Commented Feb 4, 2013 at 11:36
  • why not simply use the builtin sorted(list) and then you can just have your whole code be: print sorted(input("Enter list: ")) Commented Feb 4, 2013 at 11:36
  • 1
    As a side note, your implementation doesn't appear correct. Selection sort is an inplace algorithm, so you're supposed to use one single list for both sorted and unsorted parts (hint: swap min and current items instead of removing/appending). Commented Feb 4, 2013 at 11:47

3 Answers 3

2

if you type select(badlist) in Python shell is should show the result however if you're running your script as file you need to use print statement, as print select(badlist).

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

Comments

1

Expanding on my comment:

Why not simply use the builtin sorted(list) and then you can just have your whole code be:

print sorted(input("Enter list: "))

2 Comments

I'm sure this is an assignment or homework, and they aren't allowed to use built-ins.
@BurhanKhalid while that may be the case, it is not stated, and regardless, this answer is not ONLY for the OP, but an answer to anyone coming to StackOverflow looking for a solution to a problem similar to the OP and finding this page. It would be wrong not to include this as an answer.
0

Use print.

If you are using Python 2.x print is a keyword:

result = select(badlist)
print result

In Python 3.x print is a function and you must use parentheses:

result = select(badlist)
print(result)

You also have at least two other errors:

  • Your function parameter is called badlist but you never use it.
  • The == operator is equality comparison. You need = for assignment.

Also your algorithm will be very slow, requiring O(n2) operations.

1 Comment

It produces a TypeError: 'type' object has no attribute 'geitem' :(

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.