[Tutor] manually sorting variables
Kent Johnson
kent37 at tds.net
Fri Sep 7 03:12:49 CEST 2007
Christopher Spears wrote:
> I'm working out of Core Python Programming (2nd
> Edition) by Wesley Chun.
>
> Here is the problem:
>
> Have the user enter three numeric values and store
> them in three different variables. Without using
> lists or sorting algorithms, manually sort these three
> numbers from smallest to largest.
>
> Here is what I have so far:
> #!/usr/bin/env python
>
> def smallest_var(x,y):
> if x < y:
> return x
> elif y < x:
> return y
> else:
> print "x equals y"
>
> var1 = raw_input("Enter a number for var1: ")
> var2 = raw_input("Enter a number for var2: ")
> var3 = raw_input("Enter a number for var3: ")
>
> small = smallest_var(var1, var2)
> #print small_var_1
> smallest = smallest_var(small, var3)
> print smallest
>
> I'm not sure what the next step would be. If I was
> using a list, I could try to remove the smallest
> variable and then just compare the two remaining
> variables. Any hints?
Do you know how to do a bubble sort? You could use comparison and
swapping to sort the values so x is the smallest, y is the middle and z
is the largest. I think it can be done with three comparisons and three
or fewer swaps. Think of x, y and z as the three positions of a list.
Kent
More information about the Tutor
mailing list