Skip to content
Advertisement

Python finding numbers from a list that satisfy a specific condition [closed]

Good evening, I am currently having some problems implementing a binary search algorithm, which extracts the amount of numbers in a list that satisfy this condition

Suppose Sorted list A = [1,2,4,5,6,7,8] I need to find the amount of numbers that satisfy this condition.

Absolute(A[i] – i) <= C where C is a number specified by the user for example

|A[i] -i|<= C <—- That is the condition I need to satisfy, i need to find the amount of numbers that are in the list that fulfil this condition.

Example:

JavaScript

Now I realise I need to use binary search to ensure my running time is in O(log N) time, but I am not sure where do I put the condition/if statement.

Can someone please show me how this would look in python code. Thank you so much for the assistance.

Advertisement

Answer

Using Python Bisect module

Use a key with binary_search module to allow function evaluations

JavaScript

Test

JavaScript

Test c from 0 to 63

JavaScript

Output

JavaScript

Performance Testing

Compare to list comprehension (O(n) algorithm)

JavaScript

Timing Test

Create a large random array

JavaScript

Binary search ~289X faster for n = 10, 000

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement