Python Forum

Full Version: has anyone implemented a sort command in Python?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
has anyone implemented a sort command in Python, even if it supports fewer features than the coreutils sort command?
Yes. I worked through Introduction to Algorithms (Cormen and others), and did all the code in Python.
(Dec-16-2018, 04:39 AM)ichabod801 Wrote: [ -> ]Yes. I worked through Introduction to Algorithms (Cormen and others), and did all the code in Python.
are you giving it away, anywhere?

i am looking to modify a sort command to sort by keys of IP addresses.
Example:

ip_list = ["192.168.2.108", "192.168.2.101", "192.168.2.155", "192.168.2.134"]

items = sorted(ip_list)
print(items)
print("\n".join(items))
Output:
['192.168.2.101', '192.168.2.108', '192.168.2.134', '192.168.2.155'] 192.168.2.101 192.168.2.108 192.168.2.134 192.168.2.155
(Dec-16-2018, 05:14 AM)Skaperen Wrote: [ -> ]are you giving it away, anywhere?

i am looking to modify a sort command to sort by keys of IP addresses.

That was years ago, I'd could maybe find it, but it would be a pain. But I don't think it would be a good idea. Python's sort uses Timsort, which is a more efficient combination of merge and insertion sort. But Timsort is not covered in Introduction to Algorithms, so anything I did would be less efficient regardless of implementation issues. But there are implementation issues, as my sorts were pure Python, and Python's sort is implemented in C, a much faster language.

I would expect that Python's sort with a proper key function would be faster than anything I had implemented.
>>> ip_list = ['192.168.2.168', '192.168.2.14', '192.168.2.105']
>>> sorted(ip_list)
['192.168.2.105', '192.168.2.14', '192.168.2.168']
>>> sorted(ip_list, key = lambda s: [int(x) for x in s.split('.')])
['192.168.2.14', '192.168.2.105', '192.168.2.168']
I see an issue here.
>>> ips = ['192.168.20.1', '192.168.125.43', '192.168.12.8']
>>> sorted(ips)
['192.168.12.8', '192.168.125.43', '192.168.20.1']
>>> 
Yes, that's what my code was intended to illustrate and fix.
that was my point, sorts for text are not going to sort IP addresses the way we expect, though i have seen so many cases of IP addresses sorted that way. i wrote such a sort in C ages ago, but it needs work like adding support for key positions other than column 1. i was thinking it might be easier to start over and do it in python. if you have IP addresses in a numeric form then you could somehow use sorted() to do it.
That's exactly what my code does (line 4): it converts the ip address to numeric, sorts based on that, and returns the strings.
Pages: 1 2