[Tutor] manually sorting variables
Alan Gauld
alan.gauld at btinternet.com
Fri Sep 7 09:08:05 CEST 2007
"Christopher Spears" <cspears2002 at yahoo.com> wrote
> 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.
Hmm, the restriction of not using a sorting algorithm is interesting.
But if you only have three values its doable. With more than three
I'm not sure how it would be done.
> def smallest_var(x,y):
So you can get the smallest var.
Now if you could get the biggest then the one that's neither must
be in the middle.
You are then left with selecting one of 6 possible outcomes:
1,2,3,
1,3,2
2,1,3
2.3.1,
3,1,2
3,2,1
Does that help?
Alternatively you could write a comparison function rather than a
get smallest/get biggest. That way you can compare the original
variables rather than creating new ones.
> var1 = raw_input("Enter a number for var1: ")
> var2 = raw_input("Enter a number for var2: ")
> var3 = raw_input("Enter a number for var3: ")
You should convert these to integers!
> small = smallest_var(var1, var2)
> #print small_var_1
> smallest = smallest_var(small, var3)
> print smallest
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list