1

I have a sorted list

my_list = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384]

I have a value lets say 445. I want to find the index of first max in list. For above case, it should return index value 9 (512).

3
  • 1. What have you tried? 2. Any requirement regarding complexity? Commented Dec 14, 2016 at 7:18
  • 1
    use for i, v in enumerate(my_list): to populate both index and value. Commented Dec 14, 2016 at 7:20
  • It is prefered to avoid loop. Commented Dec 14, 2016 at 7:20

1 Answer 1

4

The easiest way is to use binary search to find the required index, because the input list is sorted. This algorithm is already implemented in the bisect module:

import bisect

my_list = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384]
print(bisect.bisect_right(my_list, 445))
print(bisect.bisect_right(my_list, 512))

Prints:

9
10
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.