In: Computer Science
In python i want to create a function. The function will take in two linked lists as the parameters. If one is shorter than the other then the shorter will be the length. I want to take the values from both linked lists and turn them into tuples. I then want these tuples to be put into a new linked list. I want to return that linked list. I want to do this using recursion and no helper functions or loops are allowed.
For example:
linked_list1 -> 1 -> a -> 65 -> 9
linked_list2 -> 3 -> 2 -> yes
final_linked_list -> (1,3) -> (a,2) -> (65, yes)
The following code accepts 2 lists and merges them into a tuple of the length of the smaller list:
def merge(L1, L2):
merged_list = []
for i in range(min((len(L1), len(L2)))):
while True:
try:
tup = (L1[i], L2[i])
except IndexError:
if len(L1) > len(L2):
L2.append('')
tup = (L1[i], L2[i])
elif len(L1) < len(L2):
L1.append('')
tup = (L1[i], L2[i])
continue
merged_list.append(tup)
break
return merged_list
# Driver code
L1 = [1, 2, 3, 4]
L2 = ['a', 'b', 'c']
print(merge(L1, L2))