0

I know there is a sort function:

>>> a = 'bags'
>>> ''.join(sorted(a))
'abgs'

However, I need to write mine from scratch. I think I would like to use mergesort but I'm not sure how that would work for a string in Python. E.g., can I compare characters? Can I find the middle of a string somehow?

I'm using Python 3.4.

5
  • Strings are just immutable sequences; but make your string a list with a_list = list(a) and go from there instead. Commented Mar 22, 2014 at 20:54
  • Will I not be able to sort the string (e.g. with this method stackoverflow.com/questions/18761766/mergesort-python) if I keep is as a string? Should I do string-->list-->sort-->string? Commented Mar 22, 2014 at 21:01
  • That question doesn't modify the result in-place, you can just pass the string directly to that function. Like sorted(), it'll return a list though. Commented Mar 22, 2014 at 21:02
  • I need it to be a string, though, so that I could use it to initialize my object. I just need to use the .join function, correct? Commented Mar 22, 2014 at 21:08
  • Yes, a list of strings can be joined with ''.join(list_of_strings). Commented Mar 22, 2014 at 21:10

1 Answer 1

1

Yes you could compare characters.

b > a evaluates to True in Python, and so forth.

You could first convert the string to a list, and get it's middle via its length, do sequential comparison and then join the sorted list to get back a sorted string.

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

2 Comments

Perfect, I think that's all I need. I think I'll use something like this mergesort but for my string: stackoverflow.com/questions/18761766/mergesort-python
great..and you can also define the lists append outside the for loops for optimization. check:wiki.python.org/moin/PythonSpeed/PerformanceTips#Avoiding_dots...

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.