0

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)
2
  • Can you post the full error traceback? Commented Aug 15, 2016 at 14:22
  • lots of problems here, don't know where to start Commented Aug 15, 2016 at 14:26

1 Answer 1

2
  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)
Sign up to request clarification or add additional context in comments.

3 Comments

I got my error, that was a silly mistake indeed!! Thanks for pointing it out
could you upvote my answer since I don't know why it had been downvoted
sorry but i can neither upvote nor download your answer because I dont have enough reputation as I am new on Stackoverflow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.