[Tutor] Example 1
Magnus Lycka
magnus@thinkware.se
Wed Dec 11 04:08:08 2002
At 22:22 2002-12-10 -03-30, Adam Vardy wrote:
>I can follow the meaning of the following function. Should be simple,
>so, want to explain?
Sure!
>def union(*args):
I assume you understand the basic "def" statement. The odd thing here
is the * before args. Python has some special features in that regard.
Typically, you do
def f(x,y):
return x + y
But sometimes you don't know how many arguments to expect.
Then you can use the *-form, like this:
>>> def f(x,y,*more):
... print "x=", x, "y=", y, "the rest=", more
...
>>> f(1,2)
x= 1 y= 2 the rest= ()
>>> f(1,2,3)
x= 1 y= 2 the rest= (3,)
>>> f(1,2,3,4,5,6,7)
x= 1 y= 2 the rest= (3, 4, 5, 6, 7)
This means that you can construct more flexible functions in python.
You might feel that it's not needed in Python (in contrast to C for
instance), since you might as well pass a list or a tuple as an argument
to a function, but sometimes this is a more convenient approach.
There is more to learn that we don't need to explain the stuff below, see
http://www.python.org/doc/current/tut/node6.html#SECTION006700000000000000000
> res = []
This is what we return below. An empty list that will append something
to before we get to the return line. Let's see below:
> for seq in args:
We loop through our function call arguments, however many they are.
From the variable name "seq" we can make a guess that the next line
of code validates: Every argument in the function call should be a
sequence, i.e. something we can loop over with a for-loop.
In other words, we expect that the function call looks something like
"union([1,4,6],(5,6,4),[2,3,4])" or perhaps "union('strings','are',
'also','sequences')".
> for x in seq:
For each sequence, loop over the elements (x) in the sequence.
> if not x in res:
If the sequence element (x) is not already in the result list...
> res.append(x)
...put it there
> return res
And finally return a list containing only one copy each of
every element that was in any of the sequences
So...
>>> union([1,4,6],(5,6,4),[2,3,4])
[1, 4, 6, 5, 2, 3]
>>> x = union('strings','are','also','sequences')
>>> print "".join(x)
stringaeloquc
OK?
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se