Home > Software engineering >  How to remove the IndexError: string index out of range while traversing through a dictionary in Pyt
How to remove the IndexError: string index out of range while traversing through a dictionary in Pyt

Time:01-13

I am trying to create a new word while comparing characters of two strings which have following criterions.

There are two strings S and T of equal lengths

  1. If character at S is equal to character at T then 'B' will be added in a new empty string called 'wordle'
  1. If the characters at S and T are different then 'G' will be added to the wordle. For example s= ABCDE and T = EDCBA will give wordle =BBGBB as output. Below is my code.
class Solution(object):


    def guess_game(self, s1, s2):
        dt = dict()
        wordle = ''
        if len(s1) == len(s2):
    
            for i in range(len(s1)):
                dt = {s1[i]: s2[i]}
    
            if dt.keys() == dt.values():
                wordle[i]  = 'G'
            else:
                wordle[i]  = 'B'
    
            return wordle
        else:
            print("The strings should be equal length")


if __name__ == "__main__":
    s1 = 'ABCDE'
    s2 = 'EDCBA'
    print(Solution().guess_game(s1, s2))

I am getting following error.

 wordle[i]  = 'B'
 IndexError: string index out of range

CodePudding user response:

The IndexError occurs because for example, in the first iteration (i=0) you are trying to access wordle[0], but wordle is an empty string so it doesn't have an element at 0.

All you are trying to do is append a letter to the string, so you just need to write:

wordle = wordle   'G'

(or B in the else part)

I also really can't understand why you would create a dictionary and then compare keys with values, when you could just see if s1[i]==s2[i] directly.

Try the following:

class Solution(object):

    def guess_game(self, s1, s2):
        wordle = ''
        if len(s1) == len(s2):
            for i in range(len(s1)):
                if s1[i] == s2[i]:
                    wordle = wordle   'G'
                else:
                    wordle = wordle   'B'
            return wordle   
        else:
            print("The strings should be equal length")


if __name__ == "__main__":
    s1 = 'ABCDE'
    s2 = 'EDCBA'
    print(Solution().guess_game(s1,s2))

Outputs BBGBB.

CodePudding user response:

You can just use '==' to compare them and populate wrodle.

Code:

wordle = []
if len(s1) == len(s2):
    for i in range(len(s1)):
        if s1[i] == s2[i]:
            wordle.append('G')
        else:
            wordle.append('B')
    print("".join(wordle))
else:
    print("The strings should be equal length")

The reason why you are getting wordle[i] = 'B' IndexError: string index out of range is because you are trying to access an index even before it's creation

  • Related