def array_to_list(data):
'''
Converts an array to linked list with the same order as in array
returns None if array is empty
'''
head = None
# for each value in array
for val in data:
# if list is empty then create a new head node
if head is None:
head = list_node.ListNode(val)
temp = head
# else create a new node and add it to the list
else:
temp.next = list_node.ListNode(val)
temp = temp.next
return head
def pair(list1, list2):
'''
Retruns a list with each node storing tuple of value pairs from the given lists
The returned list is of the length same as the smaller of the two lists givens
'''
if list1 is None or list2 is None:
return None
head = list_node.ListNode((list1.val,list2.val))
temp, temp1, temp2 = head, list1.next, list2.next
while temp1 is not None and temp2 is not None:
temp.next = list_node.ListNode((temp1.val,temp2.val))
temp, temp1, temp2 = temp.next, temp1.next, temp2.next
temp.next = None
return head
change these functions in a recursively way.
and please add some comments like this
"""
A summary/description of what the function does.
Parameters: give a brief description for each parameter (if there are any)
Returns: give a brief description of each of the return values (if there are any)
Pre-condition: detail any assumptions made by the function, i.e., any pre-condition that must be met in order for the function to work correctly
Post-condition: detail what we can expect to be true after the function has finished execution, i.e., its post-condition
""
def array_to_list(data,index = 0):
'''
Converts an array to linked list with the same order as in array
returns None if array is empty
'''
if len(data) == index:
return None
temp = list_node.ListNode(data[index])
temp.next = array_to_list(data, index=index+1)
return temp
def pair(list1, list2,index1 = 0,index2 = 0):
'''
Retruns a list reccusively with each node storing tuple of value pairs from the given lists
The returned list is of the length same as the smaller of the two lists givens
'''
if index1 == len(list1) or index2 == len(list2):
return None
temp = list_node.ListNode((list1[index1], list2[index2]))
temp.next = pair(list1, list2,index1 = index1 + 1, index2 = index2+1)
return temp
Get Answers For Free
Most questions answered within 1 hours.