I've just started using python in my computer technology class. One thing I can't figure out is how to have python put the lists inside a string into alphabetical order. If anyone has any easy answer, it will be much appreciated. Also, my teacher told me he would give extra credit if I use bubblesort.

Recommended Answers

All 9 Replies

I don't understand your question entirely, but there is a Python snippet at:
http://www.daniweb.com/code/snippet452.html
that looks at various sorting algorithms, including the ever so slow bubblesort.

Sorry, I'll be more specific. Right now, we are practicing how to read the text from another file using python. The file we are reading is a list of several names. I've so far read the text in the file and put it into a for statement loop. I was wondering how to have python put the names into alphabetical order. That is the main objective, but more teacher told me he would be impressed if I could somehow use bubble sort for it.

Also, the list is only a small list of about 20 first names

Do you know about Python's built in sort? Try
print this_list.sort()
Bubble sorts are pretty straight forward btw.

ok, so straight forward that I can't get it. I'm only in a high school programming class. So, if possible, be as specific as possible because I'm not finding any answers on how to do bubble sort.

It's your extra credit, not mine. You'll have to come up with some code to start with or at least some ideas.

lol, what a waste of time then.

In terms of putting items into a list to be sorted, you want this:

f = open("mytextfile","r")
mylist = []
for line in f:
   mylist.append(f.readline())
f.close()

or even more concisely,

f = open("mytextfile","r")
lines = f.readlines()
f.close()

I agree with woooee, but he's not refusing help: you just have to make the first move by supplying a starting idea, algorithm, code, something.

Some possible starters:

1) Google for bubblesort so that you know how it goes.
2) Try to implement bubblesort with a list of 4 items and print things along the way.
3) Then try to implement it in your code.

That's the approach I take when I'm learning something new (my current project is wxPython).

If you get stuck, we like to help.

(FWIW, I think Insertion Sort is a better choice for lines that you read in one at a time ... but that probably won't get you extra credit.)

Jeff

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.