Кристиян обнови решението на 30.04.2015 16:52 (преди над 9 години)
+class DestinationNodeDoesNotExistError(Exception):
+ pass
+
+class NotEnoughSpaceError(Exception):
+ pass
+
+class NodeDoesNotExistError(Exception):
+ pass
+
+class DestinationNodeExistsError(Exception):
+ pass
+
+class NonExplicitDirectoryDeletionError(Exception):
+ pass
+
+
+class File:
+ is_directory = False
+ def __init__(self, content):
+ self.content = content
+
+ @property
+ def size(self):
+ return len(self.content) + 1
+
+ def append(self, text):
+ self.content += text
+
+ def truncate(self, text):
+ self.content = text
+
+class Dir:
+ is_directory = True
+ def __init__(self):
+ self.content = {}
+
+ def __setitem__(self, key, item):
+ self.content[key] = item
+
+ def __getitem__(self, key):
+ return self.content[key]
+
+ def __contains__(self, x):
+ return x in self.content
+
+ def __delitem__(self, key):
+ del self.content[key]
+
+ @property
+ def nodes(self):
+ return [self.content]
+
+ @property
+ def directories(self):
+ return [ {k, v} for k, v in self.content.items() if v.is_directory]
+
+ @property
+ def files(self):
+ return [ {k, v} for k, v in self.content.items() if not v.is_directory]
+
+
+
+class FileSystem:
+ def __init__(self, size):
+ self.size = size
+ self.available_size = size - 1
+ self.filesystem = {
+ '/': Dir()
+ }
+
+
+ def get_node(self, path):
+ parts = ['/']
+ parts.extend(path.split('/')[1:])
+ parts_count = len(parts)
+ fs = self.filesystem;
+
+ for part in parts:
+ if part not in fs :
+ raise NodeDoesNotExistError
+ if parts.index(part) + 1 != parts_count:
+ fs = fs[part]
+ else:
+ return fs[part]
+
+
+ def create(self, path, directory=False, content=''):
+ parts = ['/']
+ parts.extend(path.split('/')[1:])
+ parts_count = len(parts)
+ fs = self.filesystem;
+
+ for part in parts:
+ if parts.index(part) + 1 != parts_count:
+ if part not in fs :
+ raise DestinationNodeDoesNotExistError
+ else:
+ fs = fs[part]
+ else:
+ if part in fs:
+ raise DestinationNodeExistsError
+ if directory:
+ if(self.available_size <= 1):
+ raise NotEnoughSpaceError
+ fs[part] = Dir()
+ self.available_size -= 1
+ else:
+ content_size = len(content);
+ if self.available_size < content_size + 1:
+ raise NotEnoughSpaceError
+ fs[part] = File(content)
+ self.available_size -= content_size + 1
+
+ def remove(self, path, directory=False, force=True):
+ parts = ['/']
+ parts.extend(path.split('/')[1:])
+ parts_count = len(parts)
+ fs = self.filesystem;
+
+ for part in parts:
+ if part not in fs:
+ raise NodeDoesNotExistError
+ if parts.index(part) + 1 != parts_count:
+ fs = fs[part]
+ else:
+ if fs[part].is_directory:
+ if not directory:
+ raise NonExplicitDirectoryDeletionError
+ elif bool(fs[part]) and not force:
+ raise NonEmptyDirectoryDeletionError
+ del fs[part]