Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """Write a program to prompt the user to enter 5 strings which you will store in a
- list. The program should then sort the input into alphabetical order and then
- output it.
- Write the code necessary to prompt the user for the required data and output
- the sorted data.
- Run the program and input appropriate data taking a screen shot of your
- output. Call your screenshot alphabetical.jpg."""
- #function to sort list
- def sort(unsorted_list):
- sorted = False #enter the while loop
- while not sorted:
- sorted = True # if we make no swaps this will stay true and we will know we have sorted the list
- for i in range(len(unsorted_list)-1):
- if unsorted_list[i][0] > unsorted_list[i+1][0]: #compare first letter of current and next element
- temp = unsorted_list[i]
- unsorted_list[i] = unsorted_list[i+1] #swap if nessecery
- unsorted_list[i+1] = temp
- sorted = False # if we made a swap trip the flag
- for j in range(len(unsorted_list[i])-1): #nested for loop to check for remaining letter
- if unsorted_list[i][j] == unsorted_list[i+1][j]: # i think this for loop logic is flawed
- if unsorted_list[i][j+1] > unsorted_list[i+1][j+1]:
- temp = unsorted_list[i]
- unsorted_list[i] = unsorted_list[i+1]
- unsorted_list[i+1] = temp
- sorted = False
- return unsorted_list
- #get 5 strins from user and add them to a list
- '''uncomment these lists to test'''
- #list_of_strings = ["bb", "ab", "aa", "ca", "ba"]
- list_of_strings = ["bba", "bbb", "aa", "cab", "baa","aaa", "abc"] # this gets stuck
- #list_of_strings = ["bba", "bbb", "aa", "cab", "baa","aaa", "caa"] #this one works
- # for i in range(5):
- # user_input = input(f"Enter string {i+1} of 5: ")
- # list_of_strings.append(user_input)
- #sort list alphabetically
- sorted_list = sort(list_of_strings)
- print(sorted_list)
Advertisement
Advertisement