text stringlengths 81 112k |
|---|
Encodes a list of strings to a single string.
:type strs: List[str]
:rtype: str
def encode(strs):
"""Encodes a list of strings to a single string.
:type strs: List[str]
:rtype: str
"""
res = ''
for string in strs.split():
res += str(len(string)) + ":" + string
return res |
Decodes a single string to a list of strings.
:type s: str
:rtype: List[str]
def decode(s):
"""Decodes a single string to a list of strings.
:type s: str
:rtype: List[str]
"""
strs = []
i = 0
while i < len(s):
index = s.find(":", i)
size = int(s[i:index])
str... |
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: List[List[int]]
def multiply(multiplicand: list, multiplier: list) -> list:
"""
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: List[List[int]]
"""
multiplicand_row, multiplicand_col = len(
multiplicand), len(mu... |
This function calculates nCr.
def combination(n, r):
"""This function calculates nCr."""
if n == r or r == 0:
return 1
else:
return combination(n-1, r-1) + combination(n-1, r) |
This function calculates nCr using memoization method.
def combination_memo(n, r):
"""This function calculates nCr using memoization method."""
memo = {}
def recur(n, r):
if n == r or r == 0:
return 1
if (n, r) not in memo:
memo[(n, r)] = recur(n - 1, r - 1) + recur(... |
:type s: str
:type t: str
:rtype: bool
def is_anagram(s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
maps = {}
mapt = {}
for i in s:
maps[i] = maps.get(i, 0) + 1
for i in t:
mapt[i] = mapt.get(i, 0) + 1
return maps == mapt |
Pancake_sort
Sorting a given array
mutation of selection sort
reference: https://www.geeksforgeeks.org/pancake-sorting/
Overall time complexity : O(N^2)
def pancake_sort(arr):
"""
Pancake_sort
Sorting a given array
mutation of selection sort
reference: https://www.geeksforgee... |
:rtype: int
def next(self):
"""
:rtype: int
"""
v=self.queue.pop(0)
ret=v.pop(0)
if v: self.queue.append(v)
return ret |
:type prices: List[int]
:rtype: int
def max_profit_naive(prices):
"""
:type prices: List[int]
:rtype: int
"""
max_so_far = 0
for i in range(0, len(prices) - 1):
for j in range(i + 1, len(prices)):
max_so_far = max(max_so_far, prices[j] - prices[i])
return max_so_far |
input: [7, 1, 5, 3, 6, 4]
diff : [X, -6, 4, -2, 3, -2]
:type prices: List[int]
:rtype: int
def max_profit_optimized(prices):
"""
input: [7, 1, 5, 3, 6, 4]
diff : [X, -6, 4, -2, 3, -2]
:type prices: List[int]
:rtype: int
"""
cur_max, max_so_far = 0, 0
for i in range(1, len(pr... |
:type s: str
:rtype: int
def first_unique_char(s):
"""
:type s: str
:rtype: int
"""
if (len(s) == 1):
return 0
ban = []
for i in range(len(s)):
if all(s[i] != s[k] for k in range(i + 1, len(s))) == True and s[i] not in ban:
return i
else:
... |
:type root: TreeNode
:type k: int
:rtype: int
def kth_smallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
count = []
self.helper(root, count)
return count[k-1] |
:type num: int
:rtype: str
def int_to_roman(num):
"""
:type num: int
:rtype: str
"""
m = ["", "M", "MM", "MMM"];
c = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"];
x = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"];
i = ["", "I", "II", "III", "IV", "V", ... |
:type input: str
:rtype: int
def length_longest_path(input):
"""
:type input: str
:rtype: int
"""
curr_len, max_len = 0, 0 # running length and max length
stack = [] # keep track of the name length
for s in input.split('\n'):
print("---------")
print("<path>:", s)
... |
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: List[List[int]]
def multiply(self, a, b):
"""
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: List[List[int]]
"""
if a is None or b is None: return None
m, n, l = len(a), len(b[0]), len(b[0])
if len(b) != n:
... |
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: List[List[int]]
def multiply(self, a, b):
"""
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: List[List[int]]
"""
if a is None or b is None: return None
m, n = len(a), len(b[0])
if len(b) != n:
raise Exc... |
bitonic sort is sorting algorithm to use multiple process, but this code not containing parallel process
It can sort only array that sizes power of 2
It can sort array in both increasing order and decreasing order by giving argument true(increasing) and false(decreasing)
Worst-case in parallel: O(log(n... |
Computes the strongly connected components of a graph
def scc(graph):
''' Computes the strongly connected components of a graph '''
order = []
vis = {vertex: False for vertex in graph}
graph_transposed = {vertex: [] for vertex in graph}
for (v, neighbours) in graph.iteritems():
for u in n... |
Builds the implication graph from the formula
def build_graph(formula):
''' Builds the implication graph from the formula '''
graph = {}
for clause in formula:
for (lit, _) in clause:
for neg in [False, True]:
graph[(lit, neg)] = []
for ((a_lit, a_neg), (b_lit, b_n... |
1. Sort all the arrays - a,b,c. - This improves average time complexity.
2. If c[i] < Sum, then look for Sum - c[i] in array a and b.
When pair found, insert c[i], a[j] & b[k] into the result list.
This can be done in O(n).
3. Keep on doing the above procedure while going through complete c array.... |
:type root: TreeNode
:rtype: bool
def is_bst(root):
"""
:type root: TreeNode
:rtype: bool
"""
stack = []
pre = None
while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
if pre and root.val <= pre.va... |
return 0 if unbalanced else depth + 1
def __get_depth(root):
"""
return 0 if unbalanced else depth + 1
"""
if root is None:
return 0
left = __get_depth(root.left)
right = __get_depth(root.right)
if abs(left-right) > 1 or -1 in [left, right]:
return -1
return 1 + max(lef... |
:type head: RandomListNode
:rtype: RandomListNode
def copy_random_pointer_v1(head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
dic = dict()
m = n = head
while m:
dic[m] = RandomListNode(m.label)
m = m.next
while n:
dic[n].next = dic.get(n.next)... |
:type head: RandomListNode
:rtype: RandomListNode
def copy_random_pointer_v2(head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
copy = defaultdict(lambda: RandomListNode(0))
copy[None] = None
node = head
while node:
copy[node].label = node.label
copy[no... |
[summary]
Arguments:
n {[int]} -- [to analysed number]
Returns:
[list of lists] -- [all factors of the number n]
def get_factors(n):
"""[summary]
Arguments:
n {[int]} -- [to analysed number]
Returns:
[list of lists] -- [all factors of the number n... |
[summary]
Computes all factors of n.
Translated the function get_factors(...) in
a call-stack modell.
Arguments:
n {[int]} -- [to analysed number]
Returns:
[list of lists] -- [all factors]
def get_factors_iterative1(n):
"""[summary]
Computes all factors of n.
Trans... |
[summary]
analog as above
Arguments:
n {[int]} -- [description]
Returns:
[list of lists] -- [all factors of n]
def get_factors_iterative2(n):
"""[summary]
analog as above
Arguments:
n {[int]} -- [description]
Returns:
[list of lists] -- [all facto... |
Dynamic Programming Algorithm for
counting the length of longest increasing subsequence
type sequence: List[int]
def longest_increasing_subsequence(sequence):
"""
Dynamic Programming Algorithm for
counting the length of longest increasing subsequence
type sequence: List[int]
"""
length ... |
:type nums: List[int]
:rtype: List[int]
def single_number3(nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# isolate a^b from pairs using XOR
ab = 0
for n in nums:
ab ^= n
# isolate right most bit from a^b
right_most = ab & (-ab)
# isolate a and b from a^b
... |
[summary]
HELPER-FUNCTION
calculates the (eulidean) distance between vector x and y.
Arguments:
x {[tuple]} -- [vector]
y {[tuple]} -- [vector]
def distance(x,y):
"""[summary]
HELPER-FUNCTION
calculates the (eulidean) distance between vector x and y.
Arguments:
x {... |
[summary]
Implements the nearest neighbor algorithm
Arguments:
x {[tupel]} -- [vector]
tSet {[dict]} -- [training set]
Returns:
[type] -- [result of the AND-function]
def nearest_neighbor(x, tSet):
"""[summary]
Implements the nearest neighbor algorithm
Arguments:
... |
:type num: str
:rtype: bool
def is_strobogrammatic(num):
"""
:type num: str
:rtype: bool
"""
comb = "00 11 88 69 96"
i = 0
j = len(num) - 1
while i <= j:
x = comb.find(num[i]+num[j])
if x == -1:
return False
i += 1
j -= 1
return True |
Merge Sort
Complexity: O(n log(n))
def merge_sort(arr):
""" Merge Sort
Complexity: O(n log(n))
"""
# Our recursive base case
if len(arr) <= 1:
return arr
mid = len(arr) // 2
# Perform merge_sort recursively on both halves
left, right = merge_sort(arr[:mid]), merge_so... |
Merge helper
Complexity: O(n)
def merge(left, right, merged):
""" Merge helper
Complexity: O(n)
"""
left_cursor, right_cursor = 0, 0
while left_cursor < len(left) and right_cursor < len(right):
# Sort each one and place into the result
if left[left_cursor] <= right[righ... |
Bucket Sort
Complexity: O(n^2)
The complexity is dominated by nextSort
def bucket_sort(arr):
''' Bucket Sort
Complexity: O(n^2)
The complexity is dominated by nextSort
'''
# The number of buckets and make buckets
num_buckets = len(arr)
buckets = [[] for bucket in ran... |
Initialize max heap with first k points.
Python does not support a max heap; thus we can use the default min heap where the keys (distance) are negated.
def k_closest(points, k, origin=(0, 0)):
# Time: O(k+(n-k)logk)
# Space: O(k)
"""Initialize max heap with first k points.
Python does not support ... |
:type head: ListNode
:rtype: ListNode
def reverse_list(head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
prev = None
while head:
current = head
head = head.next
current.next = prev
prev = current
re... |
:type head: ListNode
:rtype: ListNode
def reverse_list_recursive(head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
return head
p = head.next
head.next = None
revrest = reverse_list_recursive(p)
p.next = head
return revrest |
:type root: TreeNode
:type sum: int
:rtype: bool
def has_path_sum(root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if root is None:
return False
if root.left is None and root.right is None and root.val == sum:
return True
sum -= root.val
r... |
:type n: int
:type base: int
:rtype: str
def int_to_base(n, base):
"""
:type n: int
:type base: int
:rtype: str
"""
is_negative = False
if n == 0:
return '0'
elif n < 0:
is_negative = True
n *= -1
digit = string.digits + string.asc... |
Note : You can use int() built-in function instread of this.
:type s: str
:type base: int
:rtype: int
def base_to_int(s, base):
"""
Note : You can use int() built-in function instread of this.
:type s: str
:type base: int
:rtype: int
"""
digit = ... |
:type head: Node
:rtype: bool
def is_cyclic(head):
"""
:type head: Node
:rtype: bool
"""
if not head:
return False
runner = head
walker = head
while runner.next and runner.next.next:
runner = runner.next.next
walker = walker.next
if runner == walker:
... |
:type s: str
:rtype: str
def decode_string(s):
"""
:type s: str
:rtype: str
"""
stack = []; cur_num = 0; cur_string = ''
for c in s:
if c == '[':
stack.append((cur_string, cur_num))
cur_string = ''
cur_num = 0
elif c == ']':
pr... |
A slightly more Pythonic approach with a recursive generator
def palindromic_substrings_iter(s):
"""
A slightly more Pythonic approach with a recursive generator
"""
if not s:
yield []
return
for i in range(len(s), 0, -1):
sub = s[:i]
if sub == sub[::-1]:
... |
:type s: str
:type t: str
:rtype: bool
def is_isomorphic(s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t):
return False
dict = {}
set_value = set()
for i in range(len(s)):
if s[i] not in dict:
if t[i] in set_value:
... |
Calculate operation result
n2 Number: Number 2
n1 Number: Number 1
operator Char: Operation to calculate
def calc(n2, n1, operator):
"""
Calculate operation result
n2 Number: Number 2
n1 Number: Number 1
operator Char: Operation to calculate
"""
if operator == '-':... |
Apply operation to the first 2 items of the output queue
op_stack Deque (reference)
out_stack Deque (reference)
def apply_operation(op_stack, out_stack):
"""
Apply operation to the first 2 items of the output queue
op_stack Deque (reference)
out_stack Deque (reference)
"""
o... |
Return array of parsed tokens in the expression
expression String: Math expression to parse in infix notation
def parse(expression):
"""
Return array of parsed tokens in the expression
expression String: Math expression to parse in infix notation
"""
result = []
current = ""
... |
Calculate result of expression
expression String: The expression
type Type (optional): Number type [int, float]
def evaluate(expression):
"""
Calculate result of expression
expression String: The expression
type Type (optional): Number type [int, float]
"""
op_stack = deque... |
simple user-interface
def main():
"""
simple user-interface
"""
print("\t\tCalculator\n\n")
while True:
user_input = input("expression or exit: ")
if user_input == "exit":
break
try:
print("The result is {0}".format(evaluate(user_input))... |
:type root: TreeNode
:type target: float
:rtype: int
def closest_value(root, target):
"""
:type root: TreeNode
:type target: float
:rtype: int
"""
a = root.val
kid = root.left if target < a else root.right
if not kid:
return a
b = closest_value(kid, target)
retur... |
Return list of all primes less than n,
Using sieve of Eratosthenes.
def get_primes(n):
"""Return list of all primes less than n,
Using sieve of Eratosthenes.
"""
if n <= 0:
raise ValueError("'n' must be a positive integer.")
# If x is even, exclude x from list (-1):
sieve_size = (n ... |
returns a list with the permuations.
def permute(elements):
"""
returns a list with the permuations.
"""
if len(elements) <= 1:
return [elements]
else:
tmp = []
for perm in permute(elements[1:]):
for i in range(len(elements)):
tmp.append(perm[... |
iterator: returns a perumation by each call.
def permute_iter(elements):
"""
iterator: returns a perumation by each call.
"""
if len(elements) <= 1:
yield elements
else:
for perm in permute_iter(elements[1:]):
for i in range(len(elements)):
yield perm... |
Extended GCD algorithm.
Return s, t, g
such that a * s + b * t = GCD(a, b)
and s and t are co-prime.
def extended_gcd(a, b):
"""Extended GCD algorithm.
Return s, t, g
such that a * s + b * t = GCD(a, b)
and s and t are co-prime.
"""
old_s, s = 1, 0
old_t, t = 0, 1
old_r, r ... |
type root: root class
def bin_tree_to_list(root):
"""
type root: root class
"""
if not root:
return root
root = bin_tree_to_list_util(root)
while root.left:
root = root.left
return root |
:type num: str
:type target: int
:rtype: List[str]
def add_operators(num, target):
"""
:type num: str
:type target: int
:rtype: List[str]
"""
def dfs(res, path, num, target, pos, prev, multed):
if pos == len(num):
if target == prev:
res.append(path)
... |
internal library initializer.
def _init_rabit():
"""internal library initializer."""
if _LIB is not None:
_LIB.RabitGetRank.restype = ctypes.c_int
_LIB.RabitGetWorldSize.restype = ctypes.c_int
_LIB.RabitIsDistributed.restype = ctypes.c_int
_LIB.RabitVersionNumber.restype = ctype... |
Initialize the rabit library with arguments
def init(args=None):
"""Initialize the rabit library with arguments"""
if args is None:
args = []
arr = (ctypes.c_char_p * len(args))()
arr[:] = args
_LIB.RabitInit(len(arr), arr) |
Print message to the tracker.
This function can be used to communicate the information of
the progress to the tracker
Parameters
----------
msg : str
The message to be printed to tracker.
def tracker_print(msg):
"""Print message to the tracker.
This function can be used to commun... |
Get the processor name.
Returns
-------
name : str
the name of processor(host)
def get_processor_name():
"""Get the processor name.
Returns
-------
name : str
the name of processor(host)
"""
mxlen = 256
length = ctypes.c_ulong()
buf = ctypes.create_string_b... |
Broadcast object from one node to all other nodes.
Parameters
----------
data : any type that can be pickled
Input data, if current rank does not equal root, this can be None
root : int
Rank of the node to broadcast data from.
Returns
-------
object : int
the result... |
Normalize UNIX path to a native path.
def normpath(path):
"""Normalize UNIX path to a native path."""
normalized = os.path.join(*path.split("/"))
if os.path.isabs(path):
return os.path.abspath("/") + normalized
else:
return normalized |
internal training function
def _train_internal(params, dtrain,
num_boost_round=10, evals=(),
obj=None, feval=None,
xgb_model=None, callbacks=None):
"""internal training function"""
callbacks = [] if callbacks is None else callbacks
evals = list(ev... |
Train a booster with given parameters.
Parameters
----------
params : dict
Booster params.
dtrain : DMatrix
Data to be trained.
num_boost_round: int
Number of boosting iterations.
evals: list of pairs (DMatrix, string)
List of items to be evaluated during trainin... |
Make an n-fold list of CVPack from random indices.
def mknfold(dall, nfold, param, seed, evals=(), fpreproc=None, stratified=False,
folds=None, shuffle=True):
"""
Make an n-fold list of CVPack from random indices.
"""
evals = list(evals)
np.random.seed(seed)
if stratified is False ... |
Aggregate cross-validation results.
If verbose_eval is true, progress is displayed in every call. If
verbose_eval is an integer, progress will only be displayed every
`verbose_eval` trees, tracked via trial.
def aggcv(rlist):
# pylint: disable=invalid-name
"""
Aggregate cross-validation result... |
Cross-validation with given parameters.
Parameters
----------
params : dict
Booster params.
dtrain : DMatrix
Data to be trained.
num_boost_round : int
Number of boosting iterations.
nfold : int
Number of folds in CV.
stratified : bool
Perform stratifi... |
Update the boosters for one iteration
def update(self, iteration, fobj):
""""Update the boosters for one iteration"""
self.bst.update(self.dtrain, iteration, fobj) |
Evaluate the CVPack for one iteration.
def eval(self, iteration, feval):
""""Evaluate the CVPack for one iteration."""
return self.bst.eval_set(self.watchlist, iteration, feval) |
return whether the current callback context is cv or train
def _get_callback_context(env):
"""return whether the current callback context is cv or train"""
if env.model is not None and env.cvfolds is None:
context = 'train'
elif env.model is None and env.cvfolds is not None:
context = 'cv'
... |
format metric string
def _fmt_metric(value, show_stdv=True):
"""format metric string"""
if len(value) == 2:
return '%s:%g' % (value[0], value[1])
if len(value) == 3:
if show_stdv:
return '%s:%g+%g' % (value[0], value[1], value[2])
return '%s:%g' % (value[0], value[1])
... |
Create a callback that print evaluation result.
We print the evaluation results every **period** iterations
and on the first and the last iterations.
Parameters
----------
period : int
The period to log the evaluation results
show_stdv : bool, optional
Whether show stdv if pr... |
Create a call back that records the evaluation history into **eval_result**.
Parameters
----------
eval_result : dict
A dictionary to store the evaluation results.
Returns
-------
callback : function
The requested callback function.
def record_evaluation(eval_result):
"""Cr... |
Reset learning rate after iteration 1
NOTE: the initial learning rate will still take in-effect on first iteration.
Parameters
----------
learning_rates: list or function
List of learning rate for each boosting round
or a customized function that calculates eta in terms of
curr... |
Create a callback that activates early stoppping.
Validation error needs to decrease at least
every **stopping_rounds** round(s) to continue training.
Requires at least one item in **evals**.
If there's more than one, will use the last.
Returns the model from the last iteration (not the best one).
... |
Run the doxygen make command in the designated folder.
def run_doxygen(folder):
"""Run the doxygen make command in the designated folder."""
try:
retcode = subprocess.call("cd %s; make doxygen" % folder, shell=True)
if retcode < 0:
sys.stderr.write("doxygen terminated by signal %s" % (-retcode))
ex... |
Decorate an objective function
Converts an objective function using the typical sklearn metrics
signature so that it is usable with ``xgboost.training.train``
Parameters
----------
func: callable
Expects a callable with signature ``func(y_true, y_pred)``:
y_true: array_like of sha... |
Set the parameters of this estimator.
Modification of the sklearn method to allow unknown kwargs. This allows using
the full range of xgboost parameters that are not defined as member variables
in sklearn grid search.
Returns
-------
self
def set_params(self, **params):
... |
Get parameters.
def get_params(self, deep=False):
"""Get parameters."""
params = super(XGBModel, self).get_params(deep=deep)
if isinstance(self.kwargs, dict): # if kwargs is a dict, update params accordingly
params.update(self.kwargs)
if params['missing'] is np.nan:
... |
Get xgboost type parameters.
def get_xgb_params(self):
"""Get xgboost type parameters."""
xgb_params = self.get_params()
random_state = xgb_params.pop('random_state')
if 'seed' in xgb_params and xgb_params['seed'] is not None:
warnings.warn('The seed parameter is deprecated ... |
Load the model from a file.
The model is loaded from an XGBoost internal binary format which is
universal among the various XGBoost interfaces. Auxiliary attributes of
the Python Booster object (such as feature names) will not be loaded.
Label encodings (text labels to numeric labels) w... |
Fit the gradient boosting model
Parameters
----------
X : array_like
Feature matrix
y : array_like
Labels
sample_weight : array_like
instance weights
eval_set : list, optional
A list of (X, y) tuple pairs to use as a valida... |
Predict with `data`.
.. note:: This function is not thread safe.
For each booster object, predict can only be called from one thread.
If you want to run prediction using multiple thread, call ``xgb.copy()`` to make copies
of model object and then call ``predict()``.
.. n... |
Return the predicted leaf every tree for each sample.
Parameters
----------
X : array_like, shape=[n_samples, n_features]
Input features matrix.
ntree_limit : int
Limit number of trees in the prediction; defaults to 0 (use all trees).
Returns
--... |
Feature importances property
.. note:: Feature importance is defined only for tree boosters
Feature importance is only defined when the decision tree model is chosen as base
learner (`booster=gbtree`). It is not defined for other base learner types, such
as linear learners ... |
Coefficients property
.. note:: Coefficients are defined only for linear learners
Coefficients are only defined when the linear model is chosen as base
learner (`booster=gblinear`). It is not defined for other base learner types, such
as tree learners (`booster=gbtree`).
... |
Intercept (bias) property
.. note:: Intercept is defined only for linear learners
Intercept (bias) is only defined when the linear model is chosen as base
learner (`booster=gblinear`). It is not defined for other base learner types, such
as tree learners (`booster=gbtree`).... |
Fit gradient boosting classifier
Parameters
----------
X : array_like
Feature matrix
y : array_like
Labels
sample_weight : array_like
Weight for each instance
eval_set : list, optional
A list of (X, y) pairs to use as a val... |
Predict with `data`.
.. note:: This function is not thread safe.
For each booster object, predict can only be called from one thread.
If you want to run prediction using multiple thread, call ``xgb.copy()`` to make copies
of model object and then call ``predict()``.
.. n... |
Predict the probability of each `data` example being of a given class.
.. note:: This function is not thread safe
For each booster object, predict can only be called from one thread.
If you want to run prediction using multiple thread, call ``xgb.copy()`` to make copies
of ... |
Fit the gradient boosting model
Parameters
----------
X : array_like
Feature matrix
y : array_like
Labels
group : array_like
group size of training data
sample_weight : array_like
group weights
.. note:: Weight... |
Convert a list of Python str to C pointer
Parameters
----------
data : list
list of str
def from_pystr_to_cstr(data):
"""Convert a list of Python str to C pointer
Parameters
----------
data : list
list of str
"""
if not isinstance(data, list):
raise NotImp... |
Revert C pointer to Python str
Parameters
----------
data : ctypes pointer
pointer to data
length : ctypes pointer
pointer to length of data
def from_cstr_to_pystr(data, length):
"""Revert C pointer to Python str
Parameters
----------
data : ctypes pointer
poin... |
Load xgboost Library.
def _load_lib():
"""Load xgboost Library."""
lib_paths = find_lib_path()
if not lib_paths:
return None
try:
pathBackup = os.environ['PATH'].split(os.pathsep)
except KeyError:
pathBackup = []
lib_success = False
os_error_list = []
for lib_pat... |
Convert a ctypes pointer array to a numpy array.
def ctypes2numpy(cptr, length, dtype):
"""Convert a ctypes pointer array to a numpy array.
"""
NUMPY_TO_CTYPES_MAPPING = {
np.float32: ctypes.c_float,
np.uint32: ctypes.c_uint,
}
if dtype not in NUMPY_TO_CTYPES_MAPPING:
raise ... |
Convert ctypes pointer to buffer type.
def ctypes2buffer(cptr, length):
"""Convert ctypes pointer to buffer type."""
if not isinstance(cptr, ctypes.POINTER(ctypes.c_char)):
raise RuntimeError('expected char pointer')
res = bytearray(length)
rptr = (ctypes.c_char * length).from_buffer(res)
i... |
Convert a python string to c array.
def c_array(ctype, values):
"""Convert a python string to c array."""
if isinstance(values, np.ndarray) and values.dtype.itemsize == ctypes.sizeof(ctype):
return (ctype * len(values)).from_buffer_copy(values)
return (ctype * len(values))(*values) |
Extract internal data from pd.DataFrame for DMatrix data
def _maybe_pandas_data(data, feature_names, feature_types):
""" Extract internal data from pd.DataFrame for DMatrix data """
if not isinstance(data, DataFrame):
return data, feature_names, feature_types
data_dtypes = data.dtypes
if not ... |
Validate feature names and types if data table
def _maybe_dt_data(data, feature_names, feature_types):
"""
Validate feature names and types if data table
"""
if not isinstance(data, DataTable):
return data, feature_names, feature_types
data_types_names = tuple(lt.name for lt in data.ltypes... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.