Use python and write code for problem. The question requires a text file USPres.
ID: 3843941 • Letter: U
Question
Use python and write code for problem. The question requires a text file USPres.txt, so i put the image of the contents of the text file. Please also put screenshot of the code. Thanks.
63. U.S. Presidents The file USPres.txt contains the names of the first 44 U.S. presi dents in the order they served. Write a program that places the names in a list, sorts the list by the lengths of the presidents' first names in ascending order, and displays the names of the first six presidents in the list. See Fig. 4.25.Explanation / Answer
text_file = open("filename.dat", "r") #open any file you want in read mode
list=[]
lines = text_file.readlines() # get array of lines
for line in lines #iterate over all lines
list.append(line) # push all line to list where ech line contains first name and last name
print list
#print sorted(list, key=len)
#list.sort(key=lamda s:len((s.split("\s"))[0]))
list.sort(key = lambda x: len(x.split(" ")[0])) # this lamda expresion says that first split over space and get
#firstname then get length of first name as key
print list[0]
print list[1]
print list[2]
print list[3]
print list[4]
print list[5]
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.