I tried to solve with set in python .
for most case my code works.
class Solution:
def findWords(self, words: List[str]) -> List[str]:
set_top = {'q','w','e','r','t','y','u','i','o','p'}
set_mid = {'a','s','d','f','g','h','j','k','l'}
set_low = {'z','x','c','v','b','n','m'}
for i in words:
set_i = set(i.lower())
if set_i-set_top and set_i-set_mid and set_i-set_low :
words.pop(words.index(i))
return words
I dont know where i went wrong.
refer image for test case failed
>Solution :
You’re removing items from the same list you’re iterating over.
Better would be to only collect the ones that do match, and return those:
def answer():
...
valid_words = []
for word in words:
if ...:
valid_words.append(word)
return valid_words
adding a couple of debugging prints shows this more clearly:
In [81]: findWords(['abdfs', 'cccd', 'a', 'qwwewm'])
0: words = ['abdfs', 'cccd', 'a', 'qwwewm'], word=abdfs
removing abdfs: 0
1: words = ['cccd', 'a', 'qwwewm'], word=a
2: words = ['cccd', 'a', 'qwwewm'], word=qwwewm
removing qwwewm: 2
Out[81]: ['cccd', 'a']
It never actually checks cccd because you’ve fiddled with the list context and the iterator skips over it.