repl.it
@mtf/

needle-haystack found string in string

Python

No description

fork
loading
Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
def contains(haystack, needle):
    n = len(needle)
    f = needle[0]
    for i, x in enumerate(haystack):
        if x == f:
            if haystack[i:n + i] == needle:
                return True
    return False

print (contains('superimposed', 'impose'))    # True

def indices(haystack, needle):
    n = len(needle)
    f = needle[0]
    s = []
    for i, x in enumerate(haystack):
        if x == f:
            if haystack[i:n + i] == needle:
                s.append(i)
    return s

print (indices('superimposed self-imposed', 'impose'))

def has(haystack, needle):
    n = len(needle)
    f = needle[0]
    s = []
    for i, x in enumerate(haystack):
        if x == f:
            if haystack[i:n + i] == needle:
                s.append(i)
    return s or False

print (has('superimposed self-imposed', 'impose'))
print (has('superimposed self-imposed', 'imposter'))
s = has('superimposed self-imposed', 'impose')
print (s and True)
s = has('superimposed self-imposed', 'imposter')
print (s and True)

# without slicing or enumerate
def has_in(haystack, needle):
  k = range(len(needle))
  h = range(len(haystack))
  f = needle[0]
  r = False
  for i in h:
    if haystack[i] == f:
      for j in k:
        if haystack[i + j] == needle[j]:
          r = True
          continue
        else:
          r = False
          break
      if r: return r
  return r

print (has_in('superimposed self-imposed', 'impose'))
print (has_in('superimposed self-imposed', 'imposter'))

def has_at(haystack, needle):
  k = range(len(needle))
  h = range(len(haystack) - k[-1])
  f = needle[0]
  r = False
  s = []
  for i in h:
    if haystack[i] == f:
      for j in k:
        if haystack[i + j] == needle[j]:
          r = True
          continue
        else:
          r = False
          break
      if r:
        s.append(i)
        
  return s or r

print (has_at('superimposed self-imposed impose', 'impose'))
print (has_at('superimposed self-imposed impose', 'imposter'))
print (has_at('superimposed self-imposed impose', 'super'))