1

is there a method in python that would check for that and it has to be in the same order.

a = ['a', 'b', 'c']
b = ['b', 'c']

if a contains b:
   c = remove b from a

c = ['a']

and if b = ['c', 'b'] c should be equal to a, c = ['a', 'b', 'c']

Thank you so much for your help in advance!

Blake Gibbs
  • 485
  • 1
  • 9
  • 25

2 Answers2

2

I would solve this problem in two steps:

  1. Find the index of the sublist.

  2. Remove the sublist given its index in the list.

To find the index of the sublist you can do this:

def index(l, s):
    len_s = len(s)
    for pos in range(len(l) - len_s + 1):
        if l[pos:pos + len_s] == s:
            return pos
    return -1

It's not as efficient as Boyer-Moore but it will work for now. Once you have the index, you can simply delete the slice. So your code becomes:

a = ['a', 'b', 'c']
b = ['b', 'c']

pos = index(a, b)
if pos >= 0:
    c = list(a)
    del c[pos:pos + len(b)]

# c = ['a']
  • if a is ['rtz', 'qwe', 'asd', 'qwe'] and b is ['asd', 'qwe'] it yields ['r', 't', 's', 'd', ' ', 'q', 'w', 'e'] but the result should be ['rtz', 'qwe'] – Blake Gibbs Sep 01 '14 at 18:44
  • It works for me. Try this in your interpreter: `a = ['rtz', 'qwe', 'asd', 'qwe']; b = ['asd', 'qwe']; pos = index(a, b); c = a[:]; del c[pos:pos + len(b)]; c` – Lloyd Grant Sep 01 '14 at 18:53
  • hmm, strange I wonder what I did back there ;), seems to work now thanks! – Blake Gibbs Sep 01 '14 at 19:06
1

If your list only contains characters, you can definitely write

print ''.join(b) in ''.join(a)

Output:

True

This does not work, e.g. if a = ['abc', 'def', 'ghi'] and b = ['bc', 'd']. It yields True, because bcd is in abcdefghi.

But you can write:

print '@'+'@'.join(b)+'@' in '@'+'@'.join(a)+'@'

In case a or b contain items with character '@' you might replace it by some unused character.

Falko
  • 17,076
  • 13
  • 60
  • 105