STRG-P1

Patterns with blanks

Practice 1 of 6String algorithms12 tests

The problem

A pattern can have blanks, written ?, that match any one letter. Return every place i where the pattern fits the text: text[i + j] == pat[j] for every j where pat[j] is not ?. List the places in increasing order. Places may overlap, and the pattern must fit inside the text.

find_all("abcabcab", "cab")    # [2, 5]
find_all("banana", "?an")      # [0, 2]
find_all("aaaa", "aa")         # [0, 1, 2]
find_all("ab", "abc")          # []

The text has lower-case letters, and may also contain ?; only a ? in the pattern is a blank. The pattern has at least one character.

Limits

  • The text has up to 20,000 letters and the pattern up to 20. The naive method of lesson 1 is fast enough.

Builds on STRG-1 Naive matching.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

12 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2A blankNot run
3Overlapping placesNot run
4Only blanksNot run
5Pattern longer than the textNot run
6The last placeNot run
7The whole textNot run
8A blank at each endNot run
9No matchNot run
10A question mark is not a letterNot run
1120,000 lettersNot run
12Nearly every placeNot run