Home > Software engineering >  Sorting Letters in Alphabetical Order
Sorting Letters in Alphabetical Order

Time:10-11

I'm trying to solve this problem but I keep getting the error message that the variable median is referenced before the assignment. Thank you!! "Please write a program which asks the user for three letters. The program should then print out whichever of the three letters would be in the middle if the letters were in alphabetical order."

L1 = input("1st letter: ")
L2 = input("2nd letter: ")
L3 = input("3rd letter: ")

if L1>L2:
    if L1<L3:
        median = L1
    elif L2>L3:
        median = L2
    else:
        median = L3
print(f"The letter in the middle is,{median}")

CodePudding user response:

A trivial solution is to simply assign something to median before your if statements:

median = None
if L1 > L2:
    ...

This will fix your proximal error, but your overall program will still misbehave - you haven't handled the case where L1 is less than L2. You have to handle each of the logical cases:

* L1 is less than L2 is less than L3. (L2 is median)
* L1 is less than L3 is less than L2. (L3 is median)
* L2 is less than L1 is less than L3. (L1 is median)
* L2 is less than L3 is less than L1. (L3 is median)
* L3 is less than L1 is less than L2. (L1 is median)
* L3 is less than L2 is less than L1. (L2 is median)

As you can see, there are six cases here - you're only covering three of them.

But there is another way as well, which can take advantage of the fact you are aware of both the length of your list and can sort them:

ls = [L1, L2, L3]  # Unsorted list of inputs.
sorted_ls = sorted(ls)  # Sorted list of inputs.
print(f"Median: {sorted_ls[1]}")  # Median is always at index 1.

By using sorting you can move the median into a predictable place, and leverage that without having to have a complex and brittle set of if statements.

From the REPL:

>>> L1 = "Y"
>>> L2 = "X"
>>> L3 = "Z"
>>> ls = sorted([L1, L2, L3])
>>> ls[1]
'Y'
>>> ls
['X', 'Y', 'Z']
  • Related