Question: Implement a Python function that finds the k largest items in a list. DO NOT USE ANY BUILD IN FUNCTIONS. Implement find _ k _

Implement a Python function that finds the k largest items in a list. DO NOT USE ANY BUILD IN FUNCTIONS.
Implement find_k_largest(nums,k)function that takes a list nums of integers and an integer k as parameters. The function should return a list containing the k largest items in descending order.
## TESTING find_k_largest function
## DO NOT EDIT THIS CELL.
def test_find_k_largest():
# Test Case 1: Positive Integers
nums1=[3,1,4,1,5,9,2,6,5,3,5]
k1=3
expected1=[9,6,5]
assert find_k_largest(nums1, k1)== expected1, f"Test Case 1 failed: Expected {expected1}, but got {find_k_largest(nums1, k1)}"
# Test Case 2: Negative Integers
nums2=[-3,-1,-4,-1,-5,-9,-2,-6,-5,-3,-5]
k2=4
expected2=[-1,-1,-2,-3]
assert find_k_largest(nums2, k2)== expected2, f"Test Case 2 failed: Expected {expected2}, but got {find_k_largest(nums2, k2)}"
# Test Case 3: Mixed Integers
nums3=[3,-1,4,-1,5,-9,2,-6,5,3,-5]
k3=5
expected3=[5,5,4,3,3]
assert find_k_largest(nums3, k3)== expected3, f"Test Case 3 failed: Expected {expected3}, but got {find_k_largest(nums3, k3)}"
# Test Case 4: Duplicate Integers
nums4=[3,1,4,1,5,9,2,6,5,3,5]
k4=4
expected4=[9,6,5,5]
assert find_k_largest(nums4, k4)== expected4, f"Test Case 4 failed: Expected {expected4}, but got {find_k_largest(nums4, k4)}"
# Test Case 5: Empty List
nums5=[]
k5=3
expected5=[]
assert find_k_largest(nums5, k5)== expected5, f"Test Case 5 failed: Expected {expected5}, but got {find_k_largest(nums5, k5)}"
# Test Case 6: List with Fewer than k items
nums6=[3,1,4,1]
k6=5
expected6=[4,3,1,1]
assert find_k_largest(nums6, k6)== expected6, f"Test Case 6 failed: Expected {expected6}, but got {find_k_largest(nums6, k6)}"

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 Programming Questions!