Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

using python3 #!/usr/bin/python3 from test import test def front_x(words): \'\'\

ID: 3758820 • Letter: U

Question

using python3

#!/usr/bin/python3

from test import test


def front_x(words):
'''Given a list of strings, return a list of strings sorted in increasing
order, except group all the string that begin with 'x' first. See test
cases for examples.

YOU MUST USE LIST COMPREHENSION.

Hint: You can separate into 2 lists (one with 'x' first and other without
'x' first), sort each of them, then combine them.

Keyword arguments:
words -- a list of strings

Return: list
'''
# +++ADD code here+++


def main():
'''Provide some tests for front_x function'''
print('front_x')
test(front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa']),
['xaa', 'xzz', 'axx', 'bbb', 'ccc'])
test(front_x(['ccc', 'bbb', 'aaa', 'xcc', 'xaa']),
['xaa', 'xcc', 'aaa', 'bbb', 'ccc'])
test(front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark']),
['xanadu', 'xyz', 'aardvark', 'apple', 'mix'])


if __name__ == '__main__':
main()

Explanation / Answer

def front_x(words):
    listx = []
    otherlist = []

    for word in words:
        if(word.startswith("x")):
            listx.append(word)
  
        else:
            otherlist.append(word)
         
          
    listx.sort()
    otherlist.sort()
    result = listx + otherlist
    return result


print('front_x')
print(front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa']))
print (front_x(['ccc', 'bbb', 'aaa', 'xcc', 'xaa']))
print(front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark']))

---output-----------

sh-4.3$ python main.py                                                                                                                 

front_x                                                                                                                                

['xaa', 'xzz', 'axx', 'bbb', 'ccc']                                                                                                    

['xaa', 'xcc', 'aaa', 'bbb', 'ccc']                                                                                                    

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