【问题标题】:Making directory structure in python using a trie使用 trie 在 python 中制作目录结构
【发布时间】:2023-08-25 14:27:01
【问题描述】:

我有一个文件名列表:

filenames = ["111", "112", "1341", "2213", "2131", "22222", "11111"]

应该组织在一个目录结构中,并且一个目录中的最大文件数不应大于假设2。因此,如果子树中的文件数量不超过最大值,我将前缀树(trie,下面的代码)存储在字典中,前缀为键,'end'

trie = make_trie(filenames, max_freq=2)

trie
{'1': {'1': {'1': 'end', '2': 'end'}, '3': 'end'},'2': {'1': 'end', '2': 'end'}}

对于每个文件名,然后我在 trie 中进行查找(下面的代码)并相应地构建路径:

for f in filenames:
    print("Filename: ", f, "\tPath:", get_path(f, trie))

Filename:  111  Path: 1/1/1/
Filename:  112  Path: 1/1/2/
Filename:  1341         Path: 1/3/
Filename:  2213         Path: 2/2/
Filename:  2131         Path: 2/1/
Filename:  22222        Path: 2/2/
Filename:  11111        Path: 1/1/1/

这很好用,但是对于我的 trie (make_trie) 和查找 (get_path) 的幼稚实现,这变得令人望而却步。我的猜测是我应该采用有效的现有 trie 实现,例如 pytriedatrie,但我真的不知道如何制作一个后缀数量阈值为 2 的 trie,所以我有点卡在如何使用这些包上,例如:

import datrie
tr = datrie.Trie(string.digits) # make trie with digits
for f in filenames:
    tr[f] = "some value" # insert into trie, but what should be the values??

tr.prefixes('111211321') # I can look up prefixes now, but then what?

如何使用现有的快速 trie 实现来构建我的目录结构?

我对 trie 和 lookup 的幼稚实现:

def make_trie(words, max_freq):
    root = dict()
    for word in words:
        current_dict = root
        for i in range(len(word)):
            letter = word[i]
            current_prefix = word[:i+1]
            prefix_freq = sum(list(map(lambda x: x[:i+1]==current_prefix, words)))
            if prefix_freq > max_freq:
                current_dict = current_dict.setdefault(letter, {})
            else:
                current_dict = current_dict.setdefault(letter, "end")
                break
    return root

def get_path(image_id, trie):
    result = ""
    current_dict = trie
    for i in range(len(image_id)):
        letter = image_id[i]
        if letter in current_dict:
            result += letter + "/"
            if current_dict[letter] == "end":
                break
            current_dict = current_dict[letter]
    return result

【问题讨论】:

  • 你真的需要一个 trie,还是你的目标只是创建一个目录结构?
  • 我真的不需要尝试

标签: python directory-structure trie


【解决方案1】:

这可以工作,使用os.makedirs

import os

def create_dir_structure(filenames):
    for filename in filenames:
        os.makedirs(
            '/'.join(e for e in str(filename))
        )


create_dir_structure(
    ['1111', '1123']
)

如果您希望看到任何不同的行为,请在 cmets 中告诉我

【讨论】:

  • 这里没有考虑最大目录数的限制。
  • 如果每个目录只允许一个文件(和更多目录),这将起作用
  • 但是,如果每个目录的子目录限制为 2 并且每个目录的文件限制为 2 ,您如何添加 ['1', '2', '3', '4', '5'] ?需要更多假设(关于字母表大小 w.r.t 最大常数)才能使问题可行。