我要回答的问题是:
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', ';', '/']]
这是错误的输出。你知道吗
试试这个:
相关问题 更多 >
编程相关推荐