print the smallest lexicographically possible string that can be obtained by removing at most 1 character from the string

Asked

Viewed 110 times

-3

I will receive an integer number and a string``; I will have q print the smallest lexicographically possible string that can be obtained by removing at most 1 character from the string.

I found some ancient code, only it didn’t come close to the result I desire, for example:

y=input()
i=n=l=len(y)
while i:
    if (y[:i]*l)[:l]==y:n=i
        i-=1
        x=y[:n];y=x*2
while i<n:
    x=min(x,y[i:i+n])
    i+=1
print(x)

For example: I get number 26 and string: lolthisiscoolfreehackforya, and the answer would be: llthisiscoolfreehackforya

  • I do not understand why you have to give the number (in case 26). From what I understand of the problem I think it is enough to check: 1) if the first character is lexicographically larger than the second character then remove the first character ("baaa" becomes "aaa"); 2) if the first character is less than or equal to the second character then look, from the second character, a character that is lexicographically").

  • that’s right, but I have no idea how to do it in code

  • there’s definitely another way to do it, but you can do it with two loop for, traversing each character of the string and comparing it with the next, when the comparison is true you use a break to finish.

  • have any idea what that code would look like ?

1 answer

0

I think that’s about what you’re looking for.

>>> a = 'lolthisiscoolfreehackforya'
>>> n = 0
>>> while ord(a[n+1]) < ord(a[n]) and n < len(a) - 1:
...     n += 1
...
>>> a[:n+1] + a[n+2:]
'llthisiscoolfreehackforya'
>>>

NOTE The line a[:n+1] + a[n+2:] can give error if n is minor 1 or 2 that the string size. You have to make a if...

I hope I’ve helped

Browser other questions tagged

You are not signed in. Login or sign up in order to post.