Question
Write a function that returns the common elements between two sorted arrays of integers in Python. Eg. list1 = [2,4,3,6,3,8,9] list2 = [1,2,4,2,6,4,8] #Code Below
Write a function that returns the common elements between two sorted arrays of integers in Python.
Eg. list1 = [2,4,3,6,3,8,9]
list2 = [1,2,4,2,6,4,8]
#Code Below
# Implement your function below.
def common_elements(list1, list2, n1, n2): if len(list1) == 0 and len(list2) == 0: result = [] return None # Initialize starting indexes for ar1[], ar2[]
i, j= 0, 0 # Use length of arrays for while loop n1 = len(list1) n2 = len(list2) # Iterate through three arrays while all arrays have elements while (i < n1 and j < n2): # If x = y and y = z, print any of them and move ahead # in all arrays if (list1[i] == list2[j]): result = list1[i] print (result) i += 1 j += 1 return result # x < y elif list1[i] < list2[j]: i += 1
# NOTE: The following input values will be used for testing your solution. list_a1 = [1, 3, 4, 6, 7, 9] list_a2 = [1, 2, 4, 5, 9, 10] # common_elements(list_a1, list_a2) should return [1, 4, 9] (a list).
list_b1 = [1, 2, 9, 10, 11, 12] list_b2 = [0, 1, 2, 3, 4, 5, 8, 9, 10, 12, 14, 15] # common_elements(list_b1, list_b2) should return [1, 2, 9, 10, 12] (a list).
list_c1 = [0, 1, 2, 3, 4, 5] list_c2 = [6, 7, 8, 9, 10, 11] # common_elements(list_b1, list_b2) should return [] (an empty list).
print (common_elements(list1, list2, n1, n2))
Error: name list1 is not defined. I need help using current function and values, to fix error code request to get desired output.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started