Algorithm: how to delete every other file

I have a folder with thousands of images. I want to delete all other images. What's the most efficient way to do this? Traversing each one with i% 2 == 0 is still O (n). Is there a quick way to do this (preferably in Python)?

thanks

+1


a source to share


8 answers


To delete half of N images, you can't be faster than O (N)! You know that O () notation means (by the way) that constant multiplicative factors don't matter, right?



+21


a source


import os
l = os.listdir('/some/dir/with/files')

for n in l[::2]:
    os.unlink(n)

      



+11


a source


Traversing each of them with i% 2 == 0 is still O (n). Is there a quick way to do this (preferably in Python)?

The only way to be faster than O (n) is if your files are already sorted and you only want to delete one file.

You said i% 2 == 0, which means you delete every "even" file. O (n / 2) still O (n)

+3


a source


I don't see any conceivable way to delete files n/2

faster than O (n), unless the filesystem has a dedicated function to delete a large number of files (but I don't think it really exists in practice, if it's even possible)

+2


a source


If you want to delete the log files (n) will ... You can store images in the database though (MySQL has a "blob" type, among several others, that will store your images). Then you can do it in O (1) if you call them smart.

/ edit I hate how I have to use shorthand and bad grammar to get answers quickly.

if you are looking for the python equivalent for rm -rf * 2.img * 4.img * 6.img * 8.img * 0.img know that the computer should still go through the whole list of files

+1


a source


You can use islice

from module itertools

. Here's your example:

import os, itertools
dirContent = os.listdir('/some/dir/with/files')
toBeDeleted = itertools.islice(dirContent, 0, len(dirContent), 2)
# Now remove the files
[os.unlink(file) for file in toBeDeleted]

      

This is another form of doing what you want, although I'm not sure if it will be faster. Hope this helps.

+1


a source


"Traversing each of them with i% 2 == 0 is still O (n)"

Increasing by 2 instead of increasing by 1?

for(i = 0; i < numFiles; i += 2) {
  deleteFile(files[i]);
}

      

Seriously though: repeating a list of files is probably not the slowest part of your file. The actual deletion probably takes several orders of magnitude longer.

0


a source


I would try using something like the operating system, for example:

Linux:

@files = grep { -f "$dir/$_" && /*.H$/ }
unlink @files

      

Win:

$file_delete =~ /H$/;
rm $file_delete

      

to see if your os can do it faster than iterating in python.

use os.system (...) or subprocess.call (...) to run them from python.

0


a source







All Articles