Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to sort given strings (Strings starting with x first)

Code doesn't return last word when given ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] list.

def front_x(words):
    x_list = []
    no_x_list = []
    [x_list.append(i) for i in words if i[0] == "x"]
    [no_x_list.append(words[i2]) for i2 in range(len(words)-1) if words[i2] not in x_list]
    x_list.sort()
    no_x_list.sort()
    return x_list + no_x_list
print front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark'])

Must be:

['xanadu', 'xyz', 'aardvark', 'apple', 'mix']

With lists ['bbb', 'ccc', 'axx', 'xzz', 'xaa'] and ['ccc', 'bbb', 'aaa', 'xcc', 'xaa'] everything is right ['xaa', 'xzz', 'axx', 'bbb', 'ccc'] and ['xaa', 'xcc', 'aaa', 'bbb', 'ccc']

like image 817
Lorrain Avatar asked Mar 13 '26 00:03

Lorrain


2 Answers

Iterating on range(len(words)-1) looks incorrect. More so, making list appends with list comprehension is quite unpythonic; list comps are for building lists not making making list appends which is rather ironic here.

You can perform the sort once by sorting based on a two-tuple whose fist item checks if a word startswith 'x' and puts those ahead. The second item in the tuple applies a lexicograhical sort on the list, breaking ties:

def front_x(words):
    return sorted(words, key=lambda y: (not y.startswith('x'), y))

print front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark'])
# ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
like image 103
Moses Koledoye Avatar answered Mar 15 '26 12:03

Moses Koledoye


Just remove the -1 from range(len(words)-1) This will be the minimal change in your code.

like image 36
Cuber Avatar answered Mar 15 '26 12:03

Cuber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!