As I have already mentioned, the following 2 months I will be dealing with algorithms! Thus, I have enlisted myself in a course for them and I will be spamming my site constantly with some useful (mainly for me) stuff for algorithms.
As far as all the books for algorithms start with a standard introduction for algorithms, I have decided to solve one of the introduction problems. With Python. The introduction problem was a simple insertion sorting, which I considered an interesting subject in Python.
So, what do we have? We have to sort a string, by its values in the ascii table. Pretty trivial, but until this moment I was not thinking how this is done. Without reading the whole ready solution, I managed to come up with something working, which was ok for me. As far as I am not using IDE for Python (it is too easy to program, if you use one), I am always printing a lot of stuff like an old-fashioned coder. So, I started to think a lot. And after about one hour of trial and error (including a coffee pause), I have come up with the solution of two embedded for-loops. Not fascinating, but it was working and it was what people call insertion sorting algorithm. Thus, this is how it looked like, with a lot of printing from my console:
Anyway, the code is really trivial and easy to understand, if you disregard the printing. It worths mentioning that in Python strings are immutable, that is why I have converted them to a list and then I printed it as a string. Another interesting thing in the code is the way to swap values in list in Python. Something like a,b = b,a which I found really nice.
Last but not least, here comes the code, enjoy it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
myWord = input("Enter a word:") myList = [] myList.extend(myWord) for z in range(0, len(myList)): print("Z is => {}, {}".format(z, myList[z])) for x in range(z, 0, -1): print("X is => {}, {}".format(x, myList[x])) if (x - 1) >= 0: if myList[x] < myList[x - 1]: myList[x], myList[x - 1] = myList[x - 1], myList[x] print("[x]{} [x-1]{}".format(myList[x], myList[x - 1])) print("".join(myList)) |
🙂