我不得不回答的问题是:第二次迭代不起作用
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