'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']
Solution 1:[1]
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']
Solution 2:[2]
Just remove the -1 from range(len(words)-1)
This will be the minimal change in your code.
Solution 3:[3]
You can try this:
words = ['mix', 'xyz', 'apple', 'xanadu', 'aardvark']
new_words = [i for i in words if i[0].lower() == "x"]
words = [i for i in words if i[0].lower() != "x"]
final_words = sorted(new_words)+sorted(words)
print(final_words)
Output:
['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
Solution 4:[4]
You have to use len(words) instead of len(words)-1 to get expected output.
So, try this way :
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)) 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'])
Output :
['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Cuber |
| Solution 3 | Ajax1234 |
| Solution 4 | Md. Rezwanul Haque |
