0

I have the following file How do I sort based on number of "/" I find in each line

a/b/c/d/e/f a/k/l a/m/m/p b/h/s/i/l/m b/h b/e/f/g/p/l/i a/p/t a/k/s b/p/t b/k/s

The lines sorted as follows.

b/e/f/g/p/l/i a/b/c/d/e/f b/h/s/i/l/m a/m/m/p a/k/l a/p/t a/k/s b/p/t b/k/s b/h

What is the best way to achieve this?

Thanks, Ravi

  • Calculate the number of "/" in each string and add it in Sorted Hashmap with key as number of "/" and value as list of String. Once you do this for all strings then take each key in hashmap and print the list – user3653796 Jul 30 '15 at 00:03

1 Answers1

0

One approach is to read a line at a time and count how many '/' are in that line. Then insert an element into a hashmap where the key is the id of the line (could be sequential (1 to N)) and then sort by the hashmap by value. If you're using Python, this would look like this. Iterating through the keys in order will give you the index of the corresponding line.

Example in Python that prints out lines in sorted order:

import operator
def sort_by_char(lines, ch):
    """ Given a list of strings and a character, print out the lines sorted by how many characters (ch) it contains """
    hashmap = {}
    for idx in range(len(lines)):
        line = lines[idx]
        count = line.count(ch)
        hashmap[idx] = count

    sorted_lines = sorted(hashmap.items(), key=operator.itemgetter(1))

    for i in range(len(lines)):
        print lines[sorted_lines[i][0]]

Alternatively, you could use the count as the key and the line as the value.

Community
  • 1
  • 1
pushkin
  • 9,575
  • 15
  • 51
  • 95