Divyanshu Juneja
Divyanshu Juneja

Reputation: 87

IndexError: index out of range in python

i am tying to solve the following question on a competitive coding website where i have to convert '->' to '.' only in the code section but not in the comments. https://www.hackerearth.com/problem/algorithm/compiler-version-2/

i have tried to write a solution but everytime i run it it gives me IndexError message. Some help is much appreciated. Below is my solution

import copy
temp_list = []

while True:
    string = input()
    if string != "":
        temp_list.append(string)
        string = None
    else:
        break

for i in range(len(temp_list)):
    j = 0
    while j <= (len(temp_list[i]) - 2):
        if string[i][j] == '-' and string[i][j + 1] == '>':
            #print("Hello WOrld")
            temp_string = string[i][:j] + '.' + string[i][j + 2:]
            string[i] = copy.deepcopy(temp_string)
        elif string[i][j] == '/' and string[i][j + 1] == '/':
            #print("Break")
            break
        else:
            #print(j)
            j += 1

for i in temp_list:
    print(i)

Upvotes: 0

Views: 1007

Answers (1)

mic4ael
mic4ael

Reputation: 8290

  1. if string is the same as if string != ""
  2. temp_list is a list so you can loop over it in a more pythonic way for i in temp_list
  3. string is a variable of type str so you cann't index it like this: string[i][j] (i guess you wanted to use temp_list in those cases)

Something like this below should work:

import copy
temp_list = []

while True:
    string = raw_input()
    if string:
        temp_list.append(string)
        string = None
    else:
        break

for i in temp_list:
    j = 0
    while j <= (len(temp_list[i]) - 2):
        if temp_list[i][j] == '-' and temp_list[i][j + 1] == '>':
            #print("Hello WOrld")
            temp_string = temp_list[i][:j] + '.' + temp_list[i][j + 2:]
            temp_list[i] = copy.deepcopy(temp_string)
        elif temp_list[i][j] == '/' and temp_list[i][j + 1] == '/':
            #print("Break")
            break
        else:
            #print(j)
            j += 1

for i in temp_list:
    print(i)

Upvotes: 2

Related Questions