Q1:
输入: print(tupleise(7, [10, 99, 35, 40]))输出: [(7, 10), (7, 99), (7, 35), (7, 40)]
参考代码:
def tupleise(value, items):
if len(items) == 1:
return [(value, items[0])]
return [(value, items[0])] + tupleise(value, items[1:])
print(tupleise(7, [10, 99, 35, 40]))
Q2:将下述代码用递归的方式写出来(不允许使用for-loop以及while-loop)
def things(list1, list2):
stuff = []
for thing1 in list1:
for thing2 in list2:
if thing2 > thing1:
stuff.append((thing1, thing2))
return stuff
参考代码:
def sub(item, list2):
if len(list2) == 0:
return []
if item < list2[0]:
return [(item, list2[0])] + sub(item, list2[1:])
else:
return []+sub(item, list2[1:])
def things(list1, list2):
if len(list1) == 0:
return []
else:
return sub(list1[0], list2)+things(list1[1:], list2)
list1 = [1, 3, 45, 2]
list2 = [2, 31, 32, 1]
print(things(list1, list2))