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,...
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...
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.
For this lab, you will work with two-dimensional lists in Python. Do the following: Write a...
For this lab, you will work with two-dimensional lists in Python. Do the following: Write a function that returns the sum of all the elements in a specified column in a matrix using the following header: def sumColumn(matrix, columnIndex) Write a function display() that displays the elements in a matrix row by row, where the values in each row are displayed on a separate line. Use a single space to separate different values. Sample output from this function when it...
Python: I am currently a function that will return a list of lists, with the frequency...
Python: I am currently a function that will return a list of lists, with the frequency and the zip code. However, I am having a difficult time organizing the list in decreasing order of frequency. We are asked to use sort () and sorted () instead of lambda. The function will find 5 digit zip codes, and when it sees a 9-digit zip code, the function needs to truncate the last 4 digits. The following is an example of the...
Python Write a for loop with a range function and format output as currency Use an...
Python Write a for loop with a range function and format output as currency Use an input statement to ask the user for # of iterations using the prompt: #? [space after the ?] & assign to a variable Convert the variable to an integer Use a for loop and a range function to display all whole numbers from 1 to the user entered number Display the value of the item variable on screen in each iteration in the following...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT