Python:扩展复杂的树数据结构

Python:扩展复杂的树数据结构,python,algorithm,data-structures,recursion,expression-trees,Python,Algorithm,Data Structures,Recursion,Expression Trees,我正在探索一种数据结构,它可以扩展到子元素并解析为最终元素。但我只想存储最上面的两个级别 比如说,我先从纽约开始,纽约分为布朗克斯、国王、纽约、皇后和里士满四个县,但最后不知何故,他们决定去美国 我不确定这是否是一个很好的例子,但为了说明问题,这里有更清楚的解释 A (expands to) B,C,D -> B (expands to) K,L,M -> K resolves to Z 我最初在一系列for循环中编写它,然后使用递归,但在递归中,我丢失了一些得到扩展的元素,因此

我正在探索一种数据结构,它可以扩展到子元素并解析为最终元素。但我只想存储最上面的两个级别

比如说,我先从纽约开始,纽约分为布朗克斯、国王、纽约、皇后和里士满四个县,但最后不知何故,他们决定去美国

我不确定这是否是一个很好的例子,但为了说明问题,这里有更清楚的解释

A (expands to) B,C,D -> B (expands to) K,L,M -> K resolves to Z 
我最初在一系列for循环中编写它,然后使用递归,但在递归中,我丢失了一些得到扩展的元素,因此我没有深入每个扩展的元素。我已经把递归版本和非递归版本放在一起了。我正在寻找一些关于构建此数据结构的建议,以及最好的方法是什么

我为扩展版本中的每个元素调用一个数据库查询,它返回一个项目列表。继续,直到它解析为单个元素。在没有递归的情况下,我不会一路放松钻取,直到其他人决定使用的最后一个元素。但是递归的情况就不一样了。我也是python新手,所以希望在这样的网站上问这个问题不是一个坏问题

returnCategoryQuery
是一种通过调用数据库查询返回项目列表的方法。

无递归 递归 你是在试图查找“皇后”并了解它在美国吗?您是否尝试过用XML对树进行编码,并使用
lxml.etree
查找元素,然后使用
getpath
以XPath格式返回路径

这意味着在树中添加第四个顶层,即World,然后您将搜索Queen并了解到Queen的路径是
World/USA/NewYork/queen
。您的问题的答案总是
XPath
中的第二项


当然,您总是可以从XML构建一棵树并使用树搜索算法

@agf我想知道你编辑了什么…?这是个奇怪的问题。“决心”是什么意思。例如,美国包括纽约,纽约包括布朗克斯、皇后区和里士满。但这是三个层次。@MichaelDillon对此表示抱歉,我所说的“解决”是指,它是根节点。我从树的底部开始。@agf很有趣,谢谢,我在在线社区做研究,你只是给我另一个想法来探索。@agf一个用户给出了一个答案,但它完全无关,我试图把这个问题作为赏金,但我不能,因为有一个答案对这个问题没有意义。我想知道你是否可以删除答案,因为你是专家。同样根据我所看到的,一旦有了答案,专家们往往不会回答这个问题。所以我很有可能得不到一个好的答案,谢谢。实际上,我在遍历时找到了这棵树,为了给你更好的想法,如果你转到这个链接,请在页面底部单击第一个类别。我想做的是钻每一个部分,直到我到达一个不再需要探索的地方。我还能问这个问题吗。我不确定我是否能做到,因为你已经提供了答案。如果是这样的话,我们就把答案去掉。因为这不是真正的答案。对不起。也许我在这个问题上不清楚,这就是为什么你给了这个答案。嗨,迈克尔,这是一个很好的要求。我想知道你是否可以删除这个答案,这样我就可以在这个问题上悬赏了。你提供的答案与问题的标准不符。但再次感谢您尝试解决此问题。对不起,我不明白您为什么要我删除我的答案。如果这样做不允许你设定赏金,那是因为你还没有足够的分数来提供赏金。通过简化你的问题,尤其是你的代码,然后再问一遍,你会做得更好,但这次写一个更好的问题标题和更清晰的解释。你的分数什么时候超过75分的?
#Dictionary to save initial category with the rest of cl_to
baseCategoryTree = {};
#categoryResults = [];

# query get all the categories a category is linked to
categoryQuery = "select cl_to from categorylinks cl left join page p on cl.cl_from = p.page_id where p.page_namespace=14 and p.page_title ='";
cursor = db.cursor(cursors.SSDictCursor);

    for key, value in idTitleDictionary.iteritems():
        for startCategory in value[0]:
            #print startCategory + "End of Query";
            categoryResults = [];
            try:
                categoryRow = "";
                baseCategoryTree[startCategory] = [];
                print categoryQuery + startCategory + "'";
                cursor.execute(categoryQuery + startCategory + "'");
                done = False;
                while not done:
                    categoryRow = cursor.fetchone();
                    if not categoryRow:
                        done = True;
                        continue;
                    categoryResults.append(categoryRow['cl_to']);
                for subCategoryResult in categoryResults:
                    print startCategory.encode('ascii') + " - " +  subCategoryResult;
                    for item in returnCategoryQuery(categoryQuery + subCategoryResult + "'"):
                        print startCategory.encode('ascii') + " - " + subCategoryResult + " - "  + item;
                        for subItem in returnCategoryQuery(categoryQuery + item + "'"):
                            print startCategory.encode('ascii') + " - " + subCategoryResult + " - "  + item + " - " + subItem;
                            for subOfSubItem in returnCategoryQuery(categoryQuery + subItem + "'"):
                                 print startCategory.encode('ascii') + " - " + subCategoryResult + " - "  + item + " - " + subItem + " - " + subOfSubItem;
                                 for sub_1_subOfSubItem in returnCategoryQuery(categoryQuery + subOfSubItem + "'"):
                                      print startCategory.encode('ascii') + " - " + subCategoryResult + " - "  + item + " - " + subItem + " - " + subOfSubItem + " - " + sub_1_subOfSubItem;
                                      for sub_2_subOfSubItem in returnCategoryQuery(categoryQuery + sub_1_subOfSubItem + "'"):
                                          print startCategory.encode('ascii') + " - " + subCategoryResult + " - "  + item + " - " + subItem + " - " + subOfSubItem + " - " + sub_1_subOfSubItem + " - " + sub_2_subOfSubItem;
            except Exception, e:
                traceback.print_exc();
def crawlSubCategory(subCategoryList):
    level = 1;
    expandedList = [];
    for eachCategory in subCategoryList:
        level = level + 1
        print "Level  " + str(level) + " " + eachCategory;
        #crawlSubCategory(returnCategoryQuery(categoryQuery + eachCategory + "'"));
        for subOfEachCategory in returnCategoryQuery(categoryQuery + eachCategory + "'"):
            level = level + 1
            print "Level  " + str(level) + " " + subOfEachCategory;
            expandedList.append(crawlSubCategory(returnCategoryQuery(categoryQuery + subOfEachCategory + "'")));
    return expandedList;


#Dictionary to save initial category with the rest of cl_to
baseCategoryTree = {};
#categoryResults = [];

# query get all the categories a category is linked to
categoryQuery = "select cl_to from categorylinks cl left join page p on cl.cl_from = p.page_id where p.page_namespace=14 and p.page_title ='";
cursor = db.cursor(cursors.SSDictCursor);

for key, value in idTitleDictionary.iteritems():
    for startCategory in value[0]:
        #print startCategory + "End of Query";
        categoryResults = [];
        try:
            categoryRow = "";
            baseCategoryTree[startCategory] = [];
            print categoryQuery + startCategory + "'";
            cursor.execute(categoryQuery + startCategory + "'");
            done = False;
            while not done:
                categoryRow = cursor.fetchone();
                if not categoryRow:
                    done = True;
                    continue;
                categoryResults.append(categoryRow['cl_to']);
            #crawlSubCategory(categoryResults);
        except Exception, e:
            traceback.print_exc();
        #baseCategoryTree[startCategory].append(categoryResults);
        baseCategoryTree[startCategory].append(crawlSubCategory(categoryResults));