活跃农民
- 积分
- 816
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-3-17
- 最后登录
- 1970-1-1
|
本帖最后由 619899442 于 2016-10-7 04:00 编辑
写了一个基于递归的parser,求交流。。。
我的想法是:首先把输入转化成一个string list其中每个元素对应一行。在递归调用_build_subtree会对当前节点及其子树进行分析,返回下一个待分析的(对于这棵子树的中间结果,文件名的index)- class Solution:
- dic = {'.jpeg', '.png', '.gif'}
- @staticmethod
- def _is_pic(name):
- for ext in Solution.dic:
- if len(name) > len(ext) and name[-len(ext):] == ext:
- return True
- return False
- @staticmethod
- def _level(name):
- return len(name) - len(name.strip())
- @staticmethod
- def _build_subtree(strings, start): # return the (total length, next position)
- root = strings[start]
- this_level = Solution._level(root)
- count = 0
- next_file = start + 1
- # base case: leaf node
- if next_file < len(strings) and Solution._level(strings[next_file]) <= this_level or next_file == len(strings):
- # leaf node
- if Solution._is_pic(root):
- return 1 + len(root.strip()), next_file
- else:
- return 0, next_file
- while next_file < len(strings) and Solution._level(strings[next_file]) > this_level:
- tmp, next_file = Solution._build_subtree(strings, next_file)
- if tmp > 0:
- count += (tmp + len(root.strip()) + 1)
- return count, next_file
- @staticmethod
- def build_tree(string):
- strings = string.split('\n')
- next_file = 0
- res = 0
- while next_file < len(strings):
- tmp, next_file = Solution._build_subtree(strings, next_file)
- res += tmp
- return res
- if __name__ == "__main__":
- directory = 'dir1\n dir11\n dir12\n picture.jpeg\ndir121\n file1.txt\ndir2\n file2.gif'
- print(Solution.build_tree(directory))
复制代码 |
|