Best Python code snippet using avocado_python
tree_util.py
Source:tree_util.py
...28 A pair where the first element is a list of leaf values and the second29 element is a treedef representing the structure of the flattened tree.30 """31 registry = _process_pytree_registry(registry)32 is_leaf = _process_is_leaf(is_leaf)33 flat = _tree_flatten(tree, is_leaf=is_leaf, registry=registry)34 # unflatten the flat tree to make a copy35 treedef = tree_unflatten(tree, flat, is_leaf=is_leaf, registry=registry)36 return flat, treedef37def tree_just_flatten(tree, is_leaf=None, registry=None):38 """Flatten a pytree without creating a treedef.39 Args:40 tree: a pytree to flatten.41 is_leaf (callable or None): An optionally specified function that will be called42 at each flattening step. It should return a boolean, which indicates whether43 the flattening should traverse the current object, or if it should be44 stopped immediately, with the whole subtree being treated as a leaf.45 registry (dict or None): A pytree container registry that determines46 which types are considered container objects that should be flattened.47 ``is_leaf`` can override this in the sense that types that are in the48 registry are still considered a leaf but it cannot declare something a49 container that is not in the registry. None means that the default registry50 is used, i.e. that dicts, tuples and lists are considered containers.51 "extended" means that in addition numpy arrays and params DataFrames are52 considered containers. Passing a dictionary where the keys are types and the53 values are dicts with the entries "flatten", "unflatten" and "names" allows54 to completely override the default registries.55 Returns:56 A pair where the first element is a list of leaf values and the second57 element is a treedef representing the structure of the flattened tree.58 """59 registry = _process_pytree_registry(registry)60 is_leaf = _process_is_leaf(is_leaf)61 flat = _tree_flatten(tree, is_leaf=is_leaf, registry=registry)62 return flat63def _tree_flatten(tree, is_leaf, registry):64 out = []65 tree_type = get_type(tree)66 if tree_type not in registry or is_leaf(tree):67 out.append(tree)68 else:69 subtrees, _ = registry[tree_type]["flatten"](tree)70 for subtree in subtrees:71 if get_type(subtree) in registry:72 out += _tree_flatten(subtree, is_leaf, registry)73 else:74 out.append(subtree)75 return out76def tree_yield(tree, is_leaf=None, registry=None):77 """Yield leafs from a pytree and create the tree definition.78 Args:79 tree: a pytree.80 is_leaf (callable or None): An optionally specified function that will be called81 at each yield step. It should return a boolean, which indicates whether82 the generator should traverse the current object, or if it should be83 stopped immediately, with the whole subtree being treated as a leaf.84 registry (dict or None): A pytree container registry that determines85 which types are considered container objects that should be yielded.86 ``is_leaf`` can override this in the sense that types that are in the87 registry are still considered a leaf but it cannot declare something a88 container that is not in the registry. None means that the default registry89 is used, i.e. that dicts, tuples and lists are considered containers.90 "extended" means that in addition numpy arrays and params DataFrames are91 considered containers. Passing a dictionary where the keys are types and the92 values are dicts with the entries "flatten", "unflatten" and "names" allows93 to completely override the default registries.94 Returns:95 A pair where the first element is a generator of leaf values and the second96 element is a treedef representing the structure of the flattened tree.97 """98 registry = _process_pytree_registry(registry)99 is_leaf = _process_is_leaf(is_leaf)100 flat = _tree_yield(tree, is_leaf=is_leaf, registry=registry)101 return flat, tree102def tree_just_yield(tree, is_leaf=None, registry=None):103 """Yield leafs from a pytree without creating a treedef.104 Args:105 tree: a pytree.106 is_leaf (callable or None): An optionally specified function that will be called107 at each yield step. It should return a boolean, which indicates whether108 the generator should traverse the current object, or if it should be109 stopped immediately, with the whole subtree being treated as a leaf.110 registry (dict or None): A pytree container registry that determines111 which types are considered container objects that should be yielded.112 ``is_leaf`` can override this in the sense that types that are in the113 registry are still considered a leaf but it cannot declare something a114 container that is not in the registry. None means that the default registry115 is used, i.e. that dicts, tuples and lists are considered containers.116 "extended" means that in addition numpy arrays and params DataFrames are117 considered containers. Passing a dictionary where the keys are types and the118 values are dicts with the entries "flatten", "unflatten" and "names" allows119 to completely override the default registries.120 Returns:121 A generator of leaf values.122 """123 registry = _process_pytree_registry(registry)124 is_leaf = _process_is_leaf(is_leaf)125 flat = _tree_yield(tree, is_leaf=is_leaf, registry=registry)126 return flat127def _tree_yield(tree, is_leaf, registry):128 out = []129 tree_type = get_type(tree)130 if tree_type not in registry or is_leaf(tree):131 yield tree132 else:133 subtrees, _ = registry[tree_type]["flatten"](tree)134 for subtree in subtrees:135 if get_type(subtree) in registry:136 yield from _tree_yield(subtree, is_leaf, registry)137 else:138 yield subtree139 return out140def tree_unflatten(treedef, leaves, is_leaf=None, registry=None):141 """Reconstruct a pytree from the treedef and a list of leaves.142 The inverse of :func:`tree_flatten`.143 Args:144 treedef: the treedef to with information needed for reconstruction.145 leaves (list): the list of leaves to use for reconstruction. The list must match146 the leaves of the treedef.147 is_leaf (callable or None): An optionally specified function that will be called148 at each flattening step. It should return a boolean, which indicates whether149 the flattening should traverse the current object, or if it should be150 stopped immediately, with the whole subtree being treated as a leaf.151 registry (dict or None): A pytree container registry that determines152 which types are considered container objects that should be flattened.153 `is_leaf` can override this in the sense that types that are in the154 registry are still considered a leaf but it cannot declare something a155 container that is not in the registry. None means that the default registry156 is used, i.e. that dicts, tuples and lists are considered containers.157 "extended" means that in addition numpy arrays and params DataFrames are158 considered containers. Passing a dictionary where the keys are types and the159 values are dicts with the entries "flatten", "unflatten" and "names" allows160 to completely override the default registries.161 Returns:162 The reconstructed pytree, containing the ``leaves`` placed in the structure163 described by ``treedef``.164 """165 registry = _process_pytree_registry(registry)166 is_leaf = _process_is_leaf(is_leaf)167 return _tree_unflatten(treedef, leaves, is_leaf=is_leaf, registry=registry)168def _tree_unflatten(treedef, leaves, is_leaf, registry):169 leaves = iter(leaves)170 tree_type = get_type(treedef)171 if tree_type not in registry or is_leaf(treedef):172 return next(leaves)173 else:174 items, info = registry[tree_type]["flatten"](treedef)175 unflattened_items = []176 for item in items:177 if get_type(item) in registry:178 unflattened_items.append(179 _tree_unflatten(item, leaves, is_leaf=is_leaf, registry=registry)180 )181 else:182 unflattened_items.append(next(leaves))183 return registry[tree_type]["unflatten"](info, unflattened_items)184def tree_map(func, tree, is_leaf=None, registry=None):185 """Apply func to all leaves in tree.186 Args:187 func (callable): Function applied to each leaf in the tree.188 tree: A pytree.189 is_leaf (callable or None): An optionally specified function that will be called190 at each flattening step. It should return a boolean, which indicates whether191 the flattening should traverse the current object, or if it should be192 stopped immediately, with the whole subtree being treated as a leaf.193 registry (dict or None): A pytree container registry that determines194 which types are considered container objects that should be flattened.195 `is_leaf` can override this in the sense that types that are in the196 registry are still considered a leaf but it cannot declare something a197 container that is not in the registry. None means that the default registry198 is used, i.e. that dicts, tuples and lists are considered containers.199 "extended" means that in addition numpy arrays and params DataFrames are200 considered containers. Passing a dictionary where the keys are types and the201 values are dicts with the entries "flatten", "unflatten" and "names" allows202 to completely override the default registries.203 Returns:204 modified copy of tree.205 """206 flat, treedef = tree_flatten(tree, is_leaf=is_leaf, registry=registry)207 modified = [func(i) for i in flat]208 new_tree = tree_unflatten(treedef, modified, is_leaf=is_leaf, registry=registry)209 return new_tree210def tree_multimap(func, *trees, is_leaf=None, registry=None):211 """Apply func to leaves of multiple pytrees.212 Args:213 func (callable): Function applied to each leaf corresponding leaves of214 multiple py trees.215 trees: An arbitrary number of pytrees. All trees need to have the same216 structure.217 is_leaf (callable or None): An optionally specified function that will be called218 at each flattening step. It should return a boolean, which indicates whether219 the flattening should traverse the current object, or if it should be220 stopped immediately, with the whole subtree being treated as a leaf.221 registry (dict or None): A pytree container registry that determines222 which types are considered container objects that should be flattened.223 `is_leaf` can override this in the sense that types that are in the224 registry are still considered a leaf but it cannot declare something a225 container that is not in the registry. None means that the default registry226 is used, i.e. that dicts, tuples and lists are considered containers.227 "extended" means that in addition numpy arrays and params DataFrames are228 considered containers. Passing a dictionary where the keys are types and the229 values are dicts with the entries "flatten", "unflatten" and "names" allows230 to completely override the default registries.231 Returns:232 tree with the same structure as the elements in trees.233 """234 flat_trees, treedefs = [], []235 for tree in trees:236 flat, treedef = tree_flatten(tree, is_leaf=is_leaf, registry=registry)237 flat_trees.append(flat)238 treedefs.append(treedef)239 for treedef in treedefs:240 if treedef != treedefs[0]:241 raise ValueError("All trees must have the same structure.")242 modified = [func(*item) for item in zip(*flat_trees)]243 new_trees = tree_unflatten(244 treedefs[0], modified, is_leaf=is_leaf, registry=registry245 )246 return new_trees247def leaf_names(tree, is_leaf=None, registry=None, separator="_"):248 """Construct names for leaves in a pytree.249 Args:250 tree: a pytree to flatten.251 is_leaf (callable or None): An optionally specified function that will be called252 at each flattening step. It should return a boolean, which indicates whether253 the flattening should traverse the current object, or if it should be254 stopped immediately, with the whole subtree being treated as a leaf.255 registry (dict or None): A pytree container registry that determines256 which types are considered container objects that should be flattened.257 `is_leaf` can override this in the sense that types that are in the258 registry are still considered a leaf but it cannot declare something a259 container that is not in the registry. None means that the default registry260 is used, i.e. that dicts, tuples and lists are considered containers.261 "extended" means that in addition numpy arrays and params DataFrames are262 considered containers. Passing a dictionary where the keys are types and the263 values are dicts with the entries "flatten", "unflatten" and "names" allows264 to completely override the default registries.265 separator (str): String that separates the building blocks of the leaf name.266 Returns:267 list: List of strings with names for pytree leaves.268 """269 registry = _process_pytree_registry(registry)270 is_leaf = _process_is_leaf(is_leaf)271 leaf_names = _leaf_names(272 tree, is_leaf=is_leaf, registry=registry, separator=separator273 )274 return leaf_names275def _leaf_names(tree, is_leaf, registry, separator, prefix=None):276 out = []277 tree_type = get_type(tree)278 if tree_type not in registry or is_leaf(tree):279 out.append(prefix)280 else:281 subtrees, info = registry[tree_type]["flatten"](tree)282 names = registry[tree_type]["names"](tree)283 for name, subtree in zip(names, subtrees):284 if get_type(subtree) in registry:285 out += _leaf_names(286 subtree,287 is_leaf=is_leaf,288 registry=registry,289 separator=separator,290 prefix=_add_prefix(prefix, name, separator),291 )292 else:293 out.append(_add_prefix(prefix, name, separator))294 return out295def _add_prefix(prefix, string, separator):296 if prefix not in (None, ""):297 out = separator.join([prefix, string])298 else:299 out = string300 return out301def _process_pytree_registry(registry):302 registry = registry if registry is not None else get_registry()303 return registry304def _process_is_leaf(is_leaf):305 if is_leaf is None:306 return lambda tree: False # noqa: U100307 else:308 return is_leaf309def tree_equal(tree, other, is_leaf=None, registry=None, equality_checkers=None):310 """Determine if two pytrees are equal.311 Two pytrees are considered equal if their leaves are equal and the names of their312 leaves are equal. While this definition of equality might not always make sense313 it makes sense in most cases and can be implemented relatively easily.314 Args:315 tree: A pytree.316 other: Another pytree.317 is_leaf (callable or None): An optionally specified function that will be called318 at each flattening step. It should return a boolean, which indicates whether...
btree.py
Source:btree.py
1#!/usr/bin/env python32# -*- coding: utf-8 -*-3"""A B-tree"""4import bisect5class BTree:6 class Node:7 def __init__(self, keys=None, is_leaf=True, children=None):8 if not keys:9 keys = []10 self.keys = keys11 self.is_leaf = is_leaf12 if not children:13 children = []14 self.children = children15 def __len__(self):16 return len(self.keys)17 def __iter__(self):18 if self.is_leaf:19 yield from self.keys20 else:21 for c in self.children:22 yield from c23 def __init__(self, t=2**10):24 self.t = t25 self.root = self.Node()26 def search(self, k):27 r = self.root28 while True:29 i = bisect.bisect_left(r.keys, k)30 if i < len(r) and r.keys[i] == k:31 return True32 if r.is_leaf:33 return False34 r = r.children[i]35 def _split_child(self, x, i):36 # Move the second half of y to a new node z37 y = x.children[i]38 median = y.keys[self.t - 1]39 z = self.Node(is_leaf=y.is_leaf)40 y.keys, z.keys = y.keys[:self.t - 1], y.keys[self.t:]41 if not y.is_leaf:42 y.children, z.children = y.children[:self.t], y.children[self.t:]43 # Move up the median in y.keys to the parent x44 x.children.insert(i + 1, z)45 x.keys.insert(i, median)46 def insert(self, k):47 if self.search(k):48 return False49 r = self.root50 if len(r) == 2 * self.t - 1:51 # If the root is full,52 # create a new root and53 # let the original root be a child of the new root.54 self.root = self.Node(is_leaf=False, children=[r])55 # Then split the original root56 self._split_child(self.root, 0)57 self._insert_nonfull(self.root, k)58 else:59 self._insert_nonfull(r, k)60 return True61 def _insert_nonfull(self, x, k):62 i = bisect.bisect_left(x.keys, k)63 if x.is_leaf:64 x.keys.insert(i, k)65 else:66 if len(x.children[i]) == 2 * self.t - 1:67 self._split_child(x, i)68 if k > x.keys[i]:69 i += 170 self._insert_nonfull(x.children[i], k)71 def delete(self, k):72 return self._delete_nonhalf(self.root, k)73 def _delete_nonhalf(self, x, k):74 i = bisect.bisect_left(x.keys, k)75 if i < len(x) and x.keys[i] == k:76 if x.is_leaf:77 x.keys.pop(i)78 elif len(x.children[i]) >= self.t:79 # Can be improved but seems troublesome80 k2 = self._predecessor(x.children[i], k)81 self._delete_nonhalf(x.children[i], k2)82 x.keys[i] = k283 elif len(x.children[i + 1]) >= self.t:84 # Can be improved but seems troublesome85 k2 = self._sucessor(x.children[i + 1], k)86 self._delete_nonhalf(x.children[i + 1], k2)87 x.keys[i] = k288 else:89 self._merge_node(x, i)90 y = x.children[i]91 self._delete_nonhalf(y, k)92 elif x.is_leaf:93 return False94 else:95 y = x.children[i]96 if len(y) == self.t - 1:97 if i > 0 and len(x.children[i - 1]) >= self.t:98 left_sib = x.children[i - 1]99 y.keys.insert(0, x.keys[i - 1])100 x.keys[i - 1] = left_sib.keys.pop()101 if not left_sib.is_leaf:102 y.children.insert(0, left_sib.children.pop())103 elif i < len(x) and len(x.children[i + 1]) >= self.t:104 right_sib = x.children[i + 1]105 y.keys.append(x.keys[i])106 x.keys[i] = right_sib.keys.pop(0)107 if not right_sib.is_leaf:108 y.children.append(right_sib.children.pop(0))109 else:110 if i < len(x):111 self._merge_node(x, i)112 else:113 y = x.children[i - 1]114 self._merge_node(x, i - 1)115 self._delete_nonhalf(y, k)116 if not self.root.is_leaf and len(self.root) == 0:117 self.root = self.root.children[0]118 return True119 def _merge_node(self, x, i):120 """Merge the (i+1)-th child of x to the i-th child"""121 y = x.children[i]122 z = x.children.pop(i + 1)123 y.keys.append(x.keys.pop(i))124 y.keys.extend(z.keys)125 y.children.extend(z.children)126 def _predecessor(self, y, k):127 while not y.is_leaf:128 y = y.children[-1]129 return y.keys[-1]130 def _sucessor(self, y, k):131 while not y.is_leaf:132 y = y.children[0]133 return y.keys[0]134 def height(self):135 h = 1136 r = self.root137 while not r.is_leaf:138 r = r.children[0]139 h += 1140 return h141 def __iter__(self):...
test_is_leaf.py
Source:test_is_leaf.py
1from deflate_dict.is_leaf import is_leaf2def test_is_leaf():3 assert is_leaf("ghgh")4 assert is_leaf(33)5 assert is_leaf((1,2))6 assert is_leaf([1,2])7 assert is_leaf(["dd", "dd"])8 assert not is_leaf({9 "a":310 })11 assert not is_leaf([{12 "a":313 }])14 assert not is_leaf(15 ({16 "a":317 },18 {19 "a":320 })...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!