【问题标题】:Python: Expanding Complicated Tree DataStructurePython:扩展复杂的树数据结构
【发布时间】:2011-12-23 07:25:04
【问题描述】:

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

示例:假设我从纽约开始,将布朗克斯、金斯、纽约、皇后区和里士满划分为县,但最终以某种方式解决了美国。

我不确定这是否是一个很好的例子,但为了清楚起见,这里更清楚地解释了问题。

A (expands to) B,C,D -> B (expands to) K,L,M -> K resolves to Z 

我最初是在一系列 for 循环中编写它,然后使用递归,但在递归中,我丢失了一些展开的元素,因此我不会深入研究每个展开的元素。我已经把递归版本和非递归版本都放了。我正在寻找有关构建此数据结构的一些建议,以及最好的方法是什么。

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

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

没有递归

#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));

【问题讨论】:

  • @agf 我想知道你编辑了什么..?
  • 这是一个奇怪的问题。 “下定决心”是什么意思。例如,美国包含纽约,纽约包含布朗克斯、皇后区和里士满。但这是三个层次。
  • @MichaelDillon 对此感到抱歉,我的意思是,它是根节点。我从树的底部开始。
  • @agf 很有趣,谢谢,我在在线社区进行研究,而你只是在玩弄我另一个探索的想法..
  • @agf 一个用户已经给出了答案,但它完全无关紧要,我试图把这个问题作为赏金,但我不能,因为有一个答案对这个问题没有任何意义。我想知道您是否可以删除答案,因为您是专家。同样根据我所看到的,一旦有答案,专家往往不会回答该问题。所以我很有可能得不到好的答案谢谢。

标签: python algorithm data-structures recursion expression-trees


【解决方案1】:

您是否正在尝试查找“Queens”并得知它在美国?您是否尝试过在 XML 中对树进行编码,并使用 lxml.etree 查找元素,然后使用 getpath 以 XPath 格式返回路径?

这意味着在树中添加第四个顶层,即 World,然后您将搜索 Queens 并得知通往 Queens 的路径是 World/USA/NewYork/Queens。您问题的答案始终是XPath 中的第二项。

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

【讨论】:

  • 我实际上在遍历时找到了树,以便您更好地了解,如果您转到此链接,请在页面底部单击第一个类别。 en.wikipedia.org/wiki/New_York_City 我要做的是钻取每个部分,直到我到达一个没有更多可探索的地方。
  • 我还能提出这个问题来获得赏金吗?我不确定我是否可以这样做,因为您已经提供了答案。如果是这种情况,我们将取消答案。因为它不是真正的答案。对不起。可能是我的问题不清楚,这就是为什么你可能会给出这个答案。
  • 嗨迈克尔,这是一个好心的请求。我想知道您是否可以删除答案,以便我可以在这个问题上设置赏金。您提供的答案与问题的标准不符。但再次感谢您尝试解决此问题。
  • 对不起,我不明白你为什么要我删除我的答案。如果 SO 不允许您设置赏金,那是因为您还没有足够的积分来提供赏金。通过简化你的问题,特别是你的代码,然后再问一遍,你会做得更好,但这次写一个更好的问题标题和更清晰的解释。 stackoverflow.com/privileges/set-bounties你的分数什么时候超过75?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-07
相关资源
最近更新 更多