user2498110
user2498110

Reputation: 105

Python 2 - Trying to reduce string by eliminating identical letters

Let's say given string is "aabcc". After this input is run thru my function, it should be reduced to "b", because aa and cc get eliminated. If given string is "aaabbccc", this would be reduced to "ac".

So here is my code

def super_reduced_string(s):
    for i in range(len(s)-1):
        if s[i] == s[i+1]:
            s = s.replace(s[i],'')
    return s

It keeps throwing string index out of range error whenever I attempt to update string s each iteration s = s.replace(s[i],''). This also happens when I assign s to placeholder at the beginning.

Error

Traceback (most recent call last):
  File "solution.py", line 12, in <module>
    result = super_reduced_string(s)
  File "solution.py", line 7, in super_reduced_string
    if s[i] == s[i+1]:
IndexError: string index out of range

Would appreciate an explanation and a fix.

Cheers

Upvotes: 0

Views: 58

Answers (1)

jyallop
jyallop

Reputation: 31

The first big issue is that s.replace(s[i], '') will replace every instance of s[i] in the string with ''.Using either s = s.replace(s[i], '', 2) or s = s[:i] + s[i + 2:] which will remove the identicals. Also fredtantini is right you still go to 5 even after shortening your string and that's why using a for loop is dangerous in this case. It is safer if you want to iterate through a string and remove elements to use a while loop.

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

Upvotes: 1

Related Questions