0

I have a python list as follows:

['a', 'c', 'ab', 'abc', 'bc', 'b']

I need the output as:

['a', 'ab', 'abc','b', 'bc', 'c']

To build the original list, my code is:

def  buildString( s):
    arr = []
    for i, c in enumerate(s):
        for j in range(i, len(s)):
            temp = ''
            for k in range(i, j+1):
                temp += s[k]
                arr.append(temp)
    x = set(arr)
    result = list(x)
    return result

print buildString('abc')

This program is to build complete subsequences of an input string in lexicographic order

Newtt
  • 6,050
  • 13
  • 68
  • 106

1 Answers1

1

Just sort it. Use sorted or list.sort.

In [126]: a = ['a', 'c', 'ab', 'abc', 'bc', 'b']
In [127]: sorted(a)
Out[127]: ['a', 'ab', 'abc', 'b', 'bc', 'c']

In [128]: a.sort()

In [129]: a
Out[129]: ['a', 'ab', 'abc', 'b', 'bc', 'c']

Go through for learn about sorting in python.

Vishnu Upadhyay
  • 5,043
  • 1
  • 13
  • 24