-1
import sys

def super_reduced_string(s):   
    i=len(s)-1  
    while(i>0):  
        if(s[i]==s[i-1]):
            s=s.replace(s[i],'')
            s=s.replace(s[i-1],'')
            i=len(s)-1
        else:
            i-=1
    return (s)

For example, if I take a string "aaabccddd" so the value of i is 8 at the start. My if statement is true so the string becomes 'aaabccdd'.

After then I want to remove s[i-1] (s[7]) then your string should become "aaabccd"

Why does it raise an IndexError exception, saying that s[i-1] out of range?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

1 Answers1

2

You are removing multiple characters. str.replace() finds all occurrences of the given string and replaces them. s[8] is 'd', so you removed all 'd' characters from your string:

>>> s = 'aaabccddd'
>>> i = len(s) - 1
>>> i
8
>>> s.replace(s[i], '')
'aaabcc'

Now s is only 6 characters long, so s[i-1] is s[7] is out of range.

If you wanted to remove just one character from your string, don't use str.replace(); you'd have to use slicing:

s = s[:i - 1] + s[i + 1:]  # remove the doubled character found

Slicing always succeeds, it'll never throw an IndexError, but can result in an empty string.

Working code (with some PEP-8 whitespace thrown in):

def super_reduced_string(s):   
    i = len(s) - 1 
    while i:  
        if s[i] == s[i-1]:
            s = s[:i - 1] + s[i + 1:]
            i = len(s) - 1
        else:
            i -= 1
    return s

This produces:

>>> super_reduced_string('aaabccddd')
'abd'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343