2016-08-15 32 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。 –