From 823239fd63671b58eca3f72d4b42f81da6cb73af Mon Sep 17 00:00:00 2001 From: Florian Burgener <florian.brgnr@gmail.com> Date: Tue, 10 May 2022 23:29:01 +0200 Subject: [PATCH] Why --- .editorconfig | 9 +++++++ __main__.py | 69 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..18d1902 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true diff --git a/__main__.py b/__main__.py index e69de29..a314cc3 100644 --- a/__main__.py +++ b/__main__.py @@ -0,0 +1,69 @@ +# t = minimum degree +# minimum of t-1 keys for every node except root +# 2t - 1 keys at most for every node + + +class Node: + def __init__(self, t): + self.t = t + self.keys = [] + self.children = [] + self.is_leaf = False + + +def insert(t, root, key): + if root is None: + root = Node(t) + root.keys = [key] + root.is_leaf = True + return root + insert_index = -1 + for i in range(len(root.keys)): + if key < root.keys[i]: + insert_index = i + break + if i == len(root.keys) - 1: + insert_index = i + 1 + break + if root.is_leaf and len(root.keys) == 2 * root.t - 1: + parent = Node(root.t) + parent.children = [root] + split_child(parent, 0) + return parent + # parent = Node(root.t) + # root.keys.insert(insert_index, key) + # left = root + # right = Node(root.t) + # split_index = len(root.keys) // 2 + # right.keys = root.keys[split_index:] + # left.keys = root.keys[:split_index] + # parent.keys = [right.keys[0]] + # parent.children = [left, right] + if root.is_leaf: + root.keys.insert(insert_index, key) + return root + +def split_child(root, i): + left = root.children[i] + split_index = len(root.keys) // 2 + 1 + right = Node(root.t) + right.keys = left.keys[split_index:] + left.keys = left.keys[:split_index] + root.children = [left, right] + root.keys = [right.keys[0]] + + +def main(): + t = 2 + root = None + root = insert(t, root, 20) + root = insert(t, root, 40) + root = insert(t, root, 5) + root = insert(t, root, 3) + print(root.keys) + print(root.children[0].keys) + print(root.children[1].keys) + + +if __name__ == "__main__": + main() -- GitLab