w3resource

Python: Bisect Exercises, Practice, Solution


Python Bisect: [ 9 exercises with solution]


[An editor is available at the bottom of the page to write and execute the scripts.   Go to the editor]

1. Write a Python program to locate the left insertion point for a specified value in sorted order.
Expected Output:
4
2
Click me to see the sample solution

2. Write a Python program to locate the right insertion point for a specified value in sorted order.
Expected Output:
3
2
Click me to see the sample solution

3. Write a Python program to insert items into a list in sorted order.
Expected Output:
Original List:
[25, 45, 36, 47, 69, 48, 68, 78, 14, 36]
Sorted List:
[14, 25, 36, 36, 45, 47, 48, 68, 69, 78]
Click me to see the sample solution

4. Write a Python program to find the first occurrence of a given number in a sorted list using Binary Search (bisect).
Expected Output:
First occurrence of 8 is present at index 4
Click me to see the sample solution

5. Write a Python program to find the index position of the largest value smaller than a given number in a sorted list using Binary Search (bisect).
Expected Output:
Largest value smaller than 5 is at index 3
Click me to see the sample solution

6. Write a Python program to find the index position of the last occurrence of a given number in a sorted list using Binary Search (bisect).
Expected Output:
Last occurrence of 8 is present at 5
Click me to see the sample solution

7. Write a Python program to find three integers which give the sum of zero in a given array of integers using Binary Search (bisect).
Expected Output:
[[-40, 0, 40], [-20, -20, 40], [-20, 0, 20]]
[[-6, 1, 5], [-6, 2, 4]]
Click me to see the sample solution

8. Write a Python program to find a triplet in an array such that the sum is closest to a given number. Return the sum of the three integers.
Expected Output:
Array values & target value: [1, 2, 3, 4, 5, -6] & 14
Sum of the integers closest to target: 12
Array values & target value: [1, 2, 3, 4, -5, -6] & 5
Sum of the integers closest to target: 6
Click me to see the sample solution

9. Write a Python program to find four elements from a given array of integers whose sum is equal to a given number. The solution set must not contain duplicate quadruplets.
Expected Output:
Array values & target value: [-2, -1, 1, 2, 3, 4, 5, 6] & 10
Solution Set:
[[-2, 1, 5, 6], [-2, 2, 4, 6], [-2, 3, 4, 5], [-1, 1, 4, 6], [-1, 2, 3, 6], [-1, 2, 4, 5], [1, 2, 3, 4]]
Click me to see the sample solution

 

Python Code Editor:

More to Come !

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.

Test your Python skills with w3resource's quiz