python-3.xlongest-substring

Trying to get the longest decreasing substring from a given string, keeping the case sensitivity in mind


I have been trying to get below result out of this Program but for some reason it is not giving the required output.

Required Results:

Input1 : bbaasssrppoccbaaacbaba Output1 : ['bbaa','sssrppoccbaaa','cba','ba'] Input2: hjgAvjhjKLhbfvbZSF Output2 :['h', 'jgA', 'vjh', 'jK', 'L', 'hb', 'f','vbZSF']

What i am getting

Output: ['bbaa', 'sssrppoccbaaa', 'cba'] & Output: ['h', 'jgA', 'vjh', 'jK', 'L', 'hb', 'f'] from below code which is not getting last substring "ba" & "vbZSF".

s1 = 'bbaasssrppoccbaaacbaba'
# s1 = 'hjgAvjhjKLhbfvbZSF'


decSub = ''
listSub = []
i= 0

while i < len(s1):
    current = s1[i]
    previous = s1[i] if i == 0 else s1[i-1]
    if ord(current) <= ord(previous):
        decSub += current
    else:
        listSub.append(decSub)

        decSub = ''
        decSub += current
    i +=1
print(listSub)

It would be great if somebody could suggest a fix or a better way to achieve this result.Thanks in advance


Solution

  • You just need to append the missing decSub in the list.

    Updated Code:

    s1 = 'bbaasssrppoccbaaacbaba'
    # s1 = 'hjgAvjhjKLhbfvbZSF'
    
    
    decSub = ''
    listSub = []
    i= 0
    
    while i < len(s1):
        current = s1[i]
        previous = s1[i] if i == 0 else s1[i-1]
        if ord(current) <= ord(previous):
            decSub += current
        else:
            listSub.append(decSub)
            decSub = ''
            decSub += current
    
        i += 1
    
    listSub.append(decSub)
    
    print(listSub)
    

    Output:

    # s1 = 'bbaasssrppoccbaaacbaba'
    ['bbaa', 'sssrppoccbaaa', 'cba', 'ba']
    
    # s1 = 'hjgAvjhjKLhbfvbZSF'
    ['h', 'jgA', 'vjh', 'jK', 'L', 'hb', 'f', 'vbZSF']