Home > Back-end >  index out of range in same making loop
index out of range in same making loop

Time:11-12

I'm trying to understand my little exercise. I tested with the same input but in two different coding ways. One of them ran well, the other one got string index out of range.Input: abBAcC I got this problem:

Traceback (most recent call last):
  File "d:\python_courses\leetcode_make_string_great\make_string_great.py", line 17, in <module>
    print(checkObj.makeGood(stringCheck))
  File "d:\python_courses\leetcode_make_string_great\make_string_great.py", line 6, in makeGood
    if ord(s[index]) == ord(s[index   1])   32 or ord(s[index]) == ord(s[index   1]) - 32:
IndexError: string index out of range

This one is geting an error:

class Solution:
    def makeGood(self, s: str) -> str:
        while len(s) > 1:
            find = False
            for index in range(len(s) - 1):
                if ord(s[index]) == ord(s[index   1])   32 or ord(s[index]) == ord(s[index   1]) - 32:
                    s = s.replace(s[index: index   2], '')
                    find = True
            
            if not find:
                break

        return s

So I found another way. It runs well but I've not seen any difference between them.

class Solution:
    def makeGood(self, s: str) -> str:
        # if s has less than 2 characters, we just return itself.
        while len(s) > 1:
            # 'find' records if we find any pair to remove.
            find = False
            # Check every two adjacent characters, curr_char and next_char.
            for i in range(len(s) - 1):
                curr_char, next_char = s[i], s[i   1]
                # If they make a pair, remove them from 's' and let 'find = True'.
                if abs(ord(curr_char) - ord(next_char)) == 32:
                    s = s[:i]   s[i   2:]
                    find = True
                    break
            # If we cannot find any pair to remove, break the loop. 
            if not find:
                break
        return s

Is there anyone can point why I get this error? Thank you very much.

CodePudding user response:

Try to imagine how your first code works: in your example at each iteration index will take values from 0 to len(s)-1, i.e. 5.

But when index is 1 you find 'bB' and s becomes 'aAcC'. When index is 2 you find 'cC' and s is now only 'aA'. Now index becomes 3 and you get the error.

  • Related