1

I have a list of all combinations of word HACK like this:

lista = ['H', 'A', 'C', 'K', 'HA', 'HC', 'HK', 'AC', 'AK', 'CK']

I tried sorting the above using :

lista.sort(lambda x,y:cmp(len(x),len(y)))

gives me the same result.

How can I sort with both the length and alphabetically.

Expected Output:

['A', 'C', 'H', 'K', 'AC', 'AH', 'AK', 'CH', 'CK', 'HK']

Update:

from itertools import combinations
inp = "HACK 2".split(" ")
lista = []
for i in range(1,int(inp[1])+1):

    for item in list(combinations(inp[0],i)):

        lista.append("".join(item))

lista = sorted(lista, key=lambda x: (len(x), x))

print lista

#Output
['A', 'C', 'H', 'K', 'AC', 'AK', 'CK', 'HA', 'HC', 'HK']

#Expected Output
['A', 'C', 'H', 'K', 'AC', 'AH', 'AK', 'CH', 'CK', 'HK']

Also is there anything wrong with how I am iterating the combinations ?

bhansa
  • 7,282
  • 3
  • 30
  • 55

2 Answers2

1

list.sort, sorted accept an optional keyword argument key. Return value of the key function is used to compare elements instead of the elements themselves.

For your case, you can use a key function that returns a tuple of (length, string itself):

>>> lista = ['H', 'A', 'C', 'K', 'HA', 'HC', 'HK', 'AC', 'AK', 'CK']
>>> sorted(lista, key=lambda x: (len(x), x))
['A', 'C', 'H', 'K', 'AC', 'AK', 'CK', 'HA', 'HC', 'HK']
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • please check the update. – bhansa Apr 27 '17 at 08:55
  • @Bhansa, Replace `for item in list(combinations(inp[0],i)):` with `for item in list(combinations(sorted(inp[0]),i)):` (In other word, you should pass sorted items to `itertools.combinations`). If you have another question, please post a separate question. – falsetru Apr 27 '17 at 12:56
1

You want to sort not just the lista list, but also all the strings in it. So

>>> lista = ['H', 'A', 'C', 'K', 'HA', 'HC', 'HK', 'AC', 'AK', 'CK']
>>> for i, string in enumerate(lista):           
...     lista[i] = ''.join(sorted(list(string))) 
...                                              
>>> lista                                        
['H', 'A', 'C', 'K', 'AH', 'CH', 'HK', 'AC', 'AK', 'CK']                                   
>>> lista.sort(key=lambda s: (len(s), s))        
>>> lista                                        
['A', 'C', 'H', 'K', 'AC', 'AH', 'AK', 'CH', 'CK', 'HK']
Andrew Che
  • 928
  • 7
  • 20