repo
stringclasses
85 values
path
stringlengths
8
121
func_name
stringlengths
1
82
original_string
stringlengths
112
65.5k
language
stringclasses
1 value
code
stringlengths
112
65.5k
code_tokens
listlengths
20
4.09k
docstring
stringlengths
3
46.3k
docstring_tokens
listlengths
1
564
sha
stringclasses
85 values
url
stringlengths
93
218
partition
stringclasses
1 value
keon/algorithms
algorithms/strings/encode_decode.py
encode
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
python
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
[ "def", "encode", "(", "strs", ")", ":", "res", "=", "''", "for", "string", "in", "strs", ".", "split", "(", ")", ":", "res", "+=", "str", "(", "len", "(", "string", ")", ")", "+", "\":\"", "+", "string", "return", "res" ]
Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
[ "Encodes", "a", "list", "of", "strings", "to", "a", "single", "string", ".", ":", "type", "strs", ":", "List", "[", "str", "]", ":", "rtype", ":", "str" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/strings/encode_decode.py#L8-L16
train
keon/algorithms
algorithms/strings/encode_decode.py
decode
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]) strs.append(s[index+1: index+1+size]) i = index+1+size return strs
python
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]) strs.append(s[index+1: index+1+size]) i = index+1+size return strs
[ "def", "decode", "(", "s", ")", ":", "strs", "=", "[", "]", "i", "=", "0", "while", "i", "<", "len", "(", "s", ")", ":", "index", "=", "s", ".", "find", "(", "\":\"", ",", "i", ")", "size", "=", "int", "(", "s", "[", "i", ":", "index", ...
Decodes a single string to a list of strings. :type s: str :rtype: List[str]
[ "Decodes", "a", "single", "string", "to", "a", "list", "of", "strings", ".", ":", "type", "s", ":", "str", ":", "rtype", ":", "List", "[", "str", "]" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/strings/encode_decode.py#L18-L30
train
keon/algorithms
algorithms/matrix/multiply.py
multiply
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(multiplicand[0]) multiplier_row, multiplier_col = len(multiplier), len(multiplier...
python
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(multiplicand[0]) multiplier_row, multiplier_col = len(multiplier), len(multiplier...
[ "def", "multiply", "(", "multiplicand", ":", "list", ",", "multiplier", ":", "list", ")", "->", "list", ":", "multiplicand_row", ",", "multiplicand_col", "=", "len", "(", "multiplicand", ")", ",", "len", "(", "multiplicand", "[", "0", "]", ")", "multiplier...
:type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]
[ ":", "type", "A", ":", "List", "[", "List", "[", "int", "]]", ":", "type", "B", ":", "List", "[", "List", "[", "int", "]]", ":", "rtype", ":", "List", "[", "List", "[", "int", "]]" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/matrix/multiply.py#L10-L28
train
keon/algorithms
algorithms/maths/combination.py
combination
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)
python
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)
[ "def", "combination", "(", "n", ",", "r", ")", ":", "if", "n", "==", "r", "or", "r", "==", "0", ":", "return", "1", "else", ":", "return", "combination", "(", "n", "-", "1", ",", "r", "-", "1", ")", "+", "combination", "(", "n", "-", "1", "...
This function calculates nCr.
[ "This", "function", "calculates", "nCr", "." ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/combination.py#L1-L6
train
keon/algorithms
algorithms/maths/combination.py
combination_memo
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(n - 1, r) return memo[(n, r)] return recur(n...
python
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(n - 1, r) return memo[(n, r)] return recur(n...
[ "def", "combination_memo", "(", "n", ",", "r", ")", ":", "memo", "=", "{", "}", "def", "recur", "(", "n", ",", "r", ")", ":", "if", "n", "==", "r", "or", "r", "==", "0", ":", "return", "1", "if", "(", "n", ",", "r", ")", "not", "in", "mem...
This function calculates nCr using memoization method.
[ "This", "function", "calculates", "nCr", "using", "memoization", "method", "." ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/combination.py#L8-L17
train
keon/algorithms
algorithms/map/is_anagram.py
is_anagram
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
python
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
[ "def", "is_anagram", "(", "s", ",", "t", ")", ":", "maps", "=", "{", "}", "mapt", "=", "{", "}", "for", "i", "in", "s", ":", "maps", "[", "i", "]", "=", "maps", ".", "get", "(", "i", ",", "0", ")", "+", "1", "for", "i", "in", "t", ":", ...
:type s: str :type t: str :rtype: bool
[ ":", "type", "s", ":", "str", ":", "type", "t", ":", "str", ":", "rtype", ":", "bool" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/map/is_anagram.py#L17-L29
train
keon/algorithms
algorithms/sort/pancake_sort.py
pancake_sort
def pancake_sort(arr): """ Pancake_sort Sorting a given array mutation of selection sort reference: https://www.geeksforgeeks.org/pancake-sorting/ Overall time complexity : O(N^2) """ len_arr = len(arr) if len_arr <= 1: return arr for cur in range(len(arr), 1, -1):...
python
def pancake_sort(arr): """ Pancake_sort Sorting a given array mutation of selection sort reference: https://www.geeksforgeeks.org/pancake-sorting/ Overall time complexity : O(N^2) """ len_arr = len(arr) if len_arr <= 1: return arr for cur in range(len(arr), 1, -1):...
[ "def", "pancake_sort", "(", "arr", ")", ":", "len_arr", "=", "len", "(", "arr", ")", "if", "len_arr", "<=", "1", ":", "return", "arr", "for", "cur", "in", "range", "(", "len", "(", "arr", ")", ",", "1", ",", "-", "1", ")", ":", "#Finding index of...
Pancake_sort Sorting a given array mutation of selection sort reference: https://www.geeksforgeeks.org/pancake-sorting/ Overall time complexity : O(N^2)
[ "Pancake_sort", "Sorting", "a", "given", "array", "mutation", "of", "selection", "sort" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/pancake_sort.py#L1-L25
train
keon/algorithms
algorithms/queues/zigzagiterator.py
ZigZagIterator.next
def next(self): """ :rtype: int """ v=self.queue.pop(0) ret=v.pop(0) if v: self.queue.append(v) return ret
python
def next(self): """ :rtype: int """ v=self.queue.pop(0) ret=v.pop(0) if v: self.queue.append(v) return ret
[ "def", "next", "(", "self", ")", ":", "v", "=", "self", ".", "queue", ".", "pop", "(", "0", ")", "ret", "=", "v", ".", "pop", "(", "0", ")", "if", "v", ":", "self", ".", "queue", ".", "append", "(", "v", ")", "return", "ret" ]
:rtype: int
[ ":", "rtype", ":", "int" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/queues/zigzagiterator.py#L11-L18
train
keon/algorithms
algorithms/dp/buy_sell_stock.py
max_profit_naive
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
python
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
[ "def", "max_profit_naive", "(", "prices", ")", ":", "max_so_far", "=", "0", "for", "i", "in", "range", "(", "0", ",", "len", "(", "prices", ")", "-", "1", ")", ":", "for", "j", "in", "range", "(", "i", "+", "1", ",", "len", "(", "prices", ")", ...
:type prices: List[int] :rtype: int
[ ":", "type", "prices", ":", "List", "[", "int", "]", ":", "rtype", ":", "int" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/dp/buy_sell_stock.py#L24-L33
train
keon/algorithms
algorithms/dp/buy_sell_stock.py
max_profit_optimized
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(prices)): cur_max = max(0, cur_max + prices[i] - prices[i-1]) max_so_far = max(max_so_far,...
python
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(prices)): cur_max = max(0, cur_max + prices[i] - prices[i-1]) max_so_far = max(max_so_far,...
[ "def", "max_profit_optimized", "(", "prices", ")", ":", "cur_max", ",", "max_so_far", "=", "0", ",", "0", "for", "i", "in", "range", "(", "1", ",", "len", "(", "prices", ")", ")", ":", "cur_max", "=", "max", "(", "0", ",", "cur_max", "+", "prices",...
input: [7, 1, 5, 3, 6, 4] diff : [X, -6, 4, -2, 3, -2] :type prices: List[int] :rtype: int
[ "input", ":", "[", "7", "1", "5", "3", "6", "4", "]", "diff", ":", "[", "X", "-", "6", "4", "-", "2", "3", "-", "2", "]", ":", "type", "prices", ":", "List", "[", "int", "]", ":", "rtype", ":", "int" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/dp/buy_sell_stock.py#L37-L48
train
keon/algorithms
algorithms/strings/first_unique_char.py
first_unique_char
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: ban.append(s[i]) return -1
python
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: ban.append(s[i]) return -1
[ "def", "first_unique_char", "(", "s", ")", ":", "if", "(", "len", "(", "s", ")", "==", "1", ")", ":", "return", "0", "ban", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "s", ")", ")", ":", "if", "all", "(", "s", "[", "i", "]...
:type s: str :rtype: int
[ ":", "type", "s", ":", "str", ":", "rtype", ":", "int" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/strings/first_unique_char.py#L14-L27
train
keon/algorithms
algorithms/tree/bst/kth_smallest.py
Solution.kth_smallest
def kth_smallest(self, root, k): """ :type root: TreeNode :type k: int :rtype: int """ count = [] self.helper(root, count) return count[k-1]
python
def kth_smallest(self, root, k): """ :type root: TreeNode :type k: int :rtype: int """ count = [] self.helper(root, count) return count[k-1]
[ "def", "kth_smallest", "(", "self", ",", "root", ",", "k", ")", ":", "count", "=", "[", "]", "self", ".", "helper", "(", "root", ",", "count", ")", "return", "count", "[", "k", "-", "1", "]" ]
:type root: TreeNode :type k: int :rtype: int
[ ":", "type", "root", ":", "TreeNode", ":", "type", "k", ":", "int", ":", "rtype", ":", "int" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/bst/kth_smallest.py#L24-L32
train
keon/algorithms
algorithms/strings/int_to_roman.py
int_to_roman
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", "VI", "VII", "VIII", "IX"]; ...
python
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", "VI", "VII", "VIII", "IX"]; ...
[ "def", "int_to_roman", "(", "num", ")", ":", "m", "=", "[", "\"\"", ",", "\"M\"", ",", "\"MM\"", ",", "\"MMM\"", "]", "c", "=", "[", "\"\"", ",", "\"C\"", ",", "\"CC\"", ",", "\"CCC\"", ",", "\"CD\"", ",", "\"D\"", ",", "\"DC\"", ",", "\"DCC\"", ...
:type num: int :rtype: str
[ ":", "type", "num", ":", "int", ":", "rtype", ":", "str" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/strings/int_to_roman.py#L6-L15
train
keon/algorithms
algorithms/stack/longest_abs_path.py
length_longest_path
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) depth = s.count('\t') #...
python
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) depth = s.count('\t') #...
[ "def", "length_longest_path", "(", "input", ")", ":", "curr_len", ",", "max_len", "=", "0", ",", "0", "# running length and max length", "stack", "=", "[", "]", "# keep track of the name length", "for", "s", "in", "input", ".", "split", "(", "'\\n'", ")", ":",...
:type input: str :rtype: int
[ ":", "type", "input", ":", "str", ":", "rtype", ":", "int" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/stack/longest_abs_path.py#L36-L58
train
keon/algorithms
algorithms/matrix/sparse_mul.py
multiply
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: raise Exception("A's column number must be equal to B's row number.") c = ...
python
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: raise Exception("A's column number must be equal to B's row number.") c = ...
[ "def", "multiply", "(", "self", ",", "a", ",", "b", ")", ":", "if", "a", "is", "None", "or", "b", "is", "None", ":", "return", "None", "m", ",", "n", ",", "l", "=", "len", "(", "a", ")", ",", "len", "(", "b", "[", "0", "]", ")", ",", "l...
:type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]
[ ":", "type", "A", ":", "List", "[", "List", "[", "int", "]]", ":", "type", "B", ":", "List", "[", "List", "[", "int", "]]", ":", "rtype", ":", "List", "[", "List", "[", "int", "]]" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/matrix/sparse_mul.py#L27-L43
train
keon/algorithms
algorithms/matrix/sparse_mul.py
multiply
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 Exception("A's column number must be equal to B's row number.") l = len(b[0]) ...
python
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 Exception("A's column number must be equal to B's row number.") l = len(b[0]) ...
[ "def", "multiply", "(", "self", ",", "a", ",", "b", ")", ":", "if", "a", "is", "None", "or", "b", "is", "None", ":", "return", "None", "m", ",", "n", "=", "len", "(", "a", ")", ",", "len", "(", "b", "[", "0", "]", ")", "if", "len", "(", ...
:type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]
[ ":", "type", "A", ":", "List", "[", "List", "[", "int", "]]", ":", "type", "B", ":", "List", "[", "List", "[", "int", "]]", ":", "rtype", ":", "List", "[", "List", "[", "int", "]]" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/matrix/sparse_mul.py#L71-L99
train
keon/algorithms
algorithms/sort/bitonic_sort.py
bitonic_sort
def bitonic_sort(arr, reverse=False): """ 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(de...
python
def bitonic_sort(arr, reverse=False): """ 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(de...
[ "def", "bitonic_sort", "(", "arr", ",", "reverse", "=", "False", ")", ":", "def", "compare", "(", "arr", ",", "reverse", ")", ":", "n", "=", "len", "(", "arr", ")", "//", "2", "for", "i", "in", "range", "(", "n", ")", ":", "if", "reverse", "!="...
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...
[ "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", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/bitonic_sort.py#L1-L43
train
keon/algorithms
algorithms/graph/satisfiability.py
scc
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 neighbours: add_edge(graph_transposed, u, v)...
python
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 neighbours: add_edge(graph_transposed, u, v)...
[ "def", "scc", "(", "graph", ")", ":", "order", "=", "[", "]", "vis", "=", "{", "vertex", ":", "False", "for", "vertex", "in", "graph", "}", "graph_transposed", "=", "{", "vertex", ":", "[", "]", "for", "vertex", "in", "graph", "}", "for", "(", "v...
Computes the strongly connected components of a graph
[ "Computes", "the", "strongly", "connected", "components", "of", "a", "graph" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/graph/satisfiability.py#L49-L74
train
keon/algorithms
algorithms/graph/satisfiability.py
build_graph
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_neg)) in formula: add_edge(graph, (a_lit...
python
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_neg)) in formula: add_edge(graph, (a_lit...
[ "def", "build_graph", "(", "formula", ")", ":", "graph", "=", "{", "}", "for", "clause", "in", "formula", ":", "for", "(", "lit", ",", "_", ")", "in", "clause", ":", "for", "neg", "in", "[", "False", ",", "True", "]", ":", "graph", "[", "(", "l...
Builds the implication graph from the formula
[ "Builds", "the", "implication", "graph", "from", "the", "formula" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/graph/satisfiability.py#L77-L90
train
keon/algorithms
algorithms/backtrack/array_sum_combinations.py
unique_array_sum_combinations
def unique_array_sum_combinations(A, B, C, target): """ 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...
python
def unique_array_sum_combinations(A, B, C, target): """ 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...
[ "def", "unique_array_sum_combinations", "(", "A", ",", "B", ",", "C", ",", "target", ")", ":", "def", "check_sum", "(", "n", ",", "*", "nums", ")", ":", "if", "sum", "(", "x", "for", "x", "in", "nums", ")", "==", "n", ":", "return", "(", "True", ...
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....
[ "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", "ar...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/backtrack/array_sum_combinations.py#L59-L84
train
keon/algorithms
algorithms/tree/bst/is_bst.py
is_bst
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.val: return False pre...
python
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.val: return False pre...
[ "def", "is_bst", "(", "root", ")", ":", "stack", "=", "[", "]", "pre", "=", "None", "while", "root", "or", "stack", ":", "while", "root", ":", "stack", ".", "append", "(", "root", ")", "root", "=", "root", ".", "left", "root", "=", "stack", ".", ...
:type root: TreeNode :rtype: bool
[ ":", "type", "root", ":", "TreeNode", ":", "rtype", ":", "bool" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/bst/is_bst.py#L23-L42
train
keon/algorithms
algorithms/tree/is_balanced.py
__get_depth
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(left, right)
python
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(left, right)
[ "def", "__get_depth", "(", "root", ")", ":", "if", "root", "is", "None", ":", "return", "0", "left", "=", "__get_depth", "(", "root", ".", "left", ")", "right", "=", "__get_depth", "(", "root", ".", "right", ")", "if", "abs", "(", "left", "-", "rig...
return 0 if unbalanced else depth + 1
[ "return", "0", "if", "unbalanced", "else", "depth", "+", "1" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/is_balanced.py#L12-L22
train
keon/algorithms
algorithms/linkedlist/copy_random_pointer.py
copy_random_pointer_v1
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) dic[n].random = dic.get(n.random) n = ...
python
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) dic[n].random = dic.get(n.random) n = ...
[ "def", "copy_random_pointer_v1", "(", "head", ")", ":", "dic", "=", "dict", "(", ")", "m", "=", "n", "=", "head", "while", "m", ":", "dic", "[", "m", "]", "=", "RandomListNode", "(", "m", ".", "label", ")", "m", "=", "m", ".", "next", "while", ...
:type head: RandomListNode :rtype: RandomListNode
[ ":", "type", "head", ":", "RandomListNode", ":", "rtype", ":", "RandomListNode" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/copy_random_pointer.py#L17-L31
train
keon/algorithms
algorithms/linkedlist/copy_random_pointer.py
copy_random_pointer_v2
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[node].next = copy[node.next] copy[node].random = ...
python
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[node].next = copy[node.next] copy[node].random = ...
[ "def", "copy_random_pointer_v2", "(", "head", ")", ":", "copy", "=", "defaultdict", "(", "lambda", ":", "RandomListNode", "(", "0", ")", ")", "copy", "[", "None", "]", "=", "None", "node", "=", "head", "while", "node", ":", "copy", "[", "node", "]", ...
:type head: RandomListNode :rtype: RandomListNode
[ ":", "type", "head", ":", "RandomListNode", ":", "rtype", ":", "RandomListNode" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/copy_random_pointer.py#L35-L48
train
keon/algorithms
algorithms/dfs/all_factors.py
get_factors
def get_factors(n): """[summary] Arguments: n {[int]} -- [to analysed number] Returns: [list of lists] -- [all factors of the number n] """ def factor(n, i, combi, res): """[summary] helper function Arguments: n {[int]} -- [number] ...
python
def get_factors(n): """[summary] Arguments: n {[int]} -- [to analysed number] Returns: [list of lists] -- [all factors of the number n] """ def factor(n, i, combi, res): """[summary] helper function Arguments: n {[int]} -- [number] ...
[ "def", "get_factors", "(", "n", ")", ":", "def", "factor", "(", "n", ",", "i", ",", "combi", ",", "res", ")", ":", "\"\"\"[summary]\n helper function\n\n Arguments:\n n {[int]} -- [number]\n i {[int]} -- [to tested divisor]\n combi {...
[summary] Arguments: n {[int]} -- [to analysed number] Returns: [list of lists] -- [all factors of the number n]
[ "[", "summary", "]", "Arguments", ":", "n", "{", "[", "int", "]", "}", "--", "[", "to", "analysed", "number", "]", "Returns", ":", "[", "list", "of", "lists", "]", "--", "[", "all", "factors", "of", "the", "number", "n", "]" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/dfs/all_factors.py#L30-L60
train
keon/algorithms
algorithms/dfs/all_factors.py
get_factors_iterative1
def get_factors_iterative1(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] """ todo, res = [(n, 2, [])], [] while...
python
def get_factors_iterative1(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] """ todo, res = [(n, 2, [])], [] while...
[ "def", "get_factors_iterative1", "(", "n", ")", ":", "todo", ",", "res", "=", "[", "(", "n", ",", "2", ",", "[", "]", ")", "]", ",", "[", "]", "while", "todo", ":", "n", ",", "i", ",", "combi", "=", "todo", ".", "pop", "(", ")", "while", "i...
[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]
[ "[", "summary", "]", "Computes", "all", "factors", "of", "n", ".", "Translated", "the", "function", "get_factors", "(", "...", ")", "in", "a", "call", "-", "stack", "modell", "." ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/dfs/all_factors.py#L63-L84
train
keon/algorithms
algorithms/dfs/all_factors.py
get_factors_iterative2
def get_factors_iterative2(n): """[summary] analog as above Arguments: n {[int]} -- [description] Returns: [list of lists] -- [all factors of n] """ ans, stack, x = [], [], 2 while True: if x > n // x: if not stack: return ans ...
python
def get_factors_iterative2(n): """[summary] analog as above Arguments: n {[int]} -- [description] Returns: [list of lists] -- [all factors of n] """ ans, stack, x = [], [], 2 while True: if x > n // x: if not stack: return ans ...
[ "def", "get_factors_iterative2", "(", "n", ")", ":", "ans", ",", "stack", ",", "x", "=", "[", "]", ",", "[", "]", ",", "2", "while", "True", ":", "if", "x", ">", "n", "//", "x", ":", "if", "not", "stack", ":", "return", "ans", "ans", ".", "ap...
[summary] analog as above Arguments: n {[int]} -- [description] Returns: [list of lists] -- [all factors of n]
[ "[", "summary", "]", "analog", "as", "above" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/dfs/all_factors.py#L87-L111
train
keon/algorithms
algorithms/dp/longest_increasing.py
longest_increasing_subsequence
def longest_increasing_subsequence(sequence): """ Dynamic Programming Algorithm for counting the length of longest increasing subsequence type sequence: List[int] """ length = len(sequence) counts = [1 for _ in range(length)] for i in range(1, length): for j in range(0, i): ...
python
def longest_increasing_subsequence(sequence): """ Dynamic Programming Algorithm for counting the length of longest increasing subsequence type sequence: List[int] """ length = len(sequence) counts = [1 for _ in range(length)] for i in range(1, length): for j in range(0, i): ...
[ "def", "longest_increasing_subsequence", "(", "sequence", ")", ":", "length", "=", "len", "(", "sequence", ")", "counts", "=", "[", "1", "for", "_", "in", "range", "(", "length", ")", "]", "for", "i", "in", "range", "(", "1", ",", "length", ")", ":",...
Dynamic Programming Algorithm for counting the length of longest increasing subsequence type sequence: List[int]
[ "Dynamic", "Programming", "Algorithm", "for", "counting", "the", "length", "of", "longest", "increasing", "subsequence", "type", "sequence", ":", "List", "[", "int", "]" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/dp/longest_increasing.py#L13-L26
train
keon/algorithms
algorithms/bit/single_number3.py
single_number3
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 a, b = 0, 0 for n in nums: if ...
python
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 a, b = 0, 0 for n in nums: if ...
[ "def", "single_number3", "(", "nums", ")", ":", "# 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 ...
:type nums: List[int] :rtype: List[int]
[ ":", "type", "nums", ":", "List", "[", "int", "]", ":", "rtype", ":", "List", "[", "int", "]" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/bit/single_number3.py#L29-L49
train
keon/algorithms
algorithms/ml/nearest_neighbor.py
distance
def distance(x,y): """[summary] HELPER-FUNCTION calculates the (eulidean) distance between vector x and y. Arguments: x {[tuple]} -- [vector] y {[tuple]} -- [vector] """ assert len(x) == len(y), "The vector must have same length" result = () sum = 0 for i in range(le...
python
def distance(x,y): """[summary] HELPER-FUNCTION calculates the (eulidean) distance between vector x and y. Arguments: x {[tuple]} -- [vector] y {[tuple]} -- [vector] """ assert len(x) == len(y), "The vector must have same length" result = () sum = 0 for i in range(le...
[ "def", "distance", "(", "x", ",", "y", ")", ":", "assert", "len", "(", "x", ")", "==", "len", "(", "y", ")", ",", "\"The vector must have same length\"", "result", "=", "(", ")", "sum", "=", "0", "for", "i", "in", "range", "(", "len", "(", "x", "...
[summary] HELPER-FUNCTION calculates the (eulidean) distance between vector x and y. Arguments: x {[tuple]} -- [vector] y {[tuple]} -- [vector]
[ "[", "summary", "]", "HELPER", "-", "FUNCTION", "calculates", "the", "(", "eulidean", ")", "distance", "between", "vector", "x", "and", "y", "." ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/ml/nearest_neighbor.py#L3-L19
train
keon/algorithms
algorithms/ml/nearest_neighbor.py
nearest_neighbor
def nearest_neighbor(x, tSet): """[summary] Implements the nearest neighbor algorithm Arguments: x {[tupel]} -- [vector] tSet {[dict]} -- [training set] Returns: [type] -- [result of the AND-function] """ assert isinstance(x, tuple) and isinstance(tSet, dict) curren...
python
def nearest_neighbor(x, tSet): """[summary] Implements the nearest neighbor algorithm Arguments: x {[tupel]} -- [vector] tSet {[dict]} -- [training set] Returns: [type] -- [result of the AND-function] """ assert isinstance(x, tuple) and isinstance(tSet, dict) curren...
[ "def", "nearest_neighbor", "(", "x", ",", "tSet", ")", ":", "assert", "isinstance", "(", "x", ",", "tuple", ")", "and", "isinstance", "(", "tSet", ",", "dict", ")", "current_key", "=", "(", ")", "min_d", "=", "float", "(", "'inf'", ")", "for", "key",...
[summary] Implements the nearest neighbor algorithm Arguments: x {[tupel]} -- [vector] tSet {[dict]} -- [training set] Returns: [type] -- [result of the AND-function]
[ "[", "summary", "]", "Implements", "the", "nearest", "neighbor", "algorithm" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/ml/nearest_neighbor.py#L22-L41
train
keon/algorithms
algorithms/maths/is_strobogrammatic.py
is_strobogrammatic
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
python
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
[ "def", "is_strobogrammatic", "(", "num", ")", ":", "comb", "=", "\"00 11 88 69 96\"", "i", "=", "0", "j", "=", "len", "(", "num", ")", "-", "1", "while", "i", "<=", "j", ":", "x", "=", "comb", ".", "find", "(", "num", "[", "i", "]", "+", "num",...
:type num: str :rtype: bool
[ ":", "type", "num", ":", "str", ":", "rtype", ":", "bool" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/is_strobogrammatic.py#L12-L26
train
keon/algorithms
algorithms/sort/merge_sort.py
merge_sort
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_sort(arr[mid:]) # Merge each side togethe...
python
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_sort(arr[mid:]) # Merge each side togethe...
[ "def", "merge_sort", "(", "arr", ")", ":", "# 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 Complexity: O(n log(n))
[ "Merge", "Sort", "Complexity", ":", "O", "(", "n", "log", "(", "n", "))" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/merge_sort.py#L1-L13
train
keon/algorithms
algorithms/sort/merge_sort.py
merge
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[right_cursor]: merged[left_curs...
python
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[right_cursor]: merged[left_curs...
[ "def", "merge", "(", "left", ",", "right", ",", "merged", ")", ":", "left_cursor", ",", "right_cursor", "=", "0", ",", "0", "while", "left_cursor", "<", "len", "(", "left", ")", "and", "right_cursor", "<", "len", "(", "right", ")", ":", "# Sort each on...
Merge helper Complexity: O(n)
[ "Merge", "helper", "Complexity", ":", "O", "(", "n", ")" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/merge_sort.py#L16-L38
train
keon/algorithms
algorithms/sort/bucket_sort.py
bucket_sort
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 range(num_buckets)] # Assign values into bucket_sort for value in arr: inde...
python
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 range(num_buckets)] # Assign values into bucket_sort for value in arr: inde...
[ "def", "bucket_sort", "(", "arr", ")", ":", "# The number of buckets and make buckets", "num_buckets", "=", "len", "(", "arr", ")", "buckets", "=", "[", "[", "]", "for", "bucket", "in", "range", "(", "num_buckets", ")", "]", "# Assign values into bucket_sort", "...
Bucket Sort Complexity: O(n^2) The complexity is dominated by nextSort
[ "Bucket", "Sort", "Complexity", ":", "O", "(", "n^2", ")", "The", "complexity", "is", "dominated", "by", "nextSort" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/bucket_sort.py#L1-L17
train
keon/algorithms
algorithms/heap/k_closest_points.py
k_closest
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 a max heap; thus we can use the default min heap where the keys (distance) are negated. """ heap = [(-distance(p, origin), p) for p in points[:k]] ...
python
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 a max heap; thus we can use the default min heap where the keys (distance) are negated. """ heap = [(-distance(p, origin), p) for p in points[:k]] ...
[ "def", "k_closest", "(", "points", ",", "k", ",", "origin", "=", "(", "0", ",", "0", ")", ")", ":", "# Time: O(k+(n-k)logk)", "# Space: O(k)", "heap", "=", "[", "(", "-", "distance", "(", "p", ",", "origin", ")", ",", "p", ")", "for", "p", "in", ...
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.
[ "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", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/heap/k_closest_points.py#L13-L40
train
keon/algorithms
algorithms/linkedlist/reverse.py
reverse_list
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 return prev
python
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 return prev
[ "def", "reverse_list", "(", "head", ")", ":", "if", "not", "head", "or", "not", "head", ".", "next", ":", "return", "head", "prev", "=", "None", "while", "head", ":", "current", "=", "head", "head", "=", "head", ".", "next", "current", ".", "next", ...
:type head: ListNode :rtype: ListNode
[ ":", "type", "head", ":", "ListNode", ":", "rtype", ":", "ListNode" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/reverse.py#L12-L25
train
keon/algorithms
algorithms/linkedlist/reverse.py
reverse_list_recursive
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
python
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
[ "def", "reverse_list_recursive", "(", "head", ")", ":", "if", "head", "is", "None", "or", "head", ".", "next", "is", "None", ":", "return", "head", "p", "=", "head", ".", "next", "head", ".", "next", "=", "None", "revrest", "=", "reverse_list_recursive",...
:type head: ListNode :rtype: ListNode
[ ":", "type", "head", ":", "ListNode", ":", "rtype", ":", "ListNode" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/reverse.py#L32-L43
train
keon/algorithms
algorithms/tree/path_sum.py
has_path_sum
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 return has_path_sum(root.left, sum) or has_path_sum(root.ri...
python
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 return has_path_sum(root.left, sum) or has_path_sum(root.ri...
[ "def", "has_path_sum", "(", "root", ",", "sum", ")", ":", "if", "root", "is", "None", ":", "return", "False", "if", "root", ".", "left", "is", "None", "and", "root", ".", "right", "is", "None", "and", "root", ".", "val", "==", "sum", ":", "return",...
:type root: TreeNode :type sum: int :rtype: bool
[ ":", "type", "root", ":", "TreeNode", ":", "type", "sum", ":", "int", ":", "rtype", ":", "bool" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/path_sum.py#L18-L29
train
keon/algorithms
algorithms/maths/base_conversion.py
int_to_base
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.ascii_uppercase res = '' while n > 0: res += ...
python
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.ascii_uppercase res = '' while n > 0: res += ...
[ "def", "int_to_base", "(", "n", ",", "base", ")", ":", "is_negative", "=", "False", "if", "n", "==", "0", ":", "return", "'0'", "elif", "n", "<", "0", ":", "is_negative", "=", "True", "n", "*=", "-", "1", "digit", "=", "string", ".", "digits", "+...
:type n: int :type base: int :rtype: str
[ ":", "type", "n", ":", "int", ":", "type", "base", ":", "int", ":", "rtype", ":", "str" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/base_conversion.py#L11-L31
train
keon/algorithms
algorithms/maths/base_conversion.py
base_to_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 = {} for i,c in enumerate(string.digits + string.ascii_uppercase): digit[c] = i multiplier = 1 res = 0 fo...
python
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 = {} for i,c in enumerate(string.digits + string.ascii_uppercase): digit[c] = i multiplier = 1 res = 0 fo...
[ "def", "base_to_int", "(", "s", ",", "base", ")", ":", "digit", "=", "{", "}", "for", "i", ",", "c", "in", "enumerate", "(", "string", ".", "digits", "+", "string", ".", "ascii_uppercase", ")", ":", "digit", "[", "c", "]", "=", "i", "multiplier", ...
Note : You can use int() built-in function instread of this. :type s: str :type base: int :rtype: int
[ "Note", ":", "You", "can", "use", "int", "()", "built", "-", "in", "function", "instread", "of", "this", ".", ":", "type", "s", ":", "str", ":", "type", "base", ":", "int", ":", "rtype", ":", "int" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/base_conversion.py#L34-L50
train
keon/algorithms
algorithms/linkedlist/is_cyclic.py
is_cyclic
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: return True return ...
python
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: return True return ...
[ "def", "is_cyclic", "(", "head", ")", ":", "if", "not", "head", ":", "return", "False", "runner", "=", "head", "walker", "=", "head", "while", "runner", ".", "next", "and", "runner", ".", "next", ".", "next", ":", "runner", "=", "runner", ".", "next"...
:type head: Node :rtype: bool
[ ":", "type", "head", ":", "Node", ":", "rtype", ":", "bool" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/is_cyclic.py#L13-L27
train
keon/algorithms
algorithms/strings/decode_string.py
decode_string
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 == ']': prev_string, num = stack.pop() ...
python
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 == ']': prev_string, num = stack.pop() ...
[ "def", "decode_string", "(", "s", ")", ":", "stack", "=", "[", "]", "cur_num", "=", "0", "cur_string", "=", "''", "for", "c", "in", "s", ":", "if", "c", "==", "'['", ":", "stack", ".", "append", "(", "(", "cur_string", ",", "cur_num", ")", ")", ...
:type s: str :rtype: str
[ ":", "type", "s", ":", "str", ":", "rtype", ":", "str" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/strings/decode_string.py#L20-L38
train
keon/algorithms
algorithms/backtrack/palindrome_partitioning.py
palindromic_substrings_iter
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]: for rest in palindromic_substrings_iter(s[i:]): ...
python
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]: for rest in palindromic_substrings_iter(s[i:]): ...
[ "def", "palindromic_substrings_iter", "(", "s", ")", ":", "if", "not", "s", ":", "yield", "[", "]", "return", "for", "i", "in", "range", "(", "len", "(", "s", ")", ",", "0", ",", "-", "1", ")", ":", "sub", "=", "s", "[", ":", "i", "]", "if", ...
A slightly more Pythonic approach with a recursive generator
[ "A", "slightly", "more", "Pythonic", "approach", "with", "a", "recursive", "generator" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/backtrack/palindrome_partitioning.py#L34-L45
train
keon/algorithms
algorithms/map/is_isomorphic.py
is_isomorphic
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: return False dict[s[i]] = t...
python
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: return False dict[s[i]] = t...
[ "def", "is_isomorphic", "(", "s", ",", "t", ")", ":", "if", "len", "(", "s", ")", "!=", "len", "(", "t", ")", ":", "return", "False", "dict", "=", "{", "}", "set_value", "=", "set", "(", ")", "for", "i", "in", "range", "(", "len", "(", "s", ...
:type s: str :type t: str :rtype: bool
[ ":", "type", "s", ":", "str", ":", "type", "t", ":", "str", ":", "rtype", ":", "bool" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/map/is_isomorphic.py#L21-L40
train
keon/algorithms
algorithms/calculator/math_parser.py
calc
def calc(n2, n1, operator): """ Calculate operation result n2 Number: Number 2 n1 Number: Number 1 operator Char: Operation to calculate """ if operator == '-': return n1 - n2 elif operator == '+': return n1 + n2 elif operator == '*': return n1 * n2 elif operator == '...
python
def calc(n2, n1, operator): """ Calculate operation result n2 Number: Number 2 n1 Number: Number 1 operator Char: Operation to calculate """ if operator == '-': return n1 - n2 elif operator == '+': return n1 + n2 elif operator == '*': return n1 * n2 elif operator == '...
[ "def", "calc", "(", "n2", ",", "n1", ",", "operator", ")", ":", "if", "operator", "==", "'-'", ":", "return", "n1", "-", "n2", "elif", "operator", "==", "'+'", ":", "return", "n1", "+", "n2", "elif", "operator", "==", "'*'", ":", "return", "n1", ...
Calculate operation result n2 Number: Number 2 n1 Number: Number 1 operator Char: Operation to calculate
[ "Calculate", "operation", "result", "n2", "Number", ":", "Number", "2", "n1", "Number", ":", "Number", "1", "operator", "Char", ":", "Operation", "to", "calculate" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/calculator/math_parser.py#L53-L66
train
keon/algorithms
algorithms/calculator/math_parser.py
apply_operation
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) """ out_stack.append(calc(out_stack.pop(), out_stack.pop(), op_stack.pop()))
python
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) """ out_stack.append(calc(out_stack.pop(), out_stack.pop(), op_stack.pop()))
[ "def", "apply_operation", "(", "op_stack", ",", "out_stack", ")", ":", "out_stack", ".", "append", "(", "calc", "(", "out_stack", ".", "pop", "(", ")", ",", "out_stack", ".", "pop", "(", ")", ",", "op_stack", ".", "pop", "(", ")", ")", ")" ]
Apply operation to the first 2 items of the output queue op_stack Deque (reference) out_stack Deque (reference)
[ "Apply", "operation", "to", "the", "first", "2", "items", "of", "the", "output", "queue", "op_stack", "Deque", "(", "reference", ")", "out_stack", "Deque", "(", "reference", ")" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/calculator/math_parser.py#L68-L75
train
keon/algorithms
algorithms/calculator/math_parser.py
parse
def parse(expression): """ Return array of parsed tokens in the expression expression String: Math expression to parse in infix notation """ result = [] current = "" for i in expression: if i.isdigit() or i == '.': current += i else: if le...
python
def parse(expression): """ Return array of parsed tokens in the expression expression String: Math expression to parse in infix notation """ result = [] current = "" for i in expression: if i.isdigit() or i == '.': current += i else: if le...
[ "def", "parse", "(", "expression", ")", ":", "result", "=", "[", "]", "current", "=", "\"\"", "for", "i", "in", "expression", ":", "if", "i", ".", "isdigit", "(", ")", "or", "i", "==", "'.'", ":", "current", "+=", "i", "else", ":", "if", "len", ...
Return array of parsed tokens in the expression expression String: Math expression to parse in infix notation
[ "Return", "array", "of", "parsed", "tokens", "in", "the", "expression", "expression", "String", ":", "Math", "expression", "to", "parse", "in", "infix", "notation" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/calculator/math_parser.py#L77-L99
train
keon/algorithms
algorithms/calculator/math_parser.py
evaluate
def evaluate(expression): """ Calculate result of expression expression String: The expression type Type (optional): Number type [int, float] """ op_stack = deque() # operator stack out_stack = deque() # output stack (values) tokens = parse(expression) # calls the function onl...
python
def evaluate(expression): """ Calculate result of expression expression String: The expression type Type (optional): Number type [int, float] """ op_stack = deque() # operator stack out_stack = deque() # output stack (values) tokens = parse(expression) # calls the function onl...
[ "def", "evaluate", "(", "expression", ")", ":", "op_stack", "=", "deque", "(", ")", "# operator stack\r", "out_stack", "=", "deque", "(", ")", "# output stack (values)\r", "tokens", "=", "parse", "(", "expression", ")", "# calls the function only once!\r", "for", ...
Calculate result of expression expression String: The expression type Type (optional): Number type [int, float]
[ "Calculate", "result", "of", "expression", "expression", "String", ":", "The", "expression", "type", "Type", "(", "optional", ")", ":", "Number", "type", "[", "int", "float", "]" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/calculator/math_parser.py#L101-L128
train
keon/algorithms
algorithms/calculator/math_parser.py
main
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))) except Excep...
python
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))) except Excep...
[ "def", "main", "(", ")", ":", "print", "(", "\"\\t\\tCalculator\\n\\n\"", ")", "while", "True", ":", "user_input", "=", "input", "(", "\"expression or exit: \"", ")", "if", "user_input", "==", "\"exit\"", ":", "break", "try", ":", "print", "(", "\"The result i...
simple user-interface
[ "simple", "user", "-", "interface" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/calculator/math_parser.py#L131-L145
train
keon/algorithms
algorithms/tree/bst/bst_closest_value.py
closest_value
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) return min((a,b), key=lambda x: abs(target-x))
python
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) return min((a,b), key=lambda x: abs(target-x))
[ "def", "closest_value", "(", "root", ",", "target", ")", ":", "a", "=", "root", ".", "val", "kid", "=", "root", ".", "left", "if", "target", "<", "a", "else", "root", ".", "right", "if", "not", "kid", ":", "return", "a", "b", "=", "closest_value", ...
:type root: TreeNode :type target: float :rtype: int
[ ":", "type", "root", ":", "TreeNode", ":", "type", "target", ":", "float", ":", "rtype", ":", "int" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/bst/bst_closest_value.py#L17-L28
train
keon/algorithms
algorithms/maths/primes_sieve_of_eratosthenes.py
get_primes
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 // 2 - 1) if n % 2 == 0 else (n // 2) sieve = [True for _ in range(si...
python
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 // 2 - 1) if n % 2 == 0 else (n // 2) sieve = [True for _ in range(si...
[ "def", "get_primes", "(", "n", ")", ":", "if", "n", "<=", "0", ":", "raise", "ValueError", "(", "\"'n' must be a positive integer.\"", ")", "# If x is even, exclude x from list (-1):", "sieve_size", "=", "(", "n", "//", "2", "-", "1", ")", "if", "n", "%", "2...
Return list of all primes less than n, Using sieve of Eratosthenes.
[ "Return", "list", "of", "all", "primes", "less", "than", "n", "Using", "sieve", "of", "Eratosthenes", "." ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/primes_sieve_of_eratosthenes.py#L28-L46
train
keon/algorithms
algorithms/backtrack/permute.py
permute
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[:i] + elements[0:1] + perm[i:]) ...
python
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[:i] + elements[0:1] + perm[i:]) ...
[ "def", "permute", "(", "elements", ")", ":", "if", "len", "(", "elements", ")", "<=", "1", ":", "return", "[", "elements", "]", "else", ":", "tmp", "=", "[", "]", "for", "perm", "in", "permute", "(", "elements", "[", "1", ":", "]", ")", ":", "f...
returns a list with the permuations.
[ "returns", "a", "list", "with", "the", "permuations", "." ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/backtrack/permute.py#L17-L28
train
keon/algorithms
algorithms/backtrack/permute.py
permute_iter
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[:i] + elements[0:1] + perm[i:]
python
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[:i] + elements[0:1] + perm[i:]
[ "def", "permute_iter", "(", "elements", ")", ":", "if", "len", "(", "elements", ")", "<=", "1", ":", "yield", "elements", "else", ":", "for", "perm", "in", "permute_iter", "(", "elements", "[", "1", ":", "]", ")", ":", "for", "i", "in", "range", "(...
iterator: returns a perumation by each call.
[ "iterator", ":", "returns", "a", "perumation", "by", "each", "call", "." ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/backtrack/permute.py#L31-L40
train
keon/algorithms
algorithms/maths/extended_gcd.py
extended_gcd
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 = a, b while r != 0: quotient = old_r / r old_r, r = r, old_r - quotient * r ...
python
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 = a, b while r != 0: quotient = old_r / r old_r, r = r, old_r - quotient * r ...
[ "def", "extended_gcd", "(", "a", ",", "b", ")", ":", "old_s", ",", "s", "=", "1", ",", "0", "old_t", ",", "t", "=", "0", ",", "1", "old_r", ",", "r", "=", "a", ",", "b", "while", "r", "!=", "0", ":", "quotient", "=", "old_r", "/", "r", "o...
Extended GCD algorithm. Return s, t, g such that a * s + b * t = GCD(a, b) and s and t are co-prime.
[ "Extended", "GCD", "algorithm", ".", "Return", "s", "t", "g", "such", "that", "a", "*", "s", "+", "b", "*", "t", "=", "GCD", "(", "a", "b", ")", "and", "s", "and", "t", "are", "co", "-", "prime", "." ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/extended_gcd.py#L1-L19
train
keon/algorithms
algorithms/tree/bin_tree_to_list.py
bin_tree_to_list
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
python
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
[ "def", "bin_tree_to_list", "(", "root", ")", ":", "if", "not", "root", ":", "return", "root", "root", "=", "bin_tree_to_list_util", "(", "root", ")", "while", "root", ".", "left", ":", "root", "=", "root", ".", "left", "return", "root" ]
type root: root class
[ "type", "root", ":", "root", "class" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/bin_tree_to_list.py#L4-L13
train
keon/algorithms
algorithms/backtrack/add_operators.py
add_operators
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) return for i in range(pos, len(num)): ...
python
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) return for i in range(pos, len(num)): ...
[ "def", "add_operators", "(", "num", ",", "target", ")", ":", "def", "dfs", "(", "res", ",", "path", ",", "num", ",", "target", ",", "pos", ",", "prev", ",", "multed", ")", ":", "if", "pos", "==", "len", "(", "num", ")", ":", "if", "target", "==...
:type num: str :type target: int :rtype: List[str]
[ ":", "type", "num", ":", "str", ":", "type", "target", ":", "int", ":", "rtype", ":", "List", "[", "str", "]" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/backtrack/add_operators.py#L15-L45
train
dmlc/xgboost
python-package/xgboost/rabit.py
_init_rabit
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 = ctypes.c_int
python
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 = ctypes.c_int
[ "def", "_init_rabit", "(", ")", ":", "if", "_LIB", "is", "not", "None", ":", "_LIB", ".", "RabitGetRank", ".", "restype", "=", "ctypes", ".", "c_int", "_LIB", ".", "RabitGetWorldSize", ".", "restype", "=", "ctypes", ".", "c_int", "_LIB", ".", "RabitIsDis...
internal library initializer.
[ "internal", "library", "initializer", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/rabit.py#L14-L20
train
dmlc/xgboost
python-package/xgboost/rabit.py
init
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)
python
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)
[ "def", "init", "(", "args", "=", "None", ")", ":", "if", "args", "is", "None", ":", "args", "=", "[", "]", "arr", "=", "(", "ctypes", ".", "c_char_p", "*", "len", "(", "args", ")", ")", "(", ")", "arr", "[", ":", "]", "=", "args", "_LIB", "...
Initialize the rabit library with arguments
[ "Initialize", "the", "rabit", "library", "with", "arguments" ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/rabit.py#L23-L29
train
dmlc/xgboost
python-package/xgboost/rabit.py
tracker_print
def tracker_print(msg): """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. """ if not isinstance(msg, STRING_TYPES): msg = str(msg...
python
def tracker_print(msg): """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. """ if not isinstance(msg, STRING_TYPES): msg = str(msg...
[ "def", "tracker_print", "(", "msg", ")", ":", "if", "not", "isinstance", "(", "msg", ",", "STRING_TYPES", ")", ":", "msg", "=", "str", "(", "msg", ")", "is_dist", "=", "_LIB", ".", "RabitIsDistributed", "(", ")", "if", "is_dist", "!=", "0", ":", "_LI...
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.
[ "Print", "message", "to", "the", "tracker", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/rabit.py#L61-L79
train
dmlc/xgboost
python-package/xgboost/rabit.py
get_processor_name
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_buffer(mxlen) _LIB.RabitGetProcessorName(buf, ctypes.byref(length), mxlen) return buf.value
python
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_buffer(mxlen) _LIB.RabitGetProcessorName(buf, ctypes.byref(length), mxlen) return buf.value
[ "def", "get_processor_name", "(", ")", ":", "mxlen", "=", "256", "length", "=", "ctypes", ".", "c_ulong", "(", ")", "buf", "=", "ctypes", ".", "create_string_buffer", "(", "mxlen", ")", "_LIB", ".", "RabitGetProcessorName", "(", "buf", ",", "ctypes", ".", ...
Get the processor name. Returns ------- name : str the name of processor(host)
[ "Get", "the", "processor", "name", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/rabit.py#L82-L94
train
dmlc/xgboost
python-package/xgboost/rabit.py
broadcast
def broadcast(data, root): """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 ------- ...
python
def broadcast(data, root): """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 ------- ...
[ "def", "broadcast", "(", "data", ",", "root", ")", ":", "rank", "=", "get_rank", "(", ")", "length", "=", "ctypes", ".", "c_ulong", "(", ")", "if", "root", "==", "rank", ":", "assert", "data", "is", "not", "None", ",", "'need to pass in data when broadca...
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...
[ "Broadcast", "object", "from", "one", "node", "to", "all", "other", "nodes", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/rabit.py#L97-L132
train
dmlc/xgboost
jvm-packages/create_jni.py
normpath
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
python
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
[ "def", "normpath", "(", "path", ")", ":", "normalized", "=", "os", ".", "path", ".", "join", "(", "*", "path", ".", "split", "(", "\"/\"", ")", ")", "if", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "return", "os", ".", "path", ".",...
Normalize UNIX path to a native path.
[ "Normalize", "UNIX", "path", "to", "a", "native", "path", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/jvm-packages/create_jni.py#L61-L67
train
dmlc/xgboost
python-package/xgboost/training.py
_train_internal
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(evals) if isinstance(param...
python
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(evals) if isinstance(param...
[ "def", "_train_internal", "(", "params", ",", "dtrain", ",", "num_boost_round", "=", "10", ",", "evals", "=", "(", ")", ",", "obj", "=", "None", ",", "feval", "=", "None", ",", "xgb_model", "=", "None", ",", "callbacks", "=", "None", ")", ":", "callb...
internal training function
[ "internal", "training", "function" ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/training.py#L15-L112
train
dmlc/xgboost
python-package/xgboost/training.py
train
def train(params, dtrain, num_boost_round=10, evals=(), obj=None, feval=None, maximize=False, early_stopping_rounds=None, evals_result=None, verbose_eval=True, xgb_model=None, callbacks=None, learning_rates=None): # pylint: disable=too-many-statements,too-many-branches, attribute-defined-outside...
python
def train(params, dtrain, num_boost_round=10, evals=(), obj=None, feval=None, maximize=False, early_stopping_rounds=None, evals_result=None, verbose_eval=True, xgb_model=None, callbacks=None, learning_rates=None): # pylint: disable=too-many-statements,too-many-branches, attribute-defined-outside...
[ "def", "train", "(", "params", ",", "dtrain", ",", "num_boost_round", "=", "10", ",", "evals", "=", "(", ")", ",", "obj", "=", "None", ",", "feval", "=", "None", ",", "maximize", "=", "False", ",", "early_stopping_rounds", "=", "None", ",", "evals_resu...
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...
[ "Train", "a", "booster", "with", "given", "parameters", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/training.py#L115-L216
train
dmlc/xgboost
python-package/xgboost/training.py
mknfold
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 and folds is None: # Do standard k-fold cros...
python
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 and folds is None: # Do standard k-fold cros...
[ "def", "mknfold", "(", "dall", ",", "nfold", ",", "param", ",", "seed", ",", "evals", "=", "(", ")", ",", "fpreproc", "=", "None", ",", "stratified", "=", "False", ",", "folds", "=", "None", ",", "shuffle", "=", "True", ")", ":", "evals", "=", "l...
Make an n-fold list of CVPack from random indices.
[ "Make", "an", "n", "-", "fold", "list", "of", "CVPack", "from", "random", "indices", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/training.py#L237-L286
train
dmlc/xgboost
python-package/xgboost/training.py
aggcv
def aggcv(rlist): # pylint: disable=invalid-name """ 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. """ cvmap = {} idx = r...
python
def aggcv(rlist): # pylint: disable=invalid-name """ 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. """ cvmap = {} idx = r...
[ "def", "aggcv", "(", "rlist", ")", ":", "# pylint: disable=invalid-name", "cvmap", "=", "{", "}", "idx", "=", "rlist", "[", "0", "]", ".", "split", "(", ")", "[", "0", "]", "for", "line", "in", "rlist", ":", "arr", "=", "line", ".", "split", "(", ...
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.
[ "Aggregate", "cross", "-", "validation", "results", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/training.py#L289-L318
train
dmlc/xgboost
python-package/xgboost/training.py
cv
def cv(params, dtrain, num_boost_round=10, nfold=3, stratified=False, folds=None, metrics=(), obj=None, feval=None, maximize=False, early_stopping_rounds=None, fpreproc=None, as_pandas=True, verbose_eval=None, show_stdv=True, seed=0, callbacks=None, shuffle=True): # pylint: disable = invalid-na...
python
def cv(params, dtrain, num_boost_round=10, nfold=3, stratified=False, folds=None, metrics=(), obj=None, feval=None, maximize=False, early_stopping_rounds=None, fpreproc=None, as_pandas=True, verbose_eval=None, show_stdv=True, seed=0, callbacks=None, shuffle=True): # pylint: disable = invalid-na...
[ "def", "cv", "(", "params", ",", "dtrain", ",", "num_boost_round", "=", "10", ",", "nfold", "=", "3", ",", "stratified", "=", "False", ",", "folds", "=", "None", ",", "metrics", "=", "(", ")", ",", "obj", "=", "None", ",", "feval", "=", "None", "...
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...
[ "Cross", "-", "validation", "with", "given", "parameters", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/training.py#L321-L474
train
dmlc/xgboost
python-package/xgboost/training.py
CVPack.update
def update(self, iteration, fobj): """"Update the boosters for one iteration""" self.bst.update(self.dtrain, iteration, fobj)
python
def update(self, iteration, fobj): """"Update the boosters for one iteration""" self.bst.update(self.dtrain, iteration, fobj)
[ "def", "update", "(", "self", ",", "iteration", ",", "fobj", ")", ":", "self", ".", "bst", ".", "update", "(", "self", ".", "dtrain", ",", "iteration", ",", "fobj", ")" ]
Update the boosters for one iteration
[ "Update", "the", "boosters", "for", "one", "iteration" ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/training.py#L228-L230
train
dmlc/xgboost
python-package/xgboost/training.py
CVPack.eval
def eval(self, iteration, feval): """"Evaluate the CVPack for one iteration.""" return self.bst.eval_set(self.watchlist, iteration, feval)
python
def eval(self, iteration, feval): """"Evaluate the CVPack for one iteration.""" return self.bst.eval_set(self.watchlist, iteration, feval)
[ "def", "eval", "(", "self", ",", "iteration", ",", "feval", ")", ":", "return", "self", ".", "bst", ".", "eval_set", "(", "self", ".", "watchlist", ",", "iteration", ",", "feval", ")" ]
Evaluate the CVPack for one iteration.
[ "Evaluate", "the", "CVPack", "for", "one", "iteration", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/training.py#L232-L234
train
dmlc/xgboost
python-package/xgboost/callback.py
_get_callback_context
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' return context
python
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' return context
[ "def", "_get_callback_context", "(", "env", ")", ":", "if", "env", ".", "model", "is", "not", "None", "and", "env", ".", "cvfolds", "is", "None", ":", "context", "=", "'train'", "elif", "env", ".", "model", "is", "None", "and", "env", ".", "cvfolds", ...
return whether the current callback context is cv or train
[ "return", "whether", "the", "current", "callback", "context", "is", "cv", "or", "train" ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/callback.py#L10-L16
train
dmlc/xgboost
python-package/xgboost/callback.py
_fmt_metric
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]) raise ValueError("wr...
python
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]) raise ValueError("wr...
[ "def", "_fmt_metric", "(", "value", ",", "show_stdv", "=", "True", ")", ":", "if", "len", "(", "value", ")", "==", "2", ":", "return", "'%s:%g'", "%", "(", "value", "[", "0", "]", ",", "value", "[", "1", "]", ")", "if", "len", "(", "value", ")"...
format metric string
[ "format", "metric", "string" ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/callback.py#L19-L27
train
dmlc/xgboost
python-package/xgboost/callback.py
print_evaluation
def print_evaluation(period=1, show_stdv=True): """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...
python
def print_evaluation(period=1, show_stdv=True): """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...
[ "def", "print_evaluation", "(", "period", "=", "1", ",", "show_stdv", "=", "True", ")", ":", "def", "callback", "(", "env", ")", ":", "\"\"\"internal function\"\"\"", "if", "env", ".", "rank", "!=", "0", "or", "(", "not", "env", ".", "evaluation_result_lis...
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", "callback", "that", "print", "evaluation", "result", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/callback.py#L30-L57
train
dmlc/xgboost
python-package/xgboost/callback.py
record_evaluation
def record_evaluation(eval_result): """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. ...
python
def record_evaluation(eval_result): """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", ")", ":", "if", "not", "isinstance", "(", "eval_result", ",", "dict", ")", ":", "raise", "TypeError", "(", "'eval_result has to be a dictionary'", ")", "eval_result", ".", "clear", "(", ")", "def", "init", "(", "...
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.
[ "Create", "a", "call", "back", "that", "records", "the", "evaluation", "history", "into", "**", "eval_result", "**", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/callback.py#L60-L97
train
dmlc/xgboost
python-package/xgboost/callback.py
reset_learning_rate
def reset_learning_rate(learning_rates): """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 funct...
python
def reset_learning_rate(learning_rates): """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 funct...
[ "def", "reset_learning_rate", "(", "learning_rates", ")", ":", "def", "get_learning_rate", "(", "i", ",", "n", ",", "learning_rates", ")", ":", "\"\"\"helper providing the learning rate\"\"\"", "if", "isinstance", "(", "learning_rates", ",", "list", ")", ":", "if", ...
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...
[ "Reset", "learning", "rate", "after", "iteration", "1" ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/callback.py#L100-L145
train
dmlc/xgboost
python-package/xgboost/callback.py
early_stop
def early_stop(stopping_rounds, maximize=False, verbose=True): """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 la...
python
def early_stop(stopping_rounds, maximize=False, verbose=True): """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 la...
[ "def", "early_stop", "(", "stopping_rounds", ",", "maximize", "=", "False", ",", "verbose", "=", "True", ")", ":", "state", "=", "{", "}", "def", "init", "(", "env", ")", ":", "\"\"\"internal function\"\"\"", "bst", "=", "env", ".", "model", "if", "not",...
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). ...
[ "Create", "a", "callback", "that", "activates", "early", "stoppping", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/callback.py#L148-L250
train
dmlc/xgboost
doc/conf.py
run_doxygen
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)) except OSError as e: sys.stderr.write("doxygen executi...
python
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)) except OSError as e: sys.stderr.write("doxygen executi...
[ "def", "run_doxygen", "(", "folder", ")", ":", "try", ":", "retcode", "=", "subprocess", ".", "call", "(", "\"cd %s; make doxygen\"", "%", "folder", ",", "shell", "=", "True", ")", "if", "retcode", "<", "0", ":", "sys", ".", "stderr", ".", "write", "("...
Run the doxygen make command in the designated folder.
[ "Run", "the", "doxygen", "make", "command", "in", "the", "designated", "folder", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/doc/conf.py#L196-L203
train
dmlc/xgboost
python-package/xgboost/sklearn.py
_objective_decorator
def _objective_decorator(func): """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...
python
def _objective_decorator(func): """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...
[ "def", "_objective_decorator", "(", "func", ")", ":", "def", "inner", "(", "preds", ",", "dmatrix", ")", ":", "\"\"\"internal function\"\"\"", "labels", "=", "dmatrix", ".", "get_label", "(", ")", "return", "func", "(", "labels", ",", "preds", ")", "return",...
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...
[ "Decorate", "an", "objective", "function" ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/sklearn.py#L18-L50
train
dmlc/xgboost
python-package/xgboost/sklearn.py
XGBModel.set_params
def set_params(self, **params): """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 ------- ...
python
def set_params(self, **params): """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 ------- ...
[ "def", "set_params", "(", "self", ",", "*", "*", "params", ")", ":", "if", "not", "params", ":", "# Simple optimization to gain speed (inspect is slow)", "return", "self", "for", "key", ",", "value", "in", "params", ".", "items", "(", ")", ":", "if", "hasatt...
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
[ "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", "de...
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/sklearn.py#L196-L215
train
dmlc/xgboost
python-package/xgboost/sklearn.py
XGBModel.get_params
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: params['miss...
python
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: params['miss...
[ "def", "get_params", "(", "self", ",", "deep", "=", "False", ")", ":", "params", "=", "super", "(", "XGBModel", ",", "self", ")", ".", "get_params", "(", "deep", "=", "deep", ")", "if", "isinstance", "(", "self", ".", "kwargs", ",", "dict", ")", ":...
Get parameters.
[ "Get", "parameters", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/sklearn.py#L217-L226
train
dmlc/xgboost
python-package/xgboost/sklearn.py
XGBModel.get_xgb_params
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 as of version .6.' ...
python
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 as of version .6.' ...
[ "def", "get_xgb_params", "(", "self", ")", ":", "xgb_params", "=", "self", ".", "get_params", "(", ")", "random_state", "=", "xgb_params", ".", "pop", "(", "'random_state'", ")", "if", "'seed'", "in", "xgb_params", "and", "xgb_params", "[", "'seed'", "]", ...
Get xgboost type parameters.
[ "Get", "xgboost", "type", "parameters", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/sklearn.py#L228-L258
train
dmlc/xgboost
python-package/xgboost/sklearn.py
XGBModel.load_model
def load_model(self, fname): """ 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. ...
python
def load_model(self, fname): """ 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. ...
[ "def", "load_model", "(", "self", ",", "fname", ")", ":", "if", "self", ".", "_Booster", "is", "None", ":", "self", ".", "_Booster", "=", "Booster", "(", "{", "'nthread'", ":", "self", ".", "n_jobs", "}", ")", "self", ".", "_Booster", ".", "load_mode...
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...
[ "Load", "the", "model", "from", "a", "file", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/sklearn.py#L282-L300
train
dmlc/xgboost
python-package/xgboost/sklearn.py
XGBModel.fit
def fit(self, X, y, sample_weight=None, eval_set=None, eval_metric=None, early_stopping_rounds=None, verbose=True, xgb_model=None, sample_weight_eval_set=None, callbacks=None): # pylint: disable=missing-docstring,invalid-name,attribute-defined-outside-init """ Fit the gra...
python
def fit(self, X, y, sample_weight=None, eval_set=None, eval_metric=None, early_stopping_rounds=None, verbose=True, xgb_model=None, sample_weight_eval_set=None, callbacks=None): # pylint: disable=missing-docstring,invalid-name,attribute-defined-outside-init """ Fit the gra...
[ "def", "fit", "(", "self", ",", "X", ",", "y", ",", "sample_weight", "=", "None", ",", "eval_set", "=", "None", ",", "eval_metric", "=", "None", ",", "early_stopping_rounds", "=", "None", ",", "verbose", "=", "True", ",", "xgb_model", "=", "None", ",",...
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...
[ "Fit", "the", "gradient", "boosting", "model" ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/sklearn.py#L302-L408
train
dmlc/xgboost
python-package/xgboost/sklearn.py
XGBModel.predict
def predict(self, data, output_margin=False, ntree_limit=None, validate_features=True): """ 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 thr...
python
def predict(self, data, output_margin=False, ntree_limit=None, validate_features=True): """ 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 thr...
[ "def", "predict", "(", "self", ",", "data", ",", "output_margin", "=", "False", ",", "ntree_limit", "=", "None", ",", "validate_features", "=", "True", ")", ":", "# pylint: disable=missing-docstring,invalid-name", "test_dmatrix", "=", "DMatrix", "(", "data", ",", ...
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", "with", "data", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/sklearn.py#L410-L456
train
dmlc/xgboost
python-package/xgboost/sklearn.py
XGBModel.apply
def apply(self, X, ntree_limit=0): """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 ...
python
def apply(self, X, ntree_limit=0): """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 ...
[ "def", "apply", "(", "self", ",", "X", ",", "ntree_limit", "=", "0", ")", ":", "test_dmatrix", "=", "DMatrix", "(", "X", ",", "missing", "=", "self", ".", "missing", ",", "nthread", "=", "self", ".", "n_jobs", ")", "return", "self", ".", "get_booster...
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 --...
[ "Return", "the", "predicted", "leaf", "every", "tree", "for", "each", "sample", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/sklearn.py#L458-L479
train
dmlc/xgboost
python-package/xgboost/sklearn.py
XGBModel.feature_importances_
def feature_importances_(self): """ 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...
python
def feature_importances_(self): """ 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...
[ "def", "feature_importances_", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "'booster'", ",", "None", ")", "is", "not", "None", "and", "self", ".", "booster", "!=", "'gbtree'", ":", "raise", "AttributeError", "(", "'Feature importance is not defin...
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 ...
[ "Feature", "importances", "property" ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/sklearn.py#L524-L546
train
dmlc/xgboost
python-package/xgboost/sklearn.py
XGBModel.coef_
def coef_(self): """ 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...
python
def coef_(self): """ 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...
[ "def", "coef_", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "'booster'", ",", "None", ")", "is", "not", "None", "and", "self", ".", "booster", "!=", "'gblinear'", ":", "raise", "AttributeError", "(", "'Coefficients are not defined for Booster typ...
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`). ...
[ "Coefficients", "property" ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/sklearn.py#L549-L575
train
dmlc/xgboost
python-package/xgboost/sklearn.py
XGBModel.intercept_
def intercept_(self): """ 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 ...
python
def intercept_(self): """ 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 ...
[ "def", "intercept_", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "'booster'", ",", "None", ")", "is", "not", "None", "and", "self", ".", "booster", "!=", "'gblinear'", ":", "raise", "AttributeError", "(", "'Intercept (bias) is not defined for Boo...
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`)....
[ "Intercept", "(", "bias", ")", "property" ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/sklearn.py#L578-L596
train
dmlc/xgboost
python-package/xgboost/sklearn.py
XGBClassifier.fit
def fit(self, X, y, sample_weight=None, eval_set=None, eval_metric=None, early_stopping_rounds=None, verbose=True, xgb_model=None, sample_weight_eval_set=None, callbacks=None): # pylint: disable = attribute-defined-outside-init,arguments-differ """ Fit gradient boosting c...
python
def fit(self, X, y, sample_weight=None, eval_set=None, eval_metric=None, early_stopping_rounds=None, verbose=True, xgb_model=None, sample_weight_eval_set=None, callbacks=None): # pylint: disable = attribute-defined-outside-init,arguments-differ """ Fit gradient boosting c...
[ "def", "fit", "(", "self", ",", "X", ",", "y", ",", "sample_weight", "=", "None", ",", "eval_set", "=", "None", ",", "eval_metric", "=", "None", ",", "early_stopping_rounds", "=", "None", ",", "verbose", "=", "True", ",", "xgb_model", "=", "None", ",",...
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...
[ "Fit", "gradient", "boosting", "classifier" ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/sklearn.py#L622-L746
train
dmlc/xgboost
python-package/xgboost/sklearn.py
XGBClassifier.predict
def predict(self, data, output_margin=False, ntree_limit=None, validate_features=True): """ 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 thr...
python
def predict(self, data, output_margin=False, ntree_limit=None, validate_features=True): """ 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 thr...
[ "def", "predict", "(", "self", ",", "data", ",", "output_margin", "=", "False", ",", "ntree_limit", "=", "None", ",", "validate_features", "=", "True", ")", ":", "test_dmatrix", "=", "DMatrix", "(", "data", ",", "missing", "=", "self", ".", "missing", ",...
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", "with", "data", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/sklearn.py#L748-L801
train
dmlc/xgboost
python-package/xgboost/sklearn.py
XGBClassifier.predict_proba
def predict_proba(self, data, ntree_limit=None, validate_features=True): """ 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 wan...
python
def predict_proba(self, data, ntree_limit=None, validate_features=True): """ 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 wan...
[ "def", "predict_proba", "(", "self", ",", "data", ",", "ntree_limit", "=", "None", ",", "validate_features", "=", "True", ")", ":", "test_dmatrix", "=", "DMatrix", "(", "data", ",", "missing", "=", "self", ".", "missing", ",", "nthread", "=", "self", "."...
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 ...
[ "Predict", "the", "probability", "of", "each", "data", "example", "being", "of", "a", "given", "class", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/sklearn.py#L803-L839
train
dmlc/xgboost
python-package/xgboost/sklearn.py
XGBRanker.fit
def fit(self, X, y, group, sample_weight=None, eval_set=None, sample_weight_eval_set=None, eval_group=None, eval_metric=None, early_stopping_rounds=None, verbose=False, xgb_model=None, callbacks=None): # pylint: disable = attribute-defined-outside-init,arguments-differ """ ...
python
def fit(self, X, y, group, sample_weight=None, eval_set=None, sample_weight_eval_set=None, eval_group=None, eval_metric=None, early_stopping_rounds=None, verbose=False, xgb_model=None, callbacks=None): # pylint: disable = attribute-defined-outside-init,arguments-differ """ ...
[ "def", "fit", "(", "self", ",", "X", ",", "y", ",", "group", ",", "sample_weight", "=", "None", ",", "eval_set", "=", "None", ",", "sample_weight_eval_set", "=", "None", ",", "eval_group", "=", "None", ",", "eval_metric", "=", "None", ",", "early_stoppin...
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...
[ "Fit", "the", "gradient", "boosting", "model" ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/sklearn.py#L1078-L1220
train
dmlc/xgboost
python-package/xgboost/core.py
from_pystr_to_cstr
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 NotImplementedError pointers = (ctypes.c_char_p * len(data))() if PY3: data = [bytes(d, 'utf-8') for...
python
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 NotImplementedError pointers = (ctypes.c_char_p * len(data))() if PY3: data = [bytes(d, 'utf-8') for...
[ "def", "from_pystr_to_cstr", "(", "data", ")", ":", "if", "not", "isinstance", "(", "data", ",", "list", ")", ":", "raise", "NotImplementedError", "pointers", "=", "(", "ctypes", ".", "c_char_p", "*", "len", "(", "data", ")", ")", "(", ")", "if", "PY3"...
Convert a list of Python str to C pointer Parameters ---------- data : list list of str
[ "Convert", "a", "list", "of", "Python", "str", "to", "C", "pointer" ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L60-L78
train
dmlc/xgboost
python-package/xgboost/core.py
from_cstr_to_pystr
def from_cstr_to_pystr(data, length): """Revert C pointer to Python str Parameters ---------- data : ctypes pointer pointer to data length : ctypes pointer pointer to length of data """ if PY3: res = [] for i in range(length.value): try: ...
python
def from_cstr_to_pystr(data, length): """Revert C pointer to Python str Parameters ---------- data : ctypes pointer pointer to data length : ctypes pointer pointer to length of data """ if PY3: res = [] for i in range(length.value): try: ...
[ "def", "from_cstr_to_pystr", "(", "data", ",", "length", ")", ":", "if", "PY3", ":", "res", "=", "[", "]", "for", "i", "in", "range", "(", "length", ".", "value", ")", ":", "try", ":", "res", ".", "append", "(", "str", "(", "data", "[", "i", "]...
Revert C pointer to Python str Parameters ---------- data : ctypes pointer pointer to data length : ctypes pointer pointer to length of data
[ "Revert", "C", "pointer", "to", "Python", "str" ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L81-L106
train
dmlc/xgboost
python-package/xgboost/core.py
_load_lib
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_path in lib_paths: ...
python
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_path in lib_paths: ...
[ "def", "_load_lib", "(", ")", ":", "lib_paths", "=", "find_lib_path", "(", ")", "if", "not", "lib_paths", ":", "return", "None", "try", ":", "pathBackup", "=", "os", ".", "environ", "[", "'PATH'", "]", ".", "split", "(", "os", ".", "pathsep", ")", "e...
Load xgboost Library.
[ "Load", "xgboost", "Library", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L121-L157
train
dmlc/xgboost
python-package/xgboost/core.py
ctypes2numpy
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 RuntimeError('Supported types: {}'.format(NUMPY_TO...
python
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 RuntimeError('Supported types: {}'.format(NUMPY_TO...
[ "def", "ctypes2numpy", "(", "cptr", ",", "length", ",", "dtype", ")", ":", "NUMPY_TO_CTYPES_MAPPING", "=", "{", "np", ".", "float32", ":", "ctypes", ".", "c_float", ",", "np", ".", "uint32", ":", "ctypes", ".", "c_uint", ",", "}", "if", "dtype", "not",...
Convert a ctypes pointer array to a numpy array.
[ "Convert", "a", "ctypes", "pointer", "array", "to", "a", "numpy", "array", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L179-L194
train
dmlc/xgboost
python-package/xgboost/core.py
ctypes2buffer
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) if not ctypes.memmove(rptr, cptr, length)...
python
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) if not ctypes.memmove(rptr, cptr, length)...
[ "def", "ctypes2buffer", "(", "cptr", ",", "length", ")", ":", "if", "not", "isinstance", "(", "cptr", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_char", ")", ")", ":", "raise", "RuntimeError", "(", "'expected char pointer'", ")", "res", "=", "b...
Convert ctypes pointer to buffer type.
[ "Convert", "ctypes", "pointer", "to", "buffer", "type", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L197-L205
train
dmlc/xgboost
python-package/xgboost/core.py
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)
python
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)
[ "def", "c_array", "(", "ctype", ",", "values", ")", ":", "if", "isinstance", "(", "values", ",", "np", ".", "ndarray", ")", "and", "values", ".", "dtype", ".", "itemsize", "==", "ctypes", ".", "sizeof", "(", "ctype", ")", ":", "return", "(", "ctype",...
Convert a python string to c array.
[ "Convert", "a", "python", "string", "to", "c", "array", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L213-L217
train
dmlc/xgboost
python-package/xgboost/core.py
_maybe_pandas_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 all(dtype.name in PANDAS_DTYPE_MAPPER for dtype in data_dt...
python
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 all(dtype.name in PANDAS_DTYPE_MAPPER for dtype in data_dt...
[ "def", "_maybe_pandas_data", "(", "data", ",", "feature_names", ",", "feature_types", ")", ":", "if", "not", "isinstance", "(", "data", ",", "DataFrame", ")", ":", "return", "data", ",", "feature_names", ",", "feature_types", "data_dtypes", "=", "data", ".", ...
Extract internal data from pd.DataFrame for DMatrix data
[ "Extract", "internal", "data", "from", "pd", ".", "DataFrame", "for", "DMatrix", "data" ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L226-L255
train
dmlc/xgboost
python-package/xgboost/core.py
_maybe_dt_data
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) bad_fields = [data.names[i] ...
python
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) bad_fields = [data.names[i] ...
[ "def", "_maybe_dt_data", "(", "data", ",", "feature_names", ",", "feature_types", ")", ":", "if", "not", "isinstance", "(", "data", ",", "DataTable", ")", ":", "return", "data", ",", "feature_names", ",", "feature_types", "data_types_names", "=", "tuple", "(",...
Validate feature names and types if data table
[ "Validate", "feature", "names", "and", "types", "if", "data", "table" ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L279-L303
train