Python Forum
[Discussion] Re. Substring counting
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Discussion] Re. Substring counting
#3
That's pretty neat. Your recursive approach hurts my head.
I have trouble analyzing the runtime of recursive algorithms like this.

I want to say that it is O(n^m) but I'm not positive.
I base this on the idea that a run of size m,n takes:
T(m,n) = O(n) * T(m-1, n-1)
Not particularly confident in that though.

I did add a particularly pathological test however, and yours doesn't seem to manage it in a reasonable time
Output:
... ---------------------------------------------------------------------- Ran 3 tests in 346.731s
My approach went the dynamic programming route.

T[i, j] is the number of times needle[:i+1] occurs as a subsequence of haystack[:j+1] where T is our dynamic programming table.
This leads to the recursive problem definition:
T[i,j] = T[i,j-1] + T[i-1,j-1] if needle[i] == haystack[j] else T[i,j-1]

The algorithm ends up fairly straight forward from there just filling in the table row by row:
The pathological test is added at the bottom.
Mine results in:
Output:
... ---------------------------------------------------------------------- Ran 3 tests in 0.003s OK
Reply


Messages In This Thread
Re. Substring counting - by Mekire - Jan-22-2018, 02:56 AM
RE: [Discussion] Re. Substring counting - by Mekire - Jan-22-2018, 08:52 AM
RE: [Discussion] Re. Substring counting - by Mekire - Jan-22-2018, 10:29 AM
RE: [Discussion] Re. Substring counting - by wavic - Jan-22-2018, 11:38 AM
RE: [Discussion] Re. Substring counting - by wavic - Jan-22-2018, 11:43 AM
RE: [Discussion] Re. Substring counting - by Mekire - Jan-22-2018, 12:41 PM
RE: [Discussion] Re. Substring counting - by wavic - Jan-22-2018, 01:56 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Finding how many times substring is in a string using re module ranbarr 4 2,972 May-21-2021, 06:14 PM
Last Post: nilamo
  Substring in a string Propoganda 1 2,234 Dec-01-2019, 08:45 AM
Last Post: perfringo
  Find a substring in a dictonary; value substring of key aapurdel 2 7,079 May-31-2019, 06:14 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

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