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']
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']
Just remove the -1 from range(len(words)-1)
This will be the minimal change in your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With