Search code examples
pythonpython-3.xliststring-length

Adding certain lengthy elements to a list


I'm doing a project for my school and for now I have the following code:

def conjunto_palavras_para_cadeia1(conjunto):
acc = []
conjunto = sorted(conjunto, key=lambda x: (len(x), x))

def by_size(words, size):
    result = []
    for word in words:
        if len(word) == size:
            result.append(word)
    return result

for i in range(0, len(conjunto)):
    if i > 0:
        acc.append(("{} ->".format(i)))
        acc.append(by_size(conjunto, i))

acc = ('[%s]' % ', '.join(map(str, acc)))
print( acc.replace(",", "") and acc.replace("'", "") )


conjunto_palavras_para_cadeia1(c)

I have this list: c = ['A', 'E', 'LA', 'ELA'] and what I want is to return a string where the words go from the smallest one to the biggest on in terms of length, and in between they are organized alphabetically. I'm not being able to do that...

  • OUTPUT: [;1 ->, [A, E], ;2 ->, [LA], ;3 ->, [ELA]]
  • WANTED OUTPUT: ’[1->[A, E];2->[LA];3->[ELA]]’

Solution

  • Taking a look at your program, the only issue appears to be when you are formatting your output for display. Note that you can use str.format to insert lists into strings, something like this:

    '{}->{}'.format(i, sublist)
    

    Here's my crack at your problem, using sorted + itertools.groupby.

    from itertools import groupby
    
    r = []
    for i, g in groupby(sorted(c, key=len), key=len):
        r.append('{}->{}'.format(i, sorted(g)).replace("'", ''))
    
    print('[{}]'.format(';'.join(r)))
    [1->[A, E];2->[LA];3->[ELA]]
    

    A breakdown of the algorithm stepwise is as follows -

    • sort elements by length
    • group consecutive elements by length
    • for each group, sort sub-lists alphabetically, and then format them as strings
    • at the end, join each group string and surround with square brackets []