Search code examples
pythonalphabeticalnames

How to list alphabetically in this way?


I have to sort the user inputted names without using the list sort method. this is what i have so far but am having issues with defining 'one' 'two' and 'three'. i need the program to go through each letter to make sure it is truly alphabetical. can anyone help?

name1=str(input("Enter name #1: "))
name2=str(input("Enter name #2: "))
name3=str(input("Enter name #3: "))

one = name1[0].upper() + name1[1].upper() + name1[2].upper()
two = name2[0].upper() + name2[1].upper() + name2[2].upper()
three = name3[0].upper() + name3[1].upper() + name3[2].upper()

if one < two and two < three:
     print("These names in alphabetical order are: ", name1, name2, name3)
elif one < two and three < two:
     print("These names in alphabetical order are: ", name1, name3, name2)     
elif two < three and three < one:
     print("These names in alphabetical order are: ", name2, name3, name1)
elif two < one and one < three:
     print("These names in alphabetical order are: ", name2, name1, name3)
elif three < two and two < one:
     print("These names in alphabetical order are: ", name3, name2, name1)
else:
     print("These names in alphabetical order are: ", name3, name1, name2)

thanks in advance! edit my issue is in defining 'one' 'two' and 'three' it needs to run through all of the letters in the input. right now it runs through the first three letters but if i add the next letter and only a three letter name is given it errors. and if i use the len function it tells me its an integer


Solution

  • i need the program to go through each letter to make sure it is truly alphabetical.

    That's what string comparison does anyway. The problem with your code is that you restrict one, two and three to the first three letters of the input strings. Instead, you should just uppercase the entire name and compare those.

    name1 = input("Enter name #1: ")  # no need for str(...)
    ... # same for name2, name3
    
    one = name1.upper()  # uppercase whole nam, not just first three letters
    ... # same for two, three
    
    answer = "These names in alphabetical order are: "  # don't repeat this X times
    if one < two < three:  # comparison chaining
        print(answer, name1, name2, name3)
    elif one < three < two:
        print(answer, name1, name3, name2)
    elif ...:
        # a whole bunch more
    else:
        print(answer, name3, name2, name1)