Given a list of URLs, the challenge is to sort the URLs in the list based on the top-level domain.
Top Level Domain (TLD) is one of the highest-level domains in the Internet’s hierarchical domain name system. Example — org, com, edu.
This is mainly used when we need to delete pages and sort the URL by top-level domain. It is widely used in open source projects and serves as a usable snippet.
Input: url = ["https://www.isb.edu", "www. google.com "," http://cyware.com "," https://www.gst.in "," https://www.coursera.org "," https://www.create.net " , "https://www.ontariocolleges.ca"] Output: [’https://www.ontariocolleges.ca’,’ www.google.com’, ’http:// cyware. com’, ’https://www.isb.edu’,’ https://www.gst.in’, ’https://www.create.net’,’ https://www.coursera.org’ ] Explanation: The Tld for the above list is in sorted order [’.ca’,’ .com’, ’.com’,’ .edu’, ’.in’,’ .net’ , ’.org’]
Here are some ways to accomplish the above task.
Method 1: using sorted
You can separate the input by and then use sorting to sort by TLD.
|
Initial list is: [’https://www.isb.edu’,’ www.google. com’, ’http:// cyware.com’,’ https://www.gst.in’, ’https://www.coursera.org’,’ https://www.create.net’, ’ https://www.ontariocolleges.ca’] Sorted list according to TLD is: [’https://www.ontariocolleges.ca’,’ www.google.com’, ’http: / / cyware.com’, ’https://www.isb.edu’,’ https://www.gst.in’, ’https://www.create.net’,’ https://www.coursera .org’]
Method 2: Using a lambda
The shortest and most readable way to sort URLs in a list based on top-level domain — this is using lambda.
|
Initial list is: [’https://www.isb.edu’, ’www.google.com’,’ http:// cyware.com’, ’https://www.gst.in’,’ https://www.coursera.org’, ’https://www.create .net’, ’https://www.ontariocolleges.ca’] Sorted list according to TLD is: [’ https://ww w.ontariocolleges.ca’, ’www.google.com’,’ http:// cyware.com’, ’https://www.isb.edu’,’ https://www.gst.in’, ’ https://www.create.net’, ’https://www.coursera.org’]
Method 3: use in reverse
Reverse input and breaking it up, then applying sorting to sort the URL by TLD
|
Initial list is: [’https://www.isb.edu’,’ www.google.com’ , ’http:// cyware.com’,’ https://www.gst.in’, ’https://www.coursera.org’,’ https://www.create.net’, ’https://www.ontariocolleges.ca’] Sorted list according to TLD is: [’https://www.ontariocolleges.ca’,’ www.google.com’, ’http:// cyware .com’, ’https://www.isb.edu’,’ https://www.gst.in’, ’https://www.create.net’,’ https://www.coursera.org ’]