Create unit tests for the following quick_sort function.
def quick_sort(arr):
if len(arr) <= 1:
return arr
else:
pivot = arr[0]
left = [x for x in arr[1:] if x < pivot]
right = [x for x in arr[1:] if x >= pivot]
return quick_sort(left) + [pivot] + quick_sort(right)
Response
import unittest
def quick_sort(arr):
if len(arr) <= 1:
return arr
else:
pivot = arr[0]
left = [x for x in arr[1:] if x < pivot]
right = [x for x in arr[1:] if x >= pivot]
return quick_sort(left) + [pivot] + quick_sort(right)
class TestQuickSort(unittest.TestCase):
def test_empty_array(self):
self.assertEqual(quick_sort([]), [])
def test_single_element_array(self):
self.assertEqual(quick_sort([5]), [5])
def test_sorted_array(self):
self.assertEqual(quick_sort([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5])
def test_reverse_sorted_array(self):
self.assertEqual(quick_sort([5, 4, 3, 2, 1]), [1, 2, 3, 4, 5])
def test_unsorted_array(self):
self.assertEqual(quick_sort([3, 7, 8, 5, 2, 1, 9, 4, 6]), [1, 2, 3, 4, 5, 6, 7, 8, 9])
def test_array_with_duplicates(self):
self.assertEqual(quick_sort([3, 7, 8, 5, 2, 1, 9, 4, 6, 3, 7]), [1, 2, 3, 3, 4, 5, 6, 7, 7, 8, 9])
if __name__ == '__main__':
unittest.main()
Explanation of the tests:
test_empty_array : Checks if the function correctly handles an empty array.
test_single_element_array : Checks if the function correctly handles an array with a single element.
test_sorted_array : Checks if the function correctly sorts an already sorted array.
test_reverse_sorted_array : Checks if the function correctly sorts a reverse sorted array.
test_unsorted_array : Checks if the function correctly sorts an unsorted array.
test_array_with_duplicates : Checks if the function correctly handles an array with duplicate elements.
Running the tests:
To run the tests, save the code as a Python file (e.g., test_quick_sort.py ) and run it from the command line:
python test_quick_sort.py
This will execute the tests and print the results. If all tests pass, you should see output similar to:
....
----------------------------------------------------------------------
Ran 6 tests in 0.001s
OK
|
Model: |
gemini-1.5-flash-001 |
Temperature: |
1 |
Max output tokens: |
8192 |
TopK: |
40 |
TopP: |
0.95 |
|