2016-08-15 64 views
-1

我打算在竞争性编码网站上解决以下问题,我必须将' - >'转换为'。'。只在代码部分但不在注释中。 https://www.hackerearth.com/problem/algorithm/compiler-version-2/IndexError:python中的索引超出范围

我试图写一个解决方案,但每次我运行它它给了我IndexError消息。一些帮助非常感谢。下面是我的解决办法

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) 
+0

你能发布完整的错误追溯? – Harrison

+0

这里有很多问题,不知道从哪里开始 – mic4ael

回答

0
  1. if string相同if string != ""
  2. temp_list的清单,让您可以遍历它更Python的方式for i in temp_list
  3. stringstr类型,这样你的变量不能像这样索引它:string[i][j](我想你想在这些情况下使用temp_list

下面的东西应该工作:

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) 
+0

我得到了我的错误,确实是一个愚蠢的错误!感谢您指出 –

+0

您可以upvote我的答案,因为我不知道为什么它被downvoted – mic4ael

+0

抱歉,但我既不能upvote也不下载你的答案,因为我没有足够的声誉,因为我是新的Stackoverflow。 –