dificulty solving a code in O(logn)

2024/10/6 18:33:08

I wrote a function that gets as an input a list of unique ints in order,(from small to big). Im supposed to find in the list an index that matches the value in the index. for example if L[2]==2 the output is true. so after i did that in complexity O(logn) i now want to find how many indexes behave like that in the given list with the same complexity O(logn). im uploading my first code that does the first part and the second code which i need help with:

def steady_state(L):lower= 0upper= len(L) -1while lower<=upper:middle_i= (upper+ lower)//2if L[middle_i]== middle_i:return middle_ielif L[middle_i]>middle_i:upper= middle_i-1else:lower= middle_i +1return Nonedef cnt_steady_states(L):lower= 0upper= len(L) -1a=b=steady_state(L)if steady_state(L)== None:return 0else:cnt=1while True:if L[upper] == upper and a<=upper:cnt+= upper-aupper= aif L[lower]== lower and b>=lower:cnt+= b- lowerlower = b
Answer

It's not possible with the restrictions you've given yet. The best complexity you can theoretically achieve is On).

O() assumes the worst case (just a definition, you could drop that part). And in the worst case you will always have to look at each item in order to check it for being equal to its index.

The case changes if you have more restrictions (e. g. the numbers are all ints and none may appear more than once, i. e. no two consecutive numbers are equal). Maybe this is the case?

EDIT:

After hearing that in fact my assumed restrictions apply (i. e. only once-appearing ints) I now propose this approach: You can safely assume that you can have only exactly one continuous range where all your matching entries are located. I. e. you only need to find a lower bound and upper bound. The wanted result will then be the size of that range.

Each bound can safely be found using a binary search, of which each has O(log n).

def binsearch(field, lower=True, a=0, b=None):if b is None:b = len(field)while a + 1 < b:c = (a + b) / 2if lower:if field[c] < c:a = celse:b = celse:  # search for upper boundif field[c] > c:b = celse:a = creturn b if lower else adef indexMatchCount(field):upper = binsearch(field, lower=False)lower = binsearch(field, b=upper+1)return upper - lower + 1

This I used for testing:

field = list({ random.randint(-10, 30) for i in range(30) })
field.sort()
upper = binsearch(field, lower=False)
lower = binsearch(field, b=upper+1)
for i, f in enumerate(field):print lower <= i <= upper, i == f, i, f
https://en.xdnf.cn/q/70333.html

Related Q&A

Scrapy. How to change spider settings after start crawling?

I cant change spider settings in parse method. But it is definitely must be a way. For example:class SomeSpider(BaseSpider):name = mySpiderallowed_domains = [example.com]start_urls = [http://example.co…

numpy ctypes dynamic module does not define init function error if not recompiled each time

sorry for yet an other question about dynamic module does not define init function. I did go through older questions but I didnt find one which adress my case specifically enought.I have a C++ library …

How do I save Excel Sheet as HTML in Python?

Im working with this library XlsxWriter.Ive opened a workbook and written some stuff in it (considering the official example) - import xlsxwriter# Create a workbook and add a worksheet. workbook = xlsx…

Faster sockets in Python

I have a client written in Python for a server, which functions through LAN. Some part of the algorithm uses socket reading intensively and it is executing about 3-6 times slower, than almost the same …

Python gmail api send email with attachment pdf all blank

I am using python 3.5 and below code is mostly from the google api page... https://developers.google.com/gmail/api/guides/sending slightly revised for python 3.xi could successfully send out the email …

how to find height and width of image for FileField Django

How to find height and width of image if our model is defined as followclass MModel:document = FileField()format_type = CharField()and image is saved in document then how we can find height and width o…

Given a pickle dump in python how to I determine the used protocol?

Assume that I have a pickle dump - either as a file or just as a string - how can I determine the protocol that was used to create the pickle dump automatically? And if so, do I need to read the entir…

Get First element by the recent date of each group

I have following model in djangoBusiness ID Business Name Business Revenue DateHere is the sample data:Business ID | Business Name | Business Revenue | Date 1 B1 1000 …

remote: ImportError: No module named gitlab

I wrote gitlab hook with python. And added to post-receive hooks in gitlab server. When i push to remote origin server from my laptop, i get following error. But it works when i run script manually in …

Using an Access database (.mdb) with Python on Ubuntu [duplicate]

This question already has answers here:Working with an Access database in Python on non-Windows platform (Linux or Mac)(5 answers)Closed 7 years ago.Im trying to use pyodbc to access a .mdb on Ubuntu. …