Home > Software engineering >  Can anyone recognize the pattern through which this list is sorted and recommend an algorithm for th
Can anyone recognize the pattern through which this list is sorted and recommend an algorithm for th

Time:06-21

I have a list like this :

my_list = ['A','AC','F','AB','ADF','D','DF','C','B]

I want to find an algorithm to sort the list as this :

sorted_list = ['A','C','AC','B','AB','F','D','DF','ADF']

I wonder if anyone who is able to recognize the pattern could recommend me a recognized algorithm to solve this kind of problem. Thank you.

CodePudding user response:

The only rule I can see is that a single letter has to appear first before it can appear in a longer string.

If all the string are nodes and each single letter has a (directed) edge from it to all the strings that contain it then you end up with topological sort. But then there would be a lot of other solutions. E.g. A, B, C, D, F, AB, AC, ADF, DF would be valid too.

CodePudding user response:

I had noticed another pattern here,

step1: look from left to right and spot the first string that has more than one letter

step 2: put all possible combinations that had appeared in the first list of the found string (from step 1) and than the string itself.

step 3: redo step 1 for the next more than two latter string and insert only combination that had not appeared yet.

this is only based on one example so I cant be sure that this is the correct pattern but it works for this example.

  • Related