[Tutor] grrrr!

Karl Pflästerer sigurd at 12move.de
Fri Feb 13 16:15:16 EST 2004


On 13 Feb 2004, Christopher Spears <- cspears2002 at yahoo.com wrote:

> I'm writing some code that examines a directory and
> creates two lists.  One is a list of all the files in
> the directory excluding other directories and links
> along with the size of the files.  The result should
> look something like this:
> [[['openunit4.pyw', 48L], ['printlongestline.pyw',
> 214L]...]]

> I have suceeded in making this work.  The next list
> should just contain the largest file in the directory
> and look like this:

> [[huge_file, 247L]]

[Code]

> I think I need some sort of second condition in the if
> statement, but I have problems comparing s to
> biggest[0][1].  I always get an index out of range
> error.

I looked at your code and saw you like functional programming style
(very good).  Here is a bit shorter version of your code.

def get_size(dir):
    import os
    files_size = [(f, os.path.getsize(f)) for f in os.listdir(dir)
                  if not os.path.isdir(f) or os.path.islink(f)]
    biggest = reduce(lambda pair1, pair2: pair1[1] > pair2[1] and pair1 or pair2, files_size)
    return (files_size, biggest)

The list with files and the corresponding size gets build with one list
comprehension.  I use here tuples for these pairs (IMO they are better
than lists here).  Then reduce() is used to find the biggest element
(size) in the list; the lambda expression compares the sizes of two
pairs and returns the pair with the bigger size (if they are equal in
size the second pair is returned).  The result is the pair with the
biggest file size.  Finally the function returns a tuple: the list of
files and the pair with the biggest file size.



   Karl
-- 
Please do *not* send copies of replies to me.
I read the list




More information about the Tutor mailing list