[Tutor] can someone explain to me how this works
Kirk Bailey
idiot1 at netzero.net
Wed Oct 22 00:41:29 EDT 2003
I will give it a shot. Try not to laugh too hard if I mung it into kruftyness.
Conrad Koziol wrote:
> Hey thanks for the tips !!!
>
> def compare(a,b):
> if a[1]>b[1]: return 0
> else: return -1
>
ok. a[1] returns a char from a string, or a number in a list or tuple of
numbers. So does b[1]. I am ASSUMING they are numbers in a list or tuple. Look
at the values they would return.
if a[1]=12, and b[1]=4, well, 12>4 is true, so it would return a 1, which is a
logical TRUE. so the condition after the test would happen, which is 'return 0',
so your function ends, returning the value 0. now a -1 would be returned if the
test was NOT true, by executing the other leg in the if/else structure.
First, it's neater to put the conditional after a if statement indented on the
next line, and I cannot gurantee that placing it on the SAME line as the test
will work in future versions of python. so let's do this:
def compare(a,b):
if a[1]>b[1]:
return 0
else:
return -1
This is your function, nice nad neat and quite properly pythonesque. But we can
make it easier.
def compare(a,b):
return not a[1]>b[1]
Not inverts the logical vallue of a returned logical value.
Again, a[1]=12 and b[1]=4. with this test, and those values, the return is 0.
Were the values reversed, this would be a 1 return, which is true, as is a -1
return value. IF the value HAS to be 0 or -1, we need to define the function
with customized values. And a simple way to do it is:
def compare(a,b):
return (a[1]>b[1])-1
Dig; if true, the returned value of a test is 1. If false, it is 0. These are
plain old fashioned interger values, and you can do basic math on them just
fine. Subtract 1 from that result, and you get 0 and -1 respectively. Python
treats 0 as false, and any non 0 value as true, therefore the logic holds and
you get your desired result faster and simpler.
Any discussion gang?
> i tried this out and it works, but i dont understand the logic behind it
> :(
> can someone help me out
>
> i also dont get how it compares all the tuples in a list. Dont you need to enter
> in two values not just one list?????
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
--
--
end
Cheers!
Kirk D Bailey
+ think +
http://www.howlermonkey.net +-----+ http://www.tinylist.org
http://www.listville.net | BOX | http://www.sacredelectron.org
Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus
+ kniht +
Fnord.
More information about the Tutor
mailing list