Assistance on a Python program: Your program should contain the following functi
ID: 3685363 • Letter: A
Question
Assistance on a Python program:
Your program should contain the following functions:
• read_names: Takes no parameters. Prompts the user for names until the user enters a blank line. Returns a list of the names the user entered (not including the blank line). Each line of user input should count as a single name, even if it has multiple words.
For example: Enter a name: Ilana Wexler
Enter a name: Abbi Abrams
Enter a name:
should return the list [ 'Ilana Wexler', 'Abbi Abrams']
is_sorted: Takes a list of strings as a parameter. Should return True if the list is in alphabetical order (A-Z) and False otherwise. Remember that, if strings s1 and s2 are the same case (upper or lower), s1 < s2 will be True if s1 comes first alphabetically. Don’t try to pull out the last names – just sort the strings as the user typed them
average length: Takes a list of strings as a parameter, and returns the average length (in characters) of the strings in the list. Spaces count as characters
main: Calling your other functions whenever possible, this function should get a list of names from the user (stopping when the user enters a blank line). It should then print the following:
– The string that comes last alphabetically (only if the list is sorted)
– All of the strings whose lengths are greater than the average length
Explanation / Answer
def read_names(): # input string function
list = []
while True:
entered = raw_input("Enter string or leave a blank line to quit: ")
if entered == " ":
break
if len(entered) == 0:
break
list.append(entered)
print list
return list
def is_sorted(list): # function to check if list is sorted
if sorted(list) == list:
return True
else:
print False
def average_length(list): # function to find average length of list
all_lengths = []
num_of_strings = len(list)
for item in list:
string_size = len(item)
all_lengths.append(string_size)
total_size = sum(all_lengths)
ave_size = float(total_size) / float(num_of_strings)
return ave_size
def main():
list = read_names() # input list
if is_sorted(list) == True: # checking if list is sorted
print "List is sorted, last string is: "
print list[-1]
else:
print "List is not sorted"
avg = average_length(list) # find average length
print "average length: "
print avg
print "strings having size greater than average size are: "
for item in list:
string_size = len(item)
if string_size > avg:
print item # print string whose size is greater than average
main()
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.