Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Stack Overflow: https://stackoverflow.com/questions/71285098/sort-strings-based-on-tail-component-of-word
- from collections import Counter
- text = "Headword,Headstand,Tailword,Middlelistword,Headlistword,Tailwording"
- words = text.split(',')
- # start with shortest word
- size = len(min(words, key=len))
- all_tuples = []
- for s in range(size, 1, -1):
- tails = [w[-s:] for w in words]
- tails_counts = Counter(tails)
- common_tails = [key for key, val in tails_counts.items() if val > 1]
- print('common:', common_tails)
- for c in common_tails:
- temp_words = []
- for w in words:
- if w.endswith(c):
- # remove to tuples
- all_tuples.append( (c, w) )
- else:
- # keep it
- temp_words.append(w)
- words = temp_words
- print('words: ', words)
- print('---')
- # add other words with tail which will be sorted to the end of list
- for w in words:
- all_tuples.append( (chr(65535), w) )
- print(all_tuples)
- print('---')
- # sorting and displaying
- for item in sorted(all_tuples):
- print(item[1])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement