In: Computer Science
Python question
Write a function
int(lofi, alofi)
that consumes two sorted lists of distinct integers lofi and alofi, and returns a sorted list that contains only elements common to both lists.
You must obey the following restrictions:
Example:
int([4, 13, 10, 8, 15], [2, 3, 6, 13, 11, 12, 8]) => [8, 13]
Python code:
#defining function
def int(lofi,alofi):
#initializing list1 to store common elements
list1=[]
#looping through each element in lofi
for i in lofi:
#checking if each element in lofi is in alofi
if i in alofi:
#inserting that element into list1
list1.append(i)
#list for sorting
list2=[]
#looping through each element in list1
for i in range(len(list1)):
#inserting into list2, minimum element in list1
list2.append(min(list1))
#removing that element from list1
list1.remove(min(list1))
#returning list2
return(list2)
#testing and printing
print(int([4,13,10,8,15],[2,3,6,13,11,12,8]))
Screenshot:
Output: