Python: simple list merging based on intersections

My attempt: def merge(lsts): sets = [set(lst) for lst in lsts if lst] merged = True while merged: merged = False results = [] while sets: common, rest = sets[0], sets[1:] sets = [] for x in rest: if x.isdisjoint(common): sets.append(x) else: merged = True common |= x results.append(common) sets = results return sets lst … Read more

What are the known ways to store a tree structure in a relational DB? [closed]

As always: there is no best solution. Each solution makes different things easier or harder. The right solution for you depends on which operation you will do most. Naive Approach with parent-id: Pros: Easy to implement Easy to move a big subtree to another parent Insert is cheap Needed Fields directly accessible in SQL Cons: … Read more

Build a tree from a flat array in PHP [duplicate]

You forgot the unset() in there bro. function buildTree(array &$elements, $parentId = 0) { $branch = array(); foreach ($elements as $element) { if ($element[‘parent_id’] == $parentId) { $children = buildTree($elements, $element[‘id’]); if ($children) { $element[‘children’] = $children; } $branch[$element[‘id’]] = $element; unset($elements[$element[‘id’]]); } } return $branch; }

How do I print out a tree structure?

The trick is to pass a string as the indent and to treat the last child specially: class Node { public void PrintPretty(string indent, bool last) { Console.Write(indent); if (last) { Console.Write(“\\-“); indent += ” “; } else { Console.Write(“|-“); indent += “| “; } Console.WriteLine(Name); for (int i = 0; i < Children.Count; i++) … Read more

How to represent a data tree in SQL?

I’ve bookmarked this slidshare about SQL-Antipatterns, which discusses several alternatives: http://www.slideshare.net/billkarwin/sql-antipatterns-strike-back?src=embed The recommendation from there is to use a Closure Table (it’s explained in the slides). Here is the summary (slide 77): | Query Child | Query Subtree | Modify Tree | Ref. Integrity Adjacency List | Easy | Hard | Easy | Yes Path … Read more

Hitting Maximum Recursion Depth Using Pickle / cPickle

From the docs: Trying to pickle a highly recursive data structure may exceed the maximum recursion depth, a RuntimeError will be raised in this case. You can carefully raise this limit with sys.setrecursionlimit(). Although your trie implementation may be simple, it uses recursion and can lead to issues when converting to a persistent data structure. … Read more

What type of NoSQL database is best suited to store hierarchical data?

MongoDB and CouchDB offer solutions, but not built in functionality. See this SO question on representing hierarchy in a relational database as most other NoSQL solutions I’ve seen are similar in this regard; where you have to write your own algorithms for recalculating that information as nodes are added, deleted and moved. Generally speaking you’re … Read more