retrieve all the smallest strings from a set in python

221 views Asked by At

I have a set which looks like

set(['A', 'BF', 'B', 'BA', 'ABF', 'AF', 'F', 'BFA', 'AFB', 'BAF', 'FA', 'FB', 'AB', 'FAB', 'FBA'])

and I'm trying to get all Strings which has the smallest length into a list I tried using

print min((element for element in getParts(working_scheme,k)), key=len)

which just prints Abut I need ['A', 'B', 'F']

Ho can I accomplish this?

4

There are 4 answers

2
nu11p01n73R On BEST ANSWER

Something like

>>> a_set = set(['A', 'BF', 'B', 'BA', 'ABF', 'AF', 'F', 'BFA', 'AFB', 'BAF', 'FA', 'FB', 'AB', 'FAB', 'FBA'])
>>> min_len = min( len(x) for x in a_set  )
>>> [ x for x in a_set if len(x) == min_len ]
['A', 'B', 'F']

To split it up

  • min_len = min( [ len(x) for x in a_set ] ) returns the minimum of the lengths.

  • [ x for x in a_set if len(x) == min_len ] List comprehension, returns a list of elements which has length equals to min_len

0
Martijn Pieters On

min() will only ever retrieve one result.

You'll have to code your own if you want to retrieve all shortest results:

shortest = []
shortest_length = float('inf')
for element in getParts(working_scheme, k):
    if len(element) < shortest_length:
        shortest = [element]
        shortest_length = len(element)
    elif len(element) == shortest_length:
        shortest.append(element)

This loops over the set just the once.

2
Tanveer Alam On
data = set(['A', 'BF', 'B', 'BA', 'ABF', 'AF', 'F', 'BFA', 'AFB', 'BAF', 'FA', 'FB', 'AB', 'FAB', 'FBA'])

_len = len(sorted(data, key=len)[0])
print filter(lambda x:len(x)==_len, data)

Returns:

['A', 'B', 'F']
0
monkut On

Another method using a dictionary:

from collections import defaultdict

items = set(['A', 'BF', 'B', 'BA', 'ABF', 'AF', 'F', 'BFA', 'AFB', 'BAF', 'FA', 'FB', 'AB', 'FAB', 'FBA'])
d = defaultdict(list)
for item in items:
    d[len(item)].append(item)
results = d[min(d)]

results: ['A', 'B', 'F']