我不得不回答的問題是:第二次迭代不起作用
Implement a function with signature
def expand_one_or(course_lists):
This function takes a list of lists of strings course_lists, and modifies it as follows:
It finds the first list (call it lis) in course_lists in which "/" occurs.
It then finds the coordinate of the first "/" in lis (say i).
If lis[i-1] and lis[i+1] exist and are both courses, lis is replaced in course_lists with two new lists: a list identical to lis but with lis[i] and lis[i+1] removed, and a list identical to lis but with lis[i] and lis[i-1] removed.
Otherwise, all that happens is that lis[i] is removed from lis.
For example, if course_lists is:
[ ["CSC148H1", "/", "CSC150H1", ",", "CSC165H1", "/", "CSC240H1", "/", "CSC148H1", ";", "/"] ]
expand_one_or finds the first "/", and modifies course_lists to become
[ ["CSC148H1", ",", "CSC165H1", "/", "CSC240H1", "/", "CSC148H1", ";", "/"], ["CSC150H1", ",", "CSC165H1", "/", "CSC240H1", "/", "CSC148H1", ";", "/"] ]
And if we run expand_one_or a second time on the resulting list, we get
[ ["CSC148H1", ",", "CSC165H1", "/", "CSC148H1", ";", "/"], ["CSC148H1", ",", "CSC240H1", "/", "CSC148H1", ";", "/"] ["CSC150H1", ",", "CSC165H1", "/", "CSC240H1", "/", "CSC148H1", ";", "/"] ]
我曾經做到這一點的代碼是:
c = [ ["CSC148H1", "/", "CSC150H1", ",", "CSC165H1", "/", "CSC240H1", "/",
"CSC148H1", ";", "/"] ]
d = [['CSC148H1', ',', 'CSC165H1', '/', 'CSC240H1', '/', 'CSC148H1', ';', '/'], ['CSC150H1', ',', 'CSC165H1', '/', 'CSC240H1', '/', 'CSC148H1', ';', '/']]
def expand_one_or(course_lists):
accumulator = []
k = 0
for lis in course_lists:
for i in range(len(lis)):
if lis[i] == '/' and i != len(lis) and k == 0:
if lis[i - 1].isalnum() and lis[i + 1].isalnum():
k = 1
list1 = lis[:i] + lis[(i + 2):]
list2 = lis[i + 1:]
accumulator.append(list1)
accumulator.append(list2)
else:
lis.remove(lis[i])
k = 1
return accumulator
對於第一次迭代此代碼的功能,但沒有按」爲第二個工作。
因此,舉例來說,如果我們給的功能就像一個列表:
[ ["CSC148H1", "/", "CSC150H1", ",", "CSC165H1", "/", "CSC240H1", "/",
"CSC148H1", ";", "/"] ]
也應該給輸出
[['CSC148H1', ',', 'CSC165H1', '/', 'CSC240H1', '/', 'CSC148H1', ';', '/'], ['CSC150H1', ',', 'CSC165H1', '/', 'CSC240H1', '/', 'CSC148H1', ';', '/']]
現在,如果我們把功能該輸出代碼再次它應該給:
[ ["CSC148H1", ",", "CSC165H1", "/", "CSC148H1", ";", "/"],
["CSC148H1", ",", "CSC240H1", "/", "CSC148H1", ";", "/"]
["CSC150H1", ",", "CSC165H1", "/", "CSC240H1", "/", "CSC148H1", ";", "/"] ]
問題是,當我第一次運行該功能它給了我適當的輸出。但是,當我第二次運行它時,它給了我:
[['CSC148H1', ',', 'CSC165H1', '/', 'CSC148H1', ';', '/'], ['CSC240H1', '/', 'CSC148H1', ';', '/']]
而這是錯誤的輸出。
你能後的樣品輸出?你的意思是「不起作用」。你的實現有很多問題。例如,它在分解找到的第一行後不會退出(這可能是第二次失敗的原因)。此外,我在內部循環永遠不會等於len(lis) – kdopen 2014-12-04 00:45:24
「此代碼用於第一次迭代,但不適用於第二次。」迭代哪個循環?發生這種情況時,course_lists是什麼? – Marcin 2014-12-04 00:57:42
等待生病編輯整個問題。 – 2014-12-04 01:25:53