Python Forum
[Discussion] Re. Substring counting
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Discussion] Re. Substring counting
#1
This would normally go in homework discussions, but as the user has already solved their problem there is no reason to not post publicly.

Original poster was asking how to find the number of times one string occurred as a substring in another string.
https://python-forum.io/Thread-Substring-Counting

Extend this to instead give an algorithm that finds the number of times one string occurs as a subsequence in another string.

Whereas a substring must be contiguous, a subsequence need not be, though it must still be in the correct order.

For example if we count occurrences of the subsequence "an" in "banana" we get 3.
Comprised of the following: "banana", "banana", "banana"

Algorithm should run in O(mn) time where m is the size of the string we are looking for and n is the size of the string we are looking in.

def subsequence_count(needle, haystack):
    """Your code here"""
    pass

print(subsequence_count("an", "banana")) # Should print 3
print(subsequence_count("an", "trans-Panamanian banana")) # Should print 25
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 3,046 May-21-2021, 06:14 PM
Last Post: nilamo
  Substring in a string Propoganda 1 2,295 Dec-01-2019, 08:45 AM
Last Post: perfringo
  Find a substring in a dictonary; value substring of key aapurdel 2 7,183 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