Python Forum
[split] Time Complexity of Counting
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[split] Time Complexity of Counting
#10
The following code has complexity O(n log(n)) like sorting
import itertools as itt
import operator as op

def solve(problem):
    es = sorted((x, i) for i, x in enumerate(problem))
    t = sorted((x[1], i)
         for k, g in itt.groupby(es, key = op.itemgetter(0))
         for i, x in enumerate(g, 1))
    return [x[1] for x in t]

if __name__ == '__main__':
    problem = [48,52,55,48,52,55,60,62,48]
    expected = [1,1,1,2,2,2,1,1,3]
    assert solve(problem) == expected
Of course, you can reach the same asymptotic complexity by using a sorted dictionary based on binary search instead of the dict class. This module probably provides the needed SortedDict class.

But here, we do it with the standard library alone! For most practical purposes, the dict based solution is probably the best one although it's not O(n log(n))
Reply


Messages In This Thread
[split] Time Complexity of Counting - by Mekire - Jan-18-2017, 07:52 PM
RE: [split] Time Complexity of Counting - by wavic - Jan-18-2017, 10:48 PM
RE: [split] Time Complexity of Counting - by buran - Jan-10-2019, 10:11 AM
RE: [split] Time Complexity of Counting - by Gribouillis - Jan-10-2019, 11:09 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  counting lines in split data Skaperen 6 1,426 Oct-07-2022, 07:09 PM
Last Post: Skaperen
  Split gps files based on time (text splitting) dervast 0 1,896 Nov-09-2020, 09:19 AM
Last Post: dervast
  What is the run time complexity of this code and please explain? samlee916 2 2,305 Nov-06-2020, 02:37 PM
Last Post: deanhystad
  Basic Time Complexity Help Adakip 1 1,840 Aug-25-2019, 09:12 AM
Last Post: ThomasL
  Time complexity of dict vs attributes heras 6 3,790 Aug-24-2018, 10:18 PM
Last Post: Gribouillis
  How to calculate the mccabe complexity in module falke8? fuqianz 1 3,128 Oct-16-2017, 02:08 AM
Last Post: sparkz_alot

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020