Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why my set approach works in some cases and failed in others?

Leetcode 500

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Test case 14 failed image

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading