Question

In: Computer Science

Loop invariants: Consider the following Python function that merges two sorted lists. Here is a loop...

Loop invariants:
Consider the following Python function that merges two sorted lists.
Here is a loop invariant for loop 1:
“the contents ofnewlistare in sorted order,newlistcontainsaelements oflistAandbelements oflistB”

def mergeSortedLists(listA, listB):

 newlist = [ ]

 a = 0

 b = 0

 # loop 1

 while a < len(listA) and b < len(listB):

  if listA[a] < listB[b]:

   newlist.append(listA[a])

   a +=1

  else:

   newlist.append(listB[b])

   b +=1

 if a < len(listA):

  newlist.extend(listA[a:])

 if b < len(listB):

  newlist.extend(listB[b:])

 return newlist

(a) Write down (in regular English) a pre-condition for the function. What important property needs to be true about the input in order for this function to work correctly?[1 marks]
(b) Write down (in regular English) a post-condition for the function. What do we want this function to return?[1 marks]
(c) Give an argument to show that the loop invariant is true before loop 1 is entered for the first time.[2 marks]
(d) Give an argument to show that, if the loop invariant is true upon entry to an arbitrary iteration of loop 1, it remains true after that iteration of the loop.[2 marks]
(e) Write down (in regular English) a post-condition for loop 1. What is established by the loop invariant and the loop exit condition upon exit from loop 1?[2 marks]
(f) Give an argument to show that your post-condition for loop 1, along with action of the code following the loop, infers your post-condition for the function.

Solutions

Expert Solution

a)  A pre-condition for the input should be that the list should contain numeric values only. If we use strings, the side effect will be because of the function extend as a string is an iterable, so if you extend a list with a string, you’ll append each character as you iterate over the string.

Example:

my_list = ['chegg','study']

my_list.extend('expert')

print my_list

So, the output will be ['chegg','study','e','x','p','e','r','t']

b)  We want this function to return the contents of the lists in sorted order. As we have performed the operations and our newlist is ready to be returned. We can return its contents as string by using str(newlist).

c) An argument to show that the loop invariant is true before loop 1 is entered for the first time.

listA = [1, 5, 6, 9]

listB = [3, 4, 7, 8, 10]

Here: a = 0 < len(listA) & b = 0 < len(listB), so it will enter the loop 1.

d) Same above example can be used for this scenario also:

listA = [1, 5, 6, 9]

listB = [3, 4, 7, 8, 10]

In 1st iteration:

a = 0 and b = 0, listA[a] = 1 and listB[b] = 3

As  listA[a] < listB[b], a will become 1 and newList = [ 1 ]

In 2nd iteration:

a = 1 and b = 0, which means a < len(listA) & b < len(listB) so it remains true after iteration of the loop.

e)  Loop exit condition is that if any one of the list is fully traversed, i.e. all the elements of any of the listA or listB are included in the new list then the while loop shall exit.

f)  In same example,

listA = [1, 5, 6, 9]

listB = [3, 4, 7, 8, 10]

After 8th iteration:

a = 4 and b = 3, which means a is not less than len(listA) as newList would have become [1, 3, 4, 5, 6, 7, 8, 9] containing all the elements of listA, so while loop will exit and the following code will start executing.

if b < len(listB):

newlist.extend(listB[b:])

After this code, newList will become [1, 3, 4, 5, 6, 7, 8, 9, 10]


Related Solutions

Python question Write a function int(lofi, alofi) that consumes two sorted lists of distinct integers lofi...
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: No recursion or abstract list functions, intersect must run in O(n) where n is the combined length of the two parameters. sort function is not allowed as well as list comprehensions math is the only library that can be imported Example: int([4, 13,...
C++ Data Structures 4. Write a client function that merges two instances of the Sorted List...
C++ Data Structures 4. Write a client function that merges two instances of the Sorted List ADT using the following specification. MergeLists(SortedType list1, SortedType list2, SortedType& result) Function: Merge two sorted lists into a third sorted list. Preconditions: list1 and list2 have been initialized and are sorted by key using function ComparedTo. list1 and list2 do not have any keys in common. Postconditions: result is a sorted list that contains all of the items from list1 and list2. c. Write...
EXTRA CHALLENGE: Could you implement a merge lists function which merges n lists in order? This...
EXTRA CHALLENGE: Could you implement a merge lists function which merges n lists in order? This function would accept a pointer to an array of n pointers, where each pointer refers to a list.
In python i want to create a function. The function will take in two linked lists...
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...
Write a method that takes two Sorted Arrays of different sizes and merges them into one...
Write a method that takes two Sorted Arrays of different sizes and merges them into one sorted array, and use the method to write a full recursive Merge Sort Algorithm.
Python Question: Write a function that checks to see if an array of integers is sorted...
Python Question: Write a function that checks to see if an array of integers is sorted in an increasing fashion, returning true if it is, false otherwise. Test it with at least4 arrays - 2 sorted and 2 not sorted. Use a CSV formatted input file as described in the previous question to run your program through some tests, where again the filename is passed as an argument. Heres what I have so far: import sys # command line arguement...
Define a Python function named matches that has two parameters. Both parameters will be lists of...
Define a Python function named matches that has two parameters. Both parameters will be lists of ints. Both lists will have the same length. Your function should use the accumulator pattern to return a newly created list. For each index, check if the lists' entries at that index are equivalent. If the entries are equivalent, append the literal True to your accumulator. Otherwise, append the literal False to your accumulator. Hint: Since you must use the same index with each...
Smaller index Complete the following function according to its docstring using a while loop. The lists...
Smaller index Complete the following function according to its docstring using a while loop. The lists we test will not all be shown; instead, some will be described in English. If you fail any test cases, you will need to read the description and make your own test. def smaller_index(items): """ (list of int) -> int    Return the index of the first integer in items that is less than its index, or -1 if no such integer exists in...
Recall that in MergeSort algorithm, we used a linear-time subroutine called Merge which merges two sorted...
Recall that in MergeSort algorithm, we used a linear-time subroutine called Merge which merges two sorted lists into a single sorted list. Now suppose there are k sorted lists and there are n elements in total in these k lists. Design an efficient algorithm that merges these k sorted lists into one sorted list. The running time of your algorithm should be a function of both n and k.
Given two lists, write python code to print “True” if the two lists have at least...
Given two lists, write python code to print “True” if the two lists have at least one common element. For example, x = [1,2,3], y=[3,4,5], then the program should print “True” since there is a common element 3.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT