{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "t = 'haystack needle haystack' # \"text\" - thing we search in\n", "p = 'needle' # \"pattern\" - thing we search for" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "def naive(p, t):\n", " assert len(p) <= len(t) # assume text at least as long as pattern\n", " occurrences = []\n", " for i in range(len(t)-len(p)+1): # for each alignment of p to t\n", " match = True # assume we match until proven wrong\n", " for j in range(len(p)): # for each position of p\n", " if t[i+j] != p[j]:\n", " match = False # at least 1 char mismatches\n", " break\n", " if match:\n", " occurrences.append(i)\n", " return occurrences" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[9]" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "naive(p, t)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'needle'" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "t[9:9+len(p)] # confirm it really occurs" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0, 6, 12]" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "naive('needle', 'needleneedleneedle')" ] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.14" } }, "nbformat": 4, "nbformat_minor": 1 }