|
80鱼币
题目如图,由于水平有限而且对函数的使用有所限制,绞尽脑汁也想不出来,有没有大佬能给点建议,感激不尽
以下是未完成的代码。。。( cons(x,list) 是将一个元素加到列表第一位;tail(list)是把列表首位去除得到一个新列表;value是提取列表第一个元素;isempty是判断一个列表是否为空)
Algorithm: defCombine (List 1, List 2)
Require:two list, list1 and list2
Result: a combination of two list
If isempty (list1) then
Return list2
Else
If isempty (list2) then
Return list1
endif
else
if (isempty (tail(list1)) and isempty (tail(list2)))
return cons(value(list1), value(list2))
endif
else
if (isempty (tail(list1)) and not isempty (tail(list2)))
return #这里没有想出来 是cons(???,tail(list2))
endif
else
if (not isempty (tail(list1)) and isempty (tail(list2)))
return #问题同上
endif
else
return cons(cons(value(list1), value(list2)), defcombine (tail(list1), tail(list2))
用python写一个:
- def combine(list1, list2):
- list3 = []
- length = min(len(list1), len(list2))
- for i in range(length):
- list3.extend([list1[i], list2[i]])
- if len(list1) >= len(list2):
- list3.extend(list1[length:])
- else:
- list3.extend(list2[length:])
- return list3
复制代码
|
|