[Tutor] bubble sort function

Danny Yoo dyoo at hashcollision.org
Mon Nov 17 05:20:46 CET 2014


Hi Spyros,

Ok, reading the code...

> def bubbleSort_ascending(unsorted):
>     """ Sorts a list of numbers in ascending order """
>     n = len(unsorted)
>     count = swaps = 0
>     swapped = True
>     ## Prompt user to choose if they want to see each sorting step
>     option = raw_input("Show sorting steps? (Y/N):\n")
>     while swapped:
>         count += 1
>         swapped = False
>         for i in range(1, n):
>             if unsorted[i-1] > unsorted[i]:
>                 unsorted[i-1], unsorted[i] = unsorted[i], unsorted[i-1]
>                 swapped = True
>         ## Catch user input and either show or hide sorting steps
> accordingly
>         if option in ("Y", "y"):
>             print "\nIteration %d, %d swaps; list: %r\n" %(count, swaps,
> unsorted)
>         elif option in ("N", "n"):
>             pass
>         else:
>             print "\nYour input was invalid, type either Y/y or N/n"
>     return unsorted


Hmmm.  Something looks off with regards to the checking of "option".
There's the reading of the variable:


>     option = raw_input("Show sorting steps? (Y/N):\n")


and the checking for the validity of the value:


>         if option in ("Y", "y"):
>             print "\nIteration %d, %d swaps; list: %r\n" %(count, swaps,
> unsorted)
>         elif option in ("N", "n"):
>             pass
>         else:
>             print "\nYour input was invalid, type either Y/y or N/n"


where the validity checking is mingled with the usage of the value.
If you give an invalid input, you'll keep seeing "Your input was
invalid..." throughout the running of the bubblesort, and that seems
off.  The core issue is: we should have known beforehand, even before
doing anything bubblesorty, that the option wasn't good.



We might consider doing the validity testing just once and up front.
One way to  do this is to write a helper function that keeps asking
over and over, till it gets an acceptable value.  For example, here's
a function that keeps asking for a digit.  Once it gets one, it
returns the integer value of that digit:

#################################################
def ask_for_a_digit():
    while True:
        digit = raw_input("Give me a digit between 0 and 9.")
        if digit not in "0123456789":
            print "You didn't give me a digit.  Try again."
        else:
            return int(digit)
#################################################

So the checking and converting from string to integer is done all up
front.  When we get a value back from ask_for_a_digit(), we know it's
going to be an integer between 0 and 9.  Try ask_for_a_digit() out and
see how it behaves.


You can write a similar helper function to prompt for yes or not, and
return a boolean when the user provides something acceptable.  Then
your show-or-hide of sorting steps doesn't have to deal with arbitrary
strings: it can just deal with True or False.


More information about the Tutor mailing list