Advertisement
KDT85

alphabetical_sort.py

Nov 28th, 2022 (edited)
91
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.02 KB | None | 0 0
  1. """Write a program to prompt the user to enter 5 strings which you will store in a
  2. list. The program should then sort the input into alphabetical order and then
  3. output it.
  4. Write the code necessary to prompt the user for the required data and output
  5. the sorted data.
  6. Run the program and input appropriate data taking a screen shot of your
  7. output. Call your screenshot alphabetical.jpg."""
  8.  
  9. #function to sort list
  10. def sort(unsorted_list):
  11.     sorted = False #enter the while loop
  12.     while not sorted:
  13.         sorted = True # if we make no swaps this will stay true and we will know we have sorted the list
  14.         for i in range(len(unsorted_list)-1):  
  15.             if unsorted_list[i][0] > unsorted_list[i+1][0]: #compare first letter of current and next element
  16.                 temp = unsorted_list[i]
  17.                 unsorted_list[i] = unsorted_list[i+1] #swap if nessecery
  18.                 unsorted_list[i+1] = temp
  19.                 sorted = False # if we made a swap trip the flag
  20.             for j in range(len(unsorted_list[i])-1): #nested for loop to check for remaining letter
  21.                     if unsorted_list[i][j] == unsorted_list[i+1][j]: # i think this for loop logic is flawed
  22.                         if unsorted_list[i][j+1] > unsorted_list[i+1][j+1]:
  23.                             temp = unsorted_list[i]
  24.                             unsorted_list[i] = unsorted_list[i+1]
  25.                             unsorted_list[i+1] = temp
  26.                             sorted = False
  27.     return unsorted_list
  28.            
  29.  
  30. #get 5 strins from user and add them to a list
  31. '''uncomment these lists to test'''
  32. #list_of_strings = ["bb", "ab", "aa", "ca", "ba"]
  33. list_of_strings = ["bba", "bbb", "aa", "cab", "baa","aaa", "abc"]   # this gets stuck
  34. #list_of_strings = ["bba", "bbb", "aa", "cab", "baa","aaa", "caa"]  #this one works
  35. # for i in range(5):
  36. #     user_input = input(f"Enter string {i+1} of 5: ")
  37. #     list_of_strings.append(user_input)
  38.  
  39.  
  40. #sort list alphabetically
  41. sorted_list = sort(list_of_strings)
  42. print(sorted_list)
Advertisement
Comments
Add Comment
Please, Sign In to add comment
Advertisement