Question: Use python 3 Problem: Write a Python program that contains a function called count_inversions that will count the number of inversions in a list of

Use python 3

Problem: Write a Python program that contains a function called count_inversions that will count the number of inversions in a list of values. The count_inversions function will have a single parameter, which is the list to count inversions in. The function should sort the list in ascending order using merge sort, and return the number of inversions in the original list as well as the sorted list. The total number of inversions in the merged list will be the number of inversions in the left half, plus the number of inversions in the right half, plus the number of inversions between the two lists. For example, if the initial list is [5, 1, 2, 4], the left half ([5, 1]) contains 1 inversion and is sorted as [1, 5]. The right half ([2, 4]) contains 0 inversions and is sorted as [2, 4]. When we merge the left and right halves, we first choose 1 from the left half, then 2 from the right half. When we choose 2, there is one item remaining in the left half, so we add one inversion to the count. Next, we choose 4 from the right half, and again we have one item remaining in the left half, so we add one more inversion to the count. Finally, we choose 5 from the left half. The total number of inversions is (the number of inversions in the left half) + (the number of inversions in the right half) + (the number of inversions counted in the merge step), which is 1 + 0 + 2 = 3 in this example.

Sample Run 1

my_list = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] inversions = count_inversions(my_list) print(my_list) print(inversions)

Sample Output 1

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 45

Sample Run 2

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] inversions = count_inversions(my_list) print(my_list) print(inversions)

Sample Output 2

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 0

Thank you

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!