I am trying to write a SML recursive function called mergePass that will take a
ID: 3804757 • Letter: I
Question
I am trying to write a SML recursive function called mergePass that will take a list of list and merge pairs of the list. The number of sublist does not have to be even for example: mergePass([[24],[39],[50],[28],[50],[1],[15],[1],[35],[40],[9],[8],[25],[1],[2]]) returns [[24,39],[28,50],[1,50],[1,15],[35,40],[8,9],[1,25],[2]]
mergePass([[24,39],[28,50],[1,50],[1,15],[35,40],[8,9],[1,25],[2]]) returns [[24,28,39,50],[1,1,15,50],[8,9,35,40],[1,2,25]]
I have this section of code I was trying out hd(x)@hd(tl(x)). If I was to enter [[1],[9],[7],[12]] or any other list of list in place of x it would give me back [1,9] but I need to recursively be able to go through the rest of the list and make other pairs This may not be the only or easiest way to do it but it is all I can come up with
Explanation / Answer
program.py-------
from sys import exit
import random
'''This function merge a list of lists recursively'''
def recursiveMerge(l, i):
try:
l[i].extend(l[i+1])
except IndexError as iError:
return
else:
del(l[i+1])
recursiveMerge(l, i+1)
if __name__ == "__main__":
try:
n = int(input(" Enter length of the list : "))
except ValueError as v:
print(" Error code :",v)
exit(-1)
l = []
for i in range(n):
l += [[random.randrange(1,59), random.randrange(59,100)]]
print(" Initially list : ",l)
recursiveMerge(l, 0)
print(" After merge : ",l)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.