1

In Python

s= "ABCC"
n = len(s)
sorted(set([s[a:b] for a in range(n) for b in range(a+1,n+2)])

gives me, alphabetically sorted sub strings with out repetitions

['A', 'AB', 'ABC', 'ABCC', 'B', 'BC', 'BCC', 'C', 'CC']

How can I further sort it by length of sub string.

['A', 'B', 'C', 'AB', 'BC', 'CC', 'ABC', 'BCC', 'ABCC']
1

2 Answers 2

3

simple,

sorted(set(s[a:b] for a in range(n) for b in range(a+1,n+1)),
       key=lambda x:(len(x),x))

This creates a key by which the comparison is done. First it compares the string lengths to determine the order. If the strings have the same length, the tie-breaker is the string contents.

Sign up to request clarification or add additional context in comments.

Comments

2

This is your solution:

s= "ABCC"
n = len(s)
sorted(sorted(set([s[a:b] for a in range(n) for b in range(a+1,n+2)])),key=len)

6 Comments

And how is that solution wrong? Did you run it yourself? Please run it in Python and tell me if it is wrong or not.
Python sorting is guaranteed to be stable, so there's nothing wrong about double sorted. Upvoted.
I missed the fact that you're using two sorted calls(ignore my last comment(deleted)), +1.
mgilson....Could you prove your point? I have tested this with this string also s= "NOPQRSTUVWXYZABCDEFGHIJKLM"
I am wondering why two times sorting is required, 'set' sorts the list alphabetically, then you sort the with sorted for len.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.