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

Finding words of the same length

I am new to programming and I am trying to figure out this problem. I have a list of elements and I want to find words that have the same length. This is what I’ve tried:

list1 = ["dog","cat","people","tank","pop","joop","count"]    
list3 = []

for i in range(len(list1)):   
    for j in range(len(list1):    
        if len(list1[i]) == len(list1[j]):    
            list3.append(list[i])
return list3

I want to return list3 = [ "dog","cat","joop","tank"] because each word in this last has the same length as at least one other word in the list.

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

>Solution :

My advice for situations like this is to use a map rather than using a list:

list1 = ["dog","cat","people","tank","pop","joop","count"]     
results = {}
for item in list1:
    length = len(item)
    if length in results:
        results[length].append(item)
    else:
        results[length] = [item]

print(results) # {3: ['dog', 'cat', 'pop'], 6: ['people'], 4: ['tank', 'joop'], 5: ['count']}

This works by iterating over all words in list1, getting the number of characters in each and adding it to the dictionary entry associated with that length. You can then filter that dictionary for entries that contain more than one word:

import itertools
filtered = list(itertools.chain(*filter(lambda v: len(v) > 1, results.values())))
print(filtered) # ['dog', 'cat', 'pop', 'tank', 'joop']

This code works by calling the filter function with a lambda that checks if the value associated with each key (length) has more than one value, and then chaining these sub-lists together into a single list, which is returned. For more information on how itertools.chain works and why I included the *, see this answer.

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