response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
It should be possible to get a TreeNode by its ID.
def test_get_tree_node_by_id() -> None: """It should be possible to get a TreeNode by its ID.""" tree = Tree[None]("Anakin") child = tree.root.add("Leia") grandchild = child.add("Ben") assert tree.get_node_by_id(tree.root.id).id == tree.root.id assert tree.get_node_by_id(child.id).id == child.id assert tree.get_node_by_id(grandchild.id).id == grandchild.id with pytest.raises(UnknownNodeID): tree.get_node_by_id(cast(NodeID, grandchild.id + 1000))
Get the label of a node as a string
def label_of(node: TreeNode[None]): """Get the label of a node as a string""" return str(node.label)
A node's children property should act like an immutable list.
def test_tree_node_children() -> None: """A node's children property should act like an immutable list.""" CHILDREN = 23 tree = Tree[None]("Root") for child in range(CHILDREN): tree.root.add(str(child)) assert len(tree.root.children) == CHILDREN for child in range(CHILDREN): assert label_of(tree.root.children[child]) == str(child) assert label_of(tree.root.children[0]) == "0" assert label_of(tree.root.children[-1]) == str(CHILDREN - 1) assert [label_of(node) for node in tree.root.children] == [ str(n) for n in range(CHILDREN) ] assert [label_of(node) for node in tree.root.children[:2]] == [ str(n) for n in range(2) ] with pytest.raises(TypeError): tree.root.children[0] = tree.root.children[1] with pytest.raises(TypeError): del tree.root.children[0] with pytest.raises(TypeError): del tree.root.children[0:2]
It should be possible to modify a TreeNode's label.
def test_tree_node_label() -> None: """It should be possible to modify a TreeNode's label.""" node = TreeNode(Tree[None]("Xenomorph Lifecycle"), None, 0, "Facehugger") assert node.label == Text("Facehugger") node.label = "Chestbuster" assert node.label == Text("Chestbuster")
It should be possible to modify a TreeNode's label when created via a Tree.
def test_tree_node_label_via_tree() -> None: """It should be possible to modify a TreeNode's label when created via a Tree.""" tree = Tree[None]("Xenomorph Lifecycle") node = tree.root.add("Facehugger") assert node.label == Text("Facehugger") node.label = "Chestbuster" assert node.label == Text("Chestbuster")
It should be possible to access a TreeNode's parent.
def test_tree_node_parent() -> None: """It should be possible to access a TreeNode's parent.""" tree = Tree[None]("Anakin") child = tree.root.add("Leia") grandchild = child.add("Ben") assert tree.root.parent is None assert grandchild.parent == child assert child.parent == tree.root
Link IDs have a random ID and system path which is a problem for reproducible tests.
def replace_link_ids(render: str) -> str: """Link IDs have a random ID and system path which is a problem for reproducible tests. """ return re_link_ids.sub("id=0;foo\x1b", render)
No active worker raises a specific exception.
def test_no_active_worker() -> None: """No active worker raises a specific exception.""" with pytest.raises(NoActiveWorker): get_current_worker()
Decorating a non-async method without saying explicitly that it's a thread is an error.
def test_decorate_non_async_no_thread_argument() -> None: """Decorating a non-async method without saying explicitly that it's a thread is an error.""" with pytest.raises(WorkerDeclarationError): class _(App[None]): @work def foo(self) -> None: pass
Decorating a non-async method and saying it isn't a thread is an error.
def test_decorate_non_async_no_thread_is_false() -> None: """Decorating a non-async method and saying it isn't a thread is an error.""" with pytest.raises(WorkerDeclarationError): class _(App[None]): @work(thread=False) def foo(self) -> None: pass
Print a table summarising the bindings. The table contains columns for the key(s) that trigger the binding, the method that it calls (and tries to link it to the widget itself), and the description of the binding.
def print_bindings(widget: str, bindings: list[Binding]) -> None: """Print a table summarising the bindings. The table contains columns for the key(s) that trigger the binding, the method that it calls (and tries to link it to the widget itself), and the description of the binding. """ if bindings: print("BINDINGS") print('"""') print("| Key(s) | Description |") print("| :- | :- |") for binding in bindings: print(f"| {binding.key} | {binding.description} |") if bindings: print('"""')
Print a table to document these component classes. The table contains two columns, one with the component class name and another for the description of what the component class is for. The second column is always empty.
def print_component_classes(classes: set[str]) -> None: """Print a table to document these component classes. The table contains two columns, one with the component class name and another for the description of what the component class is for. The second column is always empty. """ if classes: print("COMPONENT_CLASSES") print('"""') print("| Class | Description |") print("| :- | :- |") for cls in sorted(classes): print(f"| `{cls}` | XXX |") if classes: print('"""')
Main entrypoint. Iterates over all widgets and prints docs tables.
def main() -> None: """Main entrypoint. Iterates over all widgets and prints docs tables. """ widgets: list[str] = textual.widgets.__all__ for widget in widgets: w = getattr(textual.widgets, widget) bindings: list[Binding] = w.__dict__.get("BINDINGS", []) component_classes: set[str] = getattr(w, "COMPONENT_CLASSES", set()) if bindings or component_classes: print(widget) print() print_bindings(widget, bindings) print_component_classes(component_classes) print()
Finds root from the point 'a' onwards by Newton-Raphson method
def NewtonRaphson(func, a): ''' Finds root from the point 'a' onwards by Newton-Raphson method ''' while True: c = Decimal(a) - ( Decimal(eval(func)) / Decimal(eval(str(diff(func)))) ) a = c # This number dictates the accuracy of the answer if abs(eval(func)) < 10**-15: return c
>>> encryptMessage(4545, 'The affine cipher is a type of monoalphabetic substitution cipher.') 'VL}p MM{I}p~{HL}Gp{vp pFsH}pxMpyxIx JHL O}F{~pvuOvF{FuF{xIp~{HL}Gi'
def encryptMessage(key, message): ''' >>> encryptMessage(4545, 'The affine cipher is a type of monoalphabetic substitution cipher.') 'VL}p MM{I}p~{HL}Gp{vp pFsH}pxMpyxIx JHL O}F{~pvuOvF{FuF{xIp~{HL}Gi' ''' keyA, keyB = getKeyParts(key) checkKeys(keyA, keyB, 'encrypt') cipherText = '' for symbol in message: if symbol in SYMBOLS: symIndex = SYMBOLS.find(symbol) cipherText += SYMBOLS[(symIndex * keyA + keyB) % len(SYMBOLS)] else: cipherText += symbol return cipherText
>>> decryptMessage(4545, 'VL}p MM{I}p~{HL}Gp{vp pFsH}pxMpyxIx JHL O}F{~pvuOvF{FuF{xIp~{HL}Gi') 'The affine cipher is a type of monoalphabetic substitution cipher.'
def decryptMessage(key, message): ''' >>> decryptMessage(4545, 'VL}p MM{I}p~{HL}Gp{vp pFsH}pxMpyxIx JHL O}F{~pvuOvF{FuF{xIp~{HL}Gi') 'The affine cipher is a type of monoalphabetic substitution cipher.' ''' keyA, keyB = getKeyParts(key) checkKeys(keyA, keyB, 'decrypt') plainText = '' modInverseOfkeyA = cryptoMath.findModInverse(keyA, len(SYMBOLS)) for symbol in message: if symbol in SYMBOLS: symIndex = SYMBOLS.find(symbol) plainText += SYMBOLS[(symIndex - keyB) * modInverseOfkeyA % len(SYMBOLS)] else: plainText += symbol return plainText
>>> decrypt('TMDETUX PMDVU') Decryption using Key #0: TMDETUX PMDVU Decryption using Key #1: SLCDSTW OLCUT Decryption using Key #2: RKBCRSV NKBTS Decryption using Key #3: QJABQRU MJASR Decryption using Key #4: PIZAPQT LIZRQ Decryption using Key #5: OHYZOPS KHYQP Decryption using Key #6: NGXYNOR JGXPO Decryption using Key #7: MFWXMNQ IFWON Decryption using Key #8: LEVWLMP HEVNM Decryption using Key #9: KDUVKLO GDUML Decryption using Key #10: JCTUJKN FCTLK Decryption using Key #11: IBSTIJM EBSKJ Decryption using Key #12: HARSHIL DARJI Decryption using Key #13: GZQRGHK CZQIH Decryption using Key #14: FYPQFGJ BYPHG Decryption using Key #15: EXOPEFI AXOGF Decryption using Key #16: DWNODEH ZWNFE Decryption using Key #17: CVMNCDG YVMED Decryption using Key #18: BULMBCF XULDC Decryption using Key #19: ATKLABE WTKCB Decryption using Key #20: ZSJKZAD VSJBA Decryption using Key #21: YRIJYZC URIAZ Decryption using Key #22: XQHIXYB TQHZY Decryption using Key #23: WPGHWXA SPGYX Decryption using Key #24: VOFGVWZ ROFXW Decryption using Key #25: UNEFUVY QNEWV
def decrypt(message): """ >>> decrypt('TMDETUX PMDVU') Decryption using Key #0: TMDETUX PMDVU Decryption using Key #1: SLCDSTW OLCUT Decryption using Key #2: RKBCRSV NKBTS Decryption using Key #3: QJABQRU MJASR Decryption using Key #4: PIZAPQT LIZRQ Decryption using Key #5: OHYZOPS KHYQP Decryption using Key #6: NGXYNOR JGXPO Decryption using Key #7: MFWXMNQ IFWON Decryption using Key #8: LEVWLMP HEVNM Decryption using Key #9: KDUVKLO GDUML Decryption using Key #10: JCTUJKN FCTLK Decryption using Key #11: IBSTIJM EBSKJ Decryption using Key #12: HARSHIL DARJI Decryption using Key #13: GZQRGHK CZQIH Decryption using Key #14: FYPQFGJ BYPHG Decryption using Key #15: EXOPEFI AXOGF Decryption using Key #16: DWNODEH ZWNFE Decryption using Key #17: CVMNCDG YVMED Decryption using Key #18: BULMBCF XULDC Decryption using Key #19: ATKLABE WTKCB Decryption using Key #20: ZSJKZAD VSJBA Decryption using Key #21: YRIJYZC URIAZ Decryption using Key #22: XQHIXYB TQHZY Decryption using Key #23: WPGHWXA SPGYX Decryption using Key #24: VOFGVWZ ROFXW Decryption using Key #25: UNEFUVY QNEWV """ LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for key in range(len(LETTERS)): translated = "" for symbol in message: if symbol in LETTERS: num = LETTERS.find(symbol) num = num - key if num < 0: num = num + len(LETTERS) translated = translated + LETTERS[num] else: translated = translated + symbol print("Decryption using Key #%s: %s" % (key, translated))
Prepare the plaintext by up-casing it and separating repeated letters with X's
def prepare_input(dirty): """ Prepare the plaintext by up-casing it and separating repeated letters with X's """ dirty = ''.join([c.upper() for c in dirty if c in string.ascii_letters]) clean = "" if len(dirty) < 2: return dirty for i in range(len(dirty)-1): clean += dirty[i] if dirty[i] == dirty[i+1]: clean += 'X' clean += dirty[-1] if len(clean) & 1: clean += 'X' return clean
>>> encryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Harshil Darji') 'Ilcrism Olcvs'
def encryptMessage(key, message): """ >>> encryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Harshil Darji') 'Ilcrism Olcvs' """ return translateMessage(key, message, 'encrypt')
>>> decryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Ilcrism Olcvs') 'Harshil Darji'
def decryptMessage(key, message): """ >>> decryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Ilcrism Olcvs') 'Harshil Darji' """ return translateMessage(key, message, 'decrypt')
>>> encryptMessage(6, 'Harshil Darji') 'Hlia rDsahrij'
def encryptMessage(key, message): """ >>> encryptMessage(6, 'Harshil Darji') 'Hlia rDsahrij' """ cipherText = [''] * key for col in range(key): pointer = col while pointer < len(message): cipherText[col] += message[pointer] pointer += key return ''.join(cipherText)
>>> decryptMessage(6, 'Hlia rDsahrij') 'Harshil Darji'
def decryptMessage(key, message): """ >>> decryptMessage(6, 'Hlia rDsahrij') 'Harshil Darji' """ numCols = math.ceil(len(message) / key) numRows = key numShadedBoxes = (numCols * numRows) - len(message) plainText = [""] * numCols col = 0; row = 0; for symbol in message: plainText[col] += symbol col += 1 if (col == numCols) or (col == numCols - 1) and (row >= numRows - numShadedBoxes): col = 0 row += 1 return "".join(plainText)
>>> encryptMessage('HDarji', 'This is Harshil Darji from Dharmaj.') 'Akij ra Odrjqqs Gaisq muod Mphumrs.'
def encryptMessage(key, message): ''' >>> encryptMessage('HDarji', 'This is Harshil Darji from Dharmaj.') 'Akij ra Odrjqqs Gaisq muod Mphumrs.' ''' return translateMessage(key, message, 'encrypt')
>>> decryptMessage('HDarji', 'Akij ra Odrjqqs Gaisq muod Mphumrs.') 'This is Harshil Darji from Dharmaj.'
def decryptMessage(key, message): ''' >>> decryptMessage('HDarji', 'Akij ra Odrjqqs Gaisq muod Mphumrs.') 'This is Harshil Darji from Dharmaj.' ''' return translateMessage(key, message, 'decrypt')
A B / \ / \ B C Bl A / \ --> / / \ Bl Br UB Br C / UB UB = unbalanced node
def leftrotation(node): r''' A B / \ / \ B C Bl A / \ --> / / \ Bl Br UB Br C / UB UB = unbalanced node ''' print("left rotation node:",node.getdata()) ret = node.getleft() node.setleft(ret.getright()) ret.setright(node) h1 = my_max(getheight(node.getright()),getheight(node.getleft())) + 1 node.setheight(h1) h2 = my_max(getheight(ret.getright()),getheight(ret.getleft())) + 1 ret.setheight(h2) return ret
a mirror symmetry rotation of the leftrotation
def rightrotation(node): ''' a mirror symmetry rotation of the leftrotation ''' print("right rotation node:",node.getdata()) ret = node.getright() node.setright(ret.getleft()) ret.setleft(node) h1 = my_max(getheight(node.getright()),getheight(node.getleft())) + 1 node.setheight(h1) h2 = my_max(getheight(ret.getright()),getheight(ret.getleft())) + 1 ret.setheight(h2) return ret
A A Br / \ / \ / \ B C RR Br C LR B A / \ --> / \ --> / / \ Bl Br B UB Bl UB C \ / UB Bl RR = rightrotation LR = leftrotation
def rlrotation(node): r''' A A Br / \ / \ / \ B C RR Br C LR B A / \ --> / \ --> / / \ Bl Br B UB Bl UB C \ / UB Bl RR = rightrotation LR = leftrotation ''' node.setleft(rightrotation(node.getleft())) return leftrotation(node)
Example 8 / \ 3 10 / \ \ 1 6 14 / \ / 4 7 13
def testBinarySearchTree(): r''' Example 8 / \ 3 10 / \ \ 1 6 14 / \ / 4 7 13 ''' r''' Example After Deletion 7 / \ 1 4 ''' t = BinarySearchTree() t.insert(8) t.insert(3) t.insert(6) t.insert(1) t.insert(10) t.insert(14) t.insert(13) t.insert(4) t.insert(7) #Prints all the elements of the list in order traversal print(t.__str__()) if(t.getNode(6) is not None): print("The label 6 exists") else: print("The label 6 doesn't exist") if(t.getNode(-1) is not None): print("The label -1 exists") else: print("The label -1 doesn't exist") if(not t.empty()): print(("Max Value: ", t.getMax().getLabel())) print(("Min Value: ", t.getMin().getLabel())) t.delete(13) t.delete(10) t.delete(8) t.delete(3) t.delete(6) t.delete(14) #Gets all the elements of the tree In pre order #And it prints them list = t.traversalTree(InPreOrder, t.root) for x in list: print(x)
it's not the best solution
def check_prime(number): """ it's not the best solution """ special_non_primes = [0,1,2] if number in special_non_primes[:2]: return 2 elif number == special_non_primes[-1]: return 3 return all([number % i for i in range(2, number)])
Use a stack to check if a string of parentheses is balanced.
def balanced_parentheses(parentheses): """ Use a stack to check if a string of parentheses is balanced.""" stack = Stack(len(parentheses)) for parenthesis in parentheses: if parenthesis == '(': stack.push(parenthesis) elif parenthesis == ')': if stack.is_empty(): return False stack.pop() return stack.is_empty()
Return integer value representing an operator's precedence, or order of operation. https://en.wikipedia.org/wiki/Order_of_operations
def precedence(char): """ Return integer value representing an operator's precedence, or order of operation. https://en.wikipedia.org/wiki/Order_of_operations """ dictionary = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3} return dictionary.get(char, -1)
Convert infix notation to postfix notation using the Shunting-yard algorithm. https://en.wikipedia.org/wiki/Shunting-yard_algorithm https://en.wikipedia.org/wiki/Infix_notation https://en.wikipedia.org/wiki/Reverse_Polish_notation
def infix_to_postfix(expression): """ Convert infix notation to postfix notation using the Shunting-yard algorithm. https://en.wikipedia.org/wiki/Shunting-yard_algorithm https://en.wikipedia.org/wiki/Infix_notation https://en.wikipedia.org/wiki/Reverse_Polish_notation """ stack = Stack(len(expression)) postfix = [] for char in expression: if is_operand(char): postfix.append(char) elif char not in {'(', ')'}: while (not stack.is_empty() and precedence(char) <= precedence(stack.peek())): postfix.append(stack.pop()) stack.push(char) elif char == '(': stack.push(char) elif char == ')': while not stack.is_empty() and stack.peek() != '(': postfix.append(stack.pop()) # Pop '(' from stack. If there is no '(', there is a mismatched # parentheses. if stack.peek() != '(': raise ValueError('Mismatched parentheses') stack.pop() while not stack.is_empty(): postfix.append(stack.pop()) return ' '.join(postfix)
Prints all the words in a Trie :param node: root node of Trie :param word: Word variable should be empty at start :return: None
def print_words(node: TrieNode, word: str): # noqa: E999 This syntax is Python 3 only """ Prints all the words in a Trie :param node: root node of Trie :param word: Word variable should be empty at start :return: None """ if node.is_leaf: print(word, end=' ') for key, value in node.nodes.items(): print_words(value, word + key)
:param gray_img: gray image :param mask: mask size :return: image with median filter
def median_filter(gray_img, mask=3): """ :param gray_img: gray image :param mask: mask size :return: image with median filter """ # set image borders bd = int(mask / 2) # copy image size median_img = zeros_like(gray) for i in range(bd, gray_img.shape[0] - bd): for j in range(bd, gray_img.shape[1] - bd): # get mask according with mask kernel = ravel(gray_img[i - bd:i + bd + 1, j - bd:j + bd + 1]) # calculate mask median median = sort(kernel)[int8(divide((multiply(mask, mask)), 2) + 1)] median_img[i, j] = median return median_img
This code involves the concept of memory functions. Here we solve the subproblems which are needed unlike the below example F is a 2D array with -1s filled up
def MF_knapsack(i,wt,val,j): ''' This code involves the concept of memory functions. Here we solve the subproblems which are needed unlike the below example F is a 2D array with -1s filled up ''' global F # a global dp table for knapsack if F[i][j] < 0: if j < wt[i - 1]: val = MF_knapsack(i - 1,wt,val,j) else: val = max(MF_knapsack(i - 1,wt,val,j),MF_knapsack(i - 1,wt,val,j - wt[i - 1]) + val[i - 1]) F[i][j] = val return F[i][j]
K-Means Clustering using TensorFlow. 'vectors' should be a n*k 2-D NumPy array, where n is the number of vectors of dimensionality k. 'noofclusters' should be an integer.
def TFKMeansCluster(vectors, noofclusters): """ K-Means Clustering using TensorFlow. 'vectors' should be a n*k 2-D NumPy array, where n is the number of vectors of dimensionality k. 'noofclusters' should be an integer. """ noofclusters = int(noofclusters) assert noofclusters < len(vectors) #Find out the dimensionality dim = len(vectors[0]) #Will help select random centroids from among the available vectors vector_indices = list(range(len(vectors))) shuffle(vector_indices) #GRAPH OF COMPUTATION #We initialize a new graph and set it as the default during each run #of this algorithm. This ensures that as this function is called #multiple times, the default graph doesn't keep getting crowded with #unused ops and Variables from previous function calls. graph = tf.Graph() with graph.as_default(): #SESSION OF COMPUTATION sess = tf.Session() ##CONSTRUCTING THE ELEMENTS OF COMPUTATION ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points centroids = [tf.Variable((vectors[vector_indices[i]])) for i in range(noofclusters)] ##These nodes will assign the centroid Variables the appropriate ##values centroid_value = tf.placeholder("float64", [dim]) cent_assigns = [] for centroid in centroids: cent_assigns.append(tf.assign(centroid, centroid_value)) ##Variables for cluster assignments of individual vectors(initialized ##to 0 at first) assignments = [tf.Variable(0) for i in range(len(vectors))] ##These nodes will assign an assignment Variable the appropriate ##value assignment_value = tf.placeholder("int32") cluster_assigns = [] for assignment in assignments: cluster_assigns.append(tf.assign(assignment, assignment_value)) ##Now lets construct the node that will compute the mean #The placeholder for the input mean_input = tf.placeholder("float", [None, dim]) #The Node/op takes the input and computes a mean along the 0th #dimension, i.e. the list of input vectors mean_op = tf.reduce_mean(mean_input, 0) ##Node for computing Euclidean distances #Placeholders for input v1 = tf.placeholder("float", [dim]) v2 = tf.placeholder("float", [dim]) euclid_dist = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub( v1, v2), 2))) ##This node will figure out which cluster to assign a vector to, ##based on Euclidean distances of the vector from the centroids. #Placeholder for input centroid_distances = tf.placeholder("float", [noofclusters]) cluster_assignment = tf.argmin(centroid_distances, 0) ##INITIALIZING STATE VARIABLES ##This will help initialization of all Variables defined with respect ##to the graph. The Variable-initializer should be defined after ##all the Variables have been constructed, so that each of them ##will be included in the initialization. init_op = tf.initialize_all_variables() #Initialize all variables sess.run(init_op) ##CLUSTERING ITERATIONS #Now perform the Expectation-Maximization steps of K-Means clustering #iterations. To keep things simple, we will only do a set number of #iterations, instead of using a Stopping Criterion. noofiterations = 100 for iteration_n in range(noofiterations): ##EXPECTATION STEP ##Based on the centroid locations till last iteration, compute ##the _expected_ centroid assignments. #Iterate over each vector for vector_n in range(len(vectors)): vect = vectors[vector_n] #Compute Euclidean distance between this vector and each #centroid. Remember that this list cannot be named #'centroid_distances', since that is the input to the #cluster assignment node. distances = [sess.run(euclid_dist, feed_dict={ v1: vect, v2: sess.run(centroid)}) for centroid in centroids] #Now use the cluster assignment node, with the distances #as the input assignment = sess.run(cluster_assignment, feed_dict = { centroid_distances: distances}) #Now assign the value to the appropriate state variable sess.run(cluster_assigns[vector_n], feed_dict={ assignment_value: assignment}) ##MAXIMIZATION STEP #Based on the expected state computed from the Expectation Step, #compute the locations of the centroids so as to maximize the #overall objective of minimizing within-cluster Sum-of-Squares for cluster_n in range(noofclusters): #Collect all the vectors assigned to this cluster assigned_vects = [vectors[i] for i in range(len(vectors)) if sess.run(assignments[i]) == cluster_n] #Compute new centroid location new_location = sess.run(mean_op, feed_dict={ mean_input: array(assigned_vects)}) #Assign value to appropriate variable sess.run(cent_assigns[cluster_n], feed_dict={ centroid_value: new_location}) #Return centroids and assignments centroids = sess.run(centroids) assignments = sess.run(assignments) return centroids, assignments
The DFS function simply calls itself recursively for every unvisited child of its argument. We can emulate that behaviour precisely using a stack of iterators. Instead of recursively calling with a node, we'll push an iterator to the node's children onto the iterator stack. When the iterator at the top of the stack terminates, we'll pop it off the stack.
def dfs(graph, start): """The DFS function simply calls itself recursively for every unvisited child of its argument. We can emulate that behaviour precisely using a stack of iterators. Instead of recursively calling with a node, we'll push an iterator to the node's children onto the iterator stack. When the iterator at the top of the stack terminates, we'll pop it off the stack.""" explored, stack = set(), [start] explored.add(start) while stack: v = stack.pop() # the only difference from BFS is to pop last element here instead of first one for w in graph[v]: if w not in explored: explored.add(w) stack.append(w) return explored
DFS traversal
def dfs(start): """DFS traversal""" # pylint: disable=redefined-outer-name ret = 1 visited[start] = True for v in tree.get(start): if v not in visited: ret += dfs(v) if ret % 2 == 0: cuts.append(start) return ret
2 1 3 1 4 3 5 2 6 1 7 2 8 6 9 8 10 8 On removing edges (1,3) and (1,6), we can get the desired result 2.
def even_tree(): """ 2 1 3 1 4 3 5 2 6 1 7 2 8 6 9 8 10 8 On removing edges (1,3) and (1,6), we can get the desired result 2. """ dfs(1)
Tarjan's algo for finding strongly connected components in a directed graph Uses two main attributes of each node to track reachability, the index of that node within a component(index), and the lowest index reachable from that node(lowlink). We then perform a dfs of the each component making sure to update these parameters for each node and saving the nodes we visit on the way. If ever we find that the lowest reachable node from a current node is equal to the index of the current node then it must be the root of a strongly connected component and so we save it and it's equireachable vertices as a strongly connected component. Complexity: strong_connect() is called at most once for each node and has a complexity of O(|E|) as it is DFS. Therefore this has complexity O(|V| + |E|) for a graph G = (V, E)
def tarjan(g): """ Tarjan's algo for finding strongly connected components in a directed graph Uses two main attributes of each node to track reachability, the index of that node within a component(index), and the lowest index reachable from that node(lowlink). We then perform a dfs of the each component making sure to update these parameters for each node and saving the nodes we visit on the way. If ever we find that the lowest reachable node from a current node is equal to the index of the current node then it must be the root of a strongly connected component and so we save it and it's equireachable vertices as a strongly connected component. Complexity: strong_connect() is called at most once for each node and has a complexity of O(|E|) as it is DFS. Therefore this has complexity O(|V| + |E|) for a graph G = (V, E) """ n = len(g) stack = deque() on_stack = [False for _ in range(n)] index_of = [-1 for _ in range(n)] lowlink_of = index_of[:] def strong_connect(v, index, components): index_of[v] = index # the number when this node is seen lowlink_of[v] = index # lowest rank node reachable from here index += 1 stack.append(v) on_stack[v] = True for w in g[v]: if index_of[w] == -1: index = strong_connect(w, index, components) lowlink_of[v] = lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] elif on_stack[w]: lowlink_of[v] = lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] if lowlink_of[v] == index_of[v]: component = [] w = stack.pop() on_stack[w] = False component.append(w) while w != v: w = stack.pop() on_stack[w] = False component.append(w) components.append(component) return index components = [] for v in range(n): if index_of[v] == -1: strong_connect(v, 0, components) return components
[summary] Regroups the given binary string. Arguments: bitString32 {[string]} -- [32 bit binary] Raises: ValueError -- [if the given string not are 32 bit binary string] Returns: [string] -- [32 bit binary string]
def rearrange(bitString32): """[summary] Regroups the given binary string. Arguments: bitString32 {[string]} -- [32 bit binary] Raises: ValueError -- [if the given string not are 32 bit binary string] Returns: [string] -- [32 bit binary string] """ if len(bitString32) != 32: raise ValueError("Need length 32") newString = "" for i in [3,2,1,0]: newString += bitString32[8*i:8*i+8] return newString
[summary] Converts the given integer into 8-digit hex number. Arguments: i {[int]} -- [integer]
def reformatHex(i): """[summary] Converts the given integer into 8-digit hex number. Arguments: i {[int]} -- [integer] """ hexrep = format(i,'08x') thing = "" for i in [3,2,1,0]: thing += hexrep[2*i:2*i+2] return thing
[summary] Fills up the binary string to a 512 bit binary string Arguments: bitString {[string]} -- [binary string] Returns: [string] -- [binary string]
def pad(bitString): """[summary] Fills up the binary string to a 512 bit binary string Arguments: bitString {[string]} -- [binary string] Returns: [string] -- [binary string] """ startLength = len(bitString) bitString += '1' while len(bitString) % 512 != 448: bitString += '0' lastPart = format(startLength,'064b') bitString += rearrange(lastPart[32:]) + rearrange(lastPart[:32]) return bitString
[summary] Iterator: Returns by each call a list of length 16 with the 32 bit integer blocks. Arguments: bitString {[string]} -- [binary string >= 512]
def getBlock(bitString): """[summary] Iterator: Returns by each call a list of length 16 with the 32 bit integer blocks. Arguments: bitString {[string]} -- [binary string >= 512] """ currPos = 0 while currPos < len(bitString): currPart = bitString[currPos:currPos+512] mySplits = [] for i in range(16): mySplits.append(int(rearrange(currPart[32*i:32*i+32]),2)) yield mySplits currPos += 512
[summary] Returns a 32-bit hash code of the string 'testString' Arguments: testString {[string]} -- [message]
def md5me(testString): """[summary] Returns a 32-bit hash code of the string 'testString' Arguments: testString {[string]} -- [message] """ bs ='' for i in testString: bs += format(ord(i),'08b') bs = pad(bs) tvals = [int(2**32 * abs(math.sin(i+1))) for i in range(64)] a0 = 0x67452301 b0 = 0xefcdab89 c0 = 0x98badcfe d0 = 0x10325476 s = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, \ 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, \ 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, \ 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21 ] for m in getBlock(bs): A = a0 B = b0 C = c0 D = d0 for i in range(64): if i <= 15: #f = (B & C) | (not32(B) & D) f = D ^ (B & (C ^ D)) g = i elif i<= 31: #f = (D & B) | (not32(D) & C) f = C ^ (D & (B ^ C)) g = (5*i+1) % 16 elif i <= 47: f = B ^ C ^ D g = (3*i+5) % 16 else: f = C ^ (B | not32(D)) g = (7*i) % 16 dtemp = D D = C C = B B = sum32(B,leftrot32((A + f + tvals[i] + m[g]) % 2**32, s[i])) A = dtemp a0 = sum32(a0, A) b0 = sum32(b0, B) c0 = sum32(c0, C) d0 = sum32(d0, D) digest = reformatHex(a0) + reformatHex(b0) + reformatHex(c0) + reformatHex(d0) return digest
Provides option 'string' or 'file' to take input and prints the calculated SHA1 hash. unittest.main() has been commented because we probably dont want to run the test each time.
def main(): """ Provides option 'string' or 'file' to take input and prints the calculated SHA1 hash. unittest.main() has been commented because we probably dont want to run the test each time. """ # unittest.main() parser = argparse.ArgumentParser(description='Process some strings or files') parser.add_argument('--string', dest='input_string', default='Hello World!! Welcome to Cryptography', help='Hash the string') parser.add_argument('--file', dest='input_file', help='Hash contents of a file') args = parser.parse_args() input_string = args.input_string #In any case hash input should be a bytestring if args.input_file: with open(args.input_file, 'rb') as f: hash_input = f.read() else: hash_input = bytes(input_string, 'utf-8') print(SHA1Hash(hash_input).final_hash())
returns a zero-vector of size 'dimension'
def zeroVector(dimension): """ returns a zero-vector of size 'dimension' """ #precondition assert(isinstance(dimension,int)) return Vector([0]*dimension)
returns a unit basis vector with a One at index 'pos' (indexing at 0)
def unitBasisVector(dimension,pos): """ returns a unit basis vector with a One at index 'pos' (indexing at 0) """ #precondition assert(isinstance(dimension,int) and (isinstance(pos,int))) ans = [0]*dimension ans[pos] = 1 return Vector(ans)
input: a 'scalar' and two vectors 'x' and 'y' output: a vector computes the axpy operation
def axpy(scalar,x,y): """ input: a 'scalar' and two vectors 'x' and 'y' output: a vector computes the axpy operation """ # precondition assert(isinstance(x,Vector) and (isinstance(y,Vector)) \ and (isinstance(scalar,int) or isinstance(scalar,float))) return (x*scalar + y)
input: size (N) of the vector. random range (a,b) output: returns a random vector of size N, with random integer components between 'a' and 'b'.
def randomVector(N,a,b): """ input: size (N) of the vector. random range (a,b) output: returns a random vector of size N, with random integer components between 'a' and 'b'. """ random.seed(None) ans = [random.randint(a,b) for i in range(N)] return Vector(ans)
returns a square zero-matrix of dimension NxN
def squareZeroMatrix(N): """ returns a square zero-matrix of dimension NxN """ ans = [[0]*N for i in range(N)] return Matrix(ans,N,N)
returns a random matrix WxH with integer components between 'a' and 'b'
def randomMatrix(W,H,a,b): """ returns a random matrix WxH with integer components between 'a' and 'b' """ random.seed(None) matrix = [[random.randint(a,b) for j in range(W)] for i in range(H)] return Matrix(matrix,W,H)
In this demonstration we're generating a sample data set from the sin function in numpy. We then train a decision tree on the data set and use the decision tree to predict the label of 10 different test values. Then the mean squared error over this test is displayed.
def main(): """ In this demonstration we're generating a sample data set from the sin function in numpy. We then train a decision tree on the data set and use the decision tree to predict the label of 10 different test values. Then the mean squared error over this test is displayed. """ X = np.arange(-1., 1., 0.005) y = np.sin(X) tree = Decision_Tree(depth = 10, min_leaf_size = 10) tree.train(X,y) test_cases = (np.random.rand(10) * 2) - 1 predictions = np.array([tree.predict(x) for x in test_cases]) avg_error = np.mean((predictions - test_cases) ** 2) print("Test values: " + str(test_cases)) print("Predictions: " + str(predictions)) print("Average error: " + str(avg_error))
:param data_set: train data or test data :param example_no: example number whose error has to be checked :return: error in example pointed by example number.
def _error(example_no, data_set='train'): """ :param data_set: train data or test data :param example_no: example number whose error has to be checked :return: error in example pointed by example number. """ return calculate_hypothesis_value(example_no, data_set) - output(example_no, data_set)
Calculates hypothesis function value for a given input :param data_input_tuple: Input tuple of a particular example :return: Value of hypothesis function at that point. Note that there is an 'biased input' whose value is fixed as 1. It is not explicitly mentioned in input data.. But, ML hypothesis functions use it. So, we have to take care of it separately. Line 36 takes care of it.
def _hypothesis_value(data_input_tuple): """ Calculates hypothesis function value for a given input :param data_input_tuple: Input tuple of a particular example :return: Value of hypothesis function at that point. Note that there is an 'biased input' whose value is fixed as 1. It is not explicitly mentioned in input data.. But, ML hypothesis functions use it. So, we have to take care of it separately. Line 36 takes care of it. """ hyp_val = 0 for i in range(len(parameter_vector) - 1): hyp_val += data_input_tuple[i]*parameter_vector[i+1] hyp_val += parameter_vector[0] return hyp_val
:param data_set: test data or train data :param example_no: example whose output is to be fetched :return: output for that example
def output(example_no, data_set): """ :param data_set: test data or train data :param example_no: example whose output is to be fetched :return: output for that example """ if data_set == 'train': return train_data[example_no][1] elif data_set == 'test': return test_data[example_no][1]
Calculates hypothesis value for a given example :param data_set: test data or train_data :param example_no: example whose hypothesis value is to be calculated :return: hypothesis value for that example
def calculate_hypothesis_value(example_no, data_set): """ Calculates hypothesis value for a given example :param data_set: test data or train_data :param example_no: example whose hypothesis value is to be calculated :return: hypothesis value for that example """ if data_set == "train": return _hypothesis_value(train_data[example_no][0]) elif data_set == "test": return _hypothesis_value(test_data[example_no][0])
Calculates the sum of cost function derivative :param index: index wrt derivative is being calculated :param end: value where summation ends, default is m, number of examples :return: Returns the summation of cost derivative Note: If index is -1, this means we are calculating summation wrt to biased parameter.
def summation_of_cost_derivative(index, end=m): """ Calculates the sum of cost function derivative :param index: index wrt derivative is being calculated :param end: value where summation ends, default is m, number of examples :return: Returns the summation of cost derivative Note: If index is -1, this means we are calculating summation wrt to biased parameter. """ summation_value = 0 for i in range(end): if index == -1: summation_value += _error(i) else: summation_value += _error(i)*train_data[i][0][index] return summation_value
:param index: index of the parameter vector wrt to derivative is to be calculated :return: derivative wrt to that index Note: If index is -1, this means we are calculating summation wrt to biased parameter.
def get_cost_derivative(index): """ :param index: index of the parameter vector wrt to derivative is to be calculated :return: derivative wrt to that index Note: If index is -1, this means we are calculating summation wrt to biased parameter. """ cost_derivative_value = summation_of_cost_derivative(index, m)/m return cost_derivative_value
Randomly choose k data points as initial centroids
def get_initial_centroids(data, k, seed=None): '''Randomly choose k data points as initial centroids''' if seed is not None: # useful for obtaining consistent results np.random.seed(seed) n = data.shape[0] # number of data points # Pick K indices from range [0, N). rand_indices = np.random.randint(0, n, k) # Keep centroids as dense format, as many entries will be nonzero due to averaging. # As long as at least one document in a cluster contains a word, # it will carry a nonzero weight in the TF-IDF vector of the centroid. centroids = data[rand_indices,:] return centroids
This function runs k-means on given data and initial set of centroids. maxiter: maximum number of iterations to run.(default=500) record_heterogeneity: (optional) a list, to store the history of heterogeneity as function of iterations if None, do not store the history. verbose: if True, print how many data points changed their cluster labels in each iteration
def kmeans(data, k, initial_centroids, maxiter=500, record_heterogeneity=None, verbose=False): '''This function runs k-means on given data and initial set of centroids. maxiter: maximum number of iterations to run.(default=500) record_heterogeneity: (optional) a list, to store the history of heterogeneity as function of iterations if None, do not store the history. verbose: if True, print how many data points changed their cluster labels in each iteration''' centroids = initial_centroids[:] prev_cluster_assignment = None for itr in range(maxiter): if verbose: print(itr, end='') # 1. Make cluster assignments using nearest centroids cluster_assignment = assign_clusters(data,centroids) # 2. Compute a new centroid for each of the k clusters, averaging all data points assigned to that cluster. centroids = revise_centroids(data,k, cluster_assignment) # Check for convergence: if none of the assignments changed, stop if prev_cluster_assignment is not None and \ (prev_cluster_assignment==cluster_assignment).all(): break # Print number of new assignments if prev_cluster_assignment is not None: num_changed = np.sum(prev_cluster_assignment!=cluster_assignment) if verbose: print(' {0:5d} elements changed their cluster assignment.'.format(num_changed)) # Record heterogeneity convergence metric if record_heterogeneity is not None: # YOUR CODE HERE score = compute_heterogeneity(data,k,centroids,cluster_assignment) record_heterogeneity.append(score) prev_cluster_assignment = cluster_assignment[:] return centroids, cluster_assignment
Collect dataset of CSGO The dataset contains ADR vs Rating of a Player :return : dataset obtained from the link, as matrix
def collect_dataset(): """ Collect dataset of CSGO The dataset contains ADR vs Rating of a Player :return : dataset obtained from the link, as matrix """ response = requests.get('https://raw.githubusercontent.com/yashLadha/' + 'The_Math_of_Intelligence/master/Week1/ADRvs' + 'Rating.csv') lines = response.text.splitlines() data = [] for item in lines: item = item.split(',') data.append(item) data.pop(0) # This is for removing the labels from the list dataset = np.matrix(data) return dataset
Run steep gradient descent and updates the Feature vector accordingly_ :param data_x : contains the dataset :param data_y : contains the output associated with each data-entry :param len_data : length of the data_ :param alpha : Learning rate of the model :param theta : Feature vector (weight's for our model) ;param return : Updated Feature's, using curr_features - alpha_ * gradient(w.r.t. feature)
def run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta): """ Run steep gradient descent and updates the Feature vector accordingly_ :param data_x : contains the dataset :param data_y : contains the output associated with each data-entry :param len_data : length of the data_ :param alpha : Learning rate of the model :param theta : Feature vector (weight's for our model) ;param return : Updated Feature's, using curr_features - alpha_ * gradient(w.r.t. feature) """ n = len_data prod = np.dot(theta, data_x.transpose()) prod -= data_y.transpose() sum_grad = np.dot(prod, data_x) theta = theta - (alpha / n) * sum_grad return theta
Return sum of square error for error calculation :param data_x : contains our dataset :param data_y : contains the output (result vector) :param len_data : len of the dataset :param theta : contains the feature vector :return : sum of square error computed from given feature's
def sum_of_square_error(data_x, data_y, len_data, theta): """ Return sum of square error for error calculation :param data_x : contains our dataset :param data_y : contains the output (result vector) :param len_data : len of the dataset :param theta : contains the feature vector :return : sum of square error computed from given feature's """ prod = np.dot(theta, data_x.transpose()) prod -= data_y.transpose() sum_elem = np.sum(np.square(prod)) error = sum_elem / (2 * len_data) return error
Implement Linear regression over the dataset :param data_x : contains our dataset :param data_y : contains the output (result vector) :return : feature for line of best fit (Feature vector)
def run_linear_regression(data_x, data_y): """ Implement Linear regression over the dataset :param data_x : contains our dataset :param data_y : contains the output (result vector) :return : feature for line of best fit (Feature vector) """ iterations = 100000 alpha = 0.0001550 no_features = data_x.shape[1] len_data = data_x.shape[0] - 1 theta = np.zeros((1, no_features)) for i in range(0, iterations): theta = run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta) error = sum_of_square_error(data_x, data_y, len_data, theta) print('At Iteration %d - Error is %.5f ' % (i + 1, error)) return theta
Driver function
def main(): """ Driver function """ data = collect_dataset() len_data = data.shape[0] data_x = np.c_[np.ones(len_data), data[:, :-1]].astype(float) data_y = data[:, -1].astype(float) theta = run_linear_regression(data_x, data_y) len_result = theta.shape[1] print('Resultant Feature vector : ') for i in range(0, len_result): print('%.5f' % (theta[0, i]))
Function to fins absolute value of numbers. >>absVal(-5) 5 >>absVal(0) 0
def absVal(num): """ Function to fins absolute value of numbers. >>absVal(-5) 5 >>absVal(0) 0 """ if num < 0: return -num else: return num
#>>>absMax([0,5,1,11]) 11 >>absMax([3,-10,-2]) -10
def absMax(x): """ #>>>absMax([0,5,1,11]) 11 >>absMax([3,-10,-2]) -10 """ j =x[0] for i in x: if abs(i) > abs(j): j = i return j
# >>>absMin([0,5,1,11]) 0 # >>absMin([3,-10,-2]) -2
def absMin(x): """ # >>>absMin([0,5,1,11]) 0 # >>absMin([3,-10,-2]) -2 """ j = x[0] for i in x: if absVal(i) < absVal(j): j = i return j
Calculates derivative at point a for function f using finite difference method
def calc_derivative(f, a, h=0.001): ''' Calculates derivative at point a for function f using finite difference method ''' return (f(a+h)-f(a-h))/(2*h)
>>> isEnglish('Hello World') True >>> isEnglish('llold HorWd') False
def isEnglish(message, wordPercentage = 20, letterPercentage = 85): """ >>> isEnglish('Hello World') True >>> isEnglish('llold HorWd') False """ wordsMatch = getEnglishCount(message) * 100 >= wordPercentage numLetters = len(removeNonLetters(message)) messageLettersPercentage = (float(numLetters) / len(message)) * 100 lettersMatch = messageLettersPercentage >= letterPercentage return wordsMatch and lettersMatch
>>> englishFreqMatchScore('Hello World') 1
def englishFreqMatchScore(message): ''' >>> englishFreqMatchScore('Hello World') 1 ''' freqOrder = getFrequencyOrder(message) matchScore = 0 for commonLetter in ETAOIN[:6]: if commonLetter in freqOrder[:6]: matchScore += 1 for uncommonLetter in ETAOIN[-6:]: if uncommonLetter in freqOrder[-6:]: matchScore += 1 return matchScore
input: positive integer 'number' returns true if 'number' is prime otherwise false.
def isPrime(number): """ input: positive integer 'number' returns true if 'number' is prime otherwise false. """ import math # for function sqrt # precondition assert isinstance(number,int) and (number >= 0) , \ "'number' must been an int and positive" status = True # 0 and 1 are none primes. if number <= 1: status = False for divisor in range(2,int(round(math.sqrt(number)))+1): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: status = False break # precondition assert isinstance(status,bool), "'status' must been from type bool" return status
input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N. This function implements the algorithm called sieve of erathostenes.
def sieveEr(N): """ input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N. This function implements the algorithm called sieve of erathostenes. """ # precondition assert isinstance(N,int) and (N > 2), "'N' must been an int and > 2" # beginList: conatins all natural numbers from 2 upt to N beginList = [x for x in range(2,N+1)] ans = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(beginList)): for j in range(i+1,len(beginList)): if (beginList[i] != 0) and \ (beginList[j] % beginList[i] == 0): beginList[j] = 0 # filters actual prime numbers. ans = [x for x in beginList if x != 0] # precondition assert isinstance(ans,list), "'ans' must been from type list" return ans
input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N (inclusive) This function is more efficient as function 'sieveEr(...)'
def getPrimeNumbers(N): """ input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N (inclusive) This function is more efficient as function 'sieveEr(...)' """ # precondition assert isinstance(N,int) and (N > 2), "'N' must been an int and > 2" ans = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2,N+1): if isPrime(number): ans.append(number) # precondition assert isinstance(ans,list), "'ans' must been from type list" return ans
input: positive integer 'number' returns a list of the prime number factors of 'number'
def primeFactorization(number): """ input: positive integer 'number' returns a list of the prime number factors of 'number' """ import math # for function sqrt # precondition assert isinstance(number,int) and number >= 0, \ "'number' must been an int and >= 0" ans = [] # this list will be returns of the function. # potential prime number factors. factor = 2 quotient = number if number == 0 or number == 1: ans.append(number) # if 'number' not prime then builds the prime factorization of 'number' elif not isPrime(number): while (quotient != 1): if isPrime(factor) and (quotient % factor == 0): ans.append(factor) quotient /= factor else: factor += 1 else: ans.append(number) # precondition assert isinstance(ans,list), "'ans' must been from type list" return ans
input: positive integer 'number' >= 0 returns the greatest prime number factor of 'number'
def greatestPrimeFactor(number): """ input: positive integer 'number' >= 0 returns the greatest prime number factor of 'number' """ # precondition assert isinstance(number,int) and (number >= 0), \ "'number' bust been an int and >= 0" ans = 0 # prime factorization of 'number' primeFactors = primeFactorization(number) ans = max(primeFactors) # precondition assert isinstance(ans,int), "'ans' must been from type int" return ans
input: integer 'number' >= 0 returns the smallest prime number factor of 'number'
def smallestPrimeFactor(number): """ input: integer 'number' >= 0 returns the smallest prime number factor of 'number' """ # precondition assert isinstance(number,int) and (number >= 0), \ "'number' bust been an int and >= 0" ans = 0 # prime factorization of 'number' primeFactors = primeFactorization(number) ans = min(primeFactors) # precondition assert isinstance(ans,int), "'ans' must been from type int" return ans
input: integer 'number' returns true if 'number' is even, otherwise false.
def isEven(number): """ input: integer 'number' returns true if 'number' is even, otherwise false. """ # precondition assert isinstance(number, int), "'number' must been an int" assert isinstance(number % 2 == 0, bool), "compare bust been from type bool" return number % 2 == 0
input: integer 'number' returns true if 'number' is odd, otherwise false.
def isOdd(number): """ input: integer 'number' returns true if 'number' is odd, otherwise false. """ # precondition assert isinstance(number, int), "'number' must been an int" assert isinstance(number % 2 != 0, bool), "compare bust been from type bool" return number % 2 != 0
Goldbach's assumption input: a even positive integer 'number' > 2 returns a list of two prime numbers whose sum is equal to 'number'
def goldbach(number): """ Goldbach's assumption input: a even positive integer 'number' > 2 returns a list of two prime numbers whose sum is equal to 'number' """ # precondition assert isinstance(number,int) and (number > 2) and isEven(number), \ "'number' must been an int, even and > 2" ans = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' primeNumbers = getPrimeNumbers(number) lenPN = len(primeNumbers) # run variable for while-loops. i = 0 j = 1 # exit variable. for break up the loops loop = True while (i < lenPN and loop): j = i+1 while (j < lenPN and loop): if primeNumbers[i] + primeNumbers[j] == number: loop = False ans.append(primeNumbers[i]) ans.append(primeNumbers[j]) j += 1 i += 1 # precondition assert isinstance(ans,list) and (len(ans) == 2) and \ (ans[0] + ans[1] == number) and isPrime(ans[0]) and isPrime(ans[1]), \ "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans
Greatest common divisor input: two positive integer 'number1' and 'number2' returns the greatest common divisor of 'number1' and 'number2'
def gcd(number1,number2): """ Greatest common divisor input: two positive integer 'number1' and 'number2' returns the greatest common divisor of 'number1' and 'number2' """ # precondition assert isinstance(number1,int) and isinstance(number2,int) \ and (number1 >= 0) and (number2 >= 0), \ "'number1' and 'number2' must been positive integer." rest = 0 while number2 != 0: rest = number1 % number2 number1 = number2 number2 = rest # precondition assert isinstance(number1,int) and (number1 >= 0), \ "'number' must been from type int and positive" return number1
Least common multiple input: two positive integer 'number1' and 'number2' returns the least common multiple of 'number1' and 'number2'
def kgV(number1, number2): """ Least common multiple input: two positive integer 'number1' and 'number2' returns the least common multiple of 'number1' and 'number2' """ # precondition assert isinstance(number1,int) and isinstance(number2,int) \ and (number1 >= 1) and (number2 >= 1), \ "'number1' and 'number2' must been positive integer." ans = 1 # actual answer that will be return. # for kgV (x,1) if number1 > 1 and number2 > 1: # builds the prime factorization of 'number1' and 'number2' primeFac1 = primeFactorization(number1) primeFac2 = primeFactorization(number2) elif number1 == 1 or number2 == 1: primeFac1 = [] primeFac2 = [] ans = max(number1,number2) count1 = 0 count2 = 0 done = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in primeFac1: if n not in done: if n in primeFac2: count1 = primeFac1.count(n) count2 = primeFac2.count(n) for i in range(max(count1,count2)): ans *= n else: count1 = primeFac1.count(n) for i in range(count1): ans *= n done.append(n) # iterates through primeFac2 for n in primeFac2: if n not in done: count2 = primeFac2.count(n) for i in range(count2): ans *= n done.append(n) # precondition assert isinstance(ans,int) and (ans >= 0), \ "'ans' must been from type int and positive" return ans
Gets the n-th prime number. input: positive integer 'n' >= 0 returns the n-th prime number, beginning at index 0
def getPrime(n): """ Gets the n-th prime number. input: positive integer 'n' >= 0 returns the n-th prime number, beginning at index 0 """ # precondition assert isinstance(n,int) and (n >= 0), "'number' must been a positive int" index = 0 ans = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not isPrime(ans): ans += 1 # precondition assert isinstance(ans,int) and isPrime(ans), \ "'ans' must been a prime number and from type int" return ans
input: prime numbers 'pNumber1' and 'pNumber2' pNumber1 < pNumber2 returns a list of all prime numbers between 'pNumber1' (exclusiv) and 'pNumber2' (exclusiv)
def getPrimesBetween(pNumber1, pNumber2): """ input: prime numbers 'pNumber1' and 'pNumber2' pNumber1 < pNumber2 returns a list of all prime numbers between 'pNumber1' (exclusiv) and 'pNumber2' (exclusiv) """ # precondition assert isPrime(pNumber1) and isPrime(pNumber2) and (pNumber1 < pNumber2), \ "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" number = pNumber1 + 1 # jump to the next number ans = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not isPrime(number): number += 1 while number < pNumber2: ans.append(number) number += 1 # fetch the next prime number. while not isPrime(number): number += 1 # precondition assert isinstance(ans,list) and ans[0] != pNumber1 \ and ans[len(ans)-1] != pNumber2, \ "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans
input: positive integer 'n' >= 1 returns all divisors of n (inclusive 1 and 'n')
def getDivisors(n): """ input: positive integer 'n' >= 1 returns all divisors of n (inclusive 1 and 'n') """ # precondition assert isinstance(n,int) and (n >= 1), "'n' must been int and >= 1" from math import sqrt ans = [] # will be returned. for divisor in range(1,n+1): if n % divisor == 0: ans.append(divisor) #precondition assert ans[0] == 1 and ans[len(ans)-1] == n, \ "Error in function getDivisiors(...)" return ans
input: positive integer 'number' > 1 returns true if 'number' is a perfect number otherwise false.
def isPerfectNumber(number): """ input: positive integer 'number' > 1 returns true if 'number' is a perfect number otherwise false. """ # precondition assert isinstance(number,int) and (number > 1), \ "'number' must been an int and >= 1" divisors = getDivisors(number) # precondition assert isinstance(divisors,list) and(divisors[0] == 1) and \ (divisors[len(divisors)-1] == number), \ "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1]) == number
input: two integer 'numerator' and 'denominator' assumes: 'denominator' != 0 returns: a tuple with simplify numerator and denominator.
def simplifyFraction(numerator, denominator): """ input: two integer 'numerator' and 'denominator' assumes: 'denominator' != 0 returns: a tuple with simplify numerator and denominator. """ # precondition assert isinstance(numerator, int) and isinstance(denominator,int) \ and (denominator != 0), \ "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. gcdOfFraction = gcd(abs(numerator), abs(denominator)) # precondition assert isinstance(gcdOfFraction, int) and (numerator % gcdOfFraction == 0) \ and (denominator % gcdOfFraction == 0), \ "Error in function gcd(...,...)" return (numerator // gcdOfFraction, denominator // gcdOfFraction)
input: positive integer 'n' returns the factorial of 'n' (n!)
def factorial(n): """ input: positive integer 'n' returns the factorial of 'n' (n!) """ # precondition assert isinstance(n,int) and (n >= 0), "'n' must been a int and >= 0" ans = 1 # this will be return. for factor in range(1,n+1): ans *= factor return ans
input: positive integer 'n' returns the n-th fibonacci term , indexing by 0
def fib(n): """ input: positive integer 'n' returns the n-th fibonacci term , indexing by 0 """ # precondition assert isinstance(n, int) and (n >= 0), "'n' must been an int and >= 0" tmp = 0 fib1 = 1 ans = 1 # this will be return for i in range(n-1): tmp = ans ans += fib1 fib1 = tmp return ans
>>> moveTower(3, 'A', 'B', 'C') moving disk from A to B moving disk from A to C moving disk from B to C moving disk from A to B moving disk from C to A moving disk from C to B moving disk from A to B
def moveTower(height, fromPole, toPole, withPole): ''' >>> moveTower(3, 'A', 'B', 'C') moving disk from A to B moving disk from A to C moving disk from B to C moving disk from A to B moving disk from C to A moving disk from C to B moving disk from A to B ''' if height >= 1: moveTower(height-1, fromPole, withPole, toPole) moveDisk(fromPole, toPole) moveTower(height-1, withPole, toPole, fromPole)
:type nums: List[int] :type target: int :rtype: List[int]
def twoSum(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ chk_map = {} for index, val in enumerate(nums): compl = target - val if compl in chk_map: indices = [chk_map[compl], index] print(indices) return [indices] else: chk_map[val] = index return False
This function runs the rules of game through all points, and changes their status accordingly.(in the same canvas) @Args: -- canvas : canvas of population to run the rules on. @returns: -- None
def run(canvas): ''' This function runs the rules of game through all points, and changes their status accordingly.(in the same canvas) @Args: -- canvas : canvas of population to run the rules on. @returns: -- None ''' canvas = np.array(canvas) next_gen_canvas = np.array(create_canvas(canvas.shape[0])) for r, row in enumerate(canvas): for c, pt in enumerate(row): # print(r-1,r+2,c-1,c+2) next_gen_canvas[r][c] = __judge_point(pt,canvas[r-1:r+2,c-1:c+2]) canvas = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. return canvas.tolist()
Returns a list of all the even terms in the Fibonacci sequence that are less than n.
def fib(n): """ Returns a list of all the even terms in the Fibonacci sequence that are less than n. """ ls = [] a, b = 0, 1 while b < n: if b % 2 == 0: ls.append(b) a, b = b, a+b return ls
Collatz conjecture: start with any positive integer n.Next termis obtained from the previous term as follows: if the previous term is even, the next term is one half the previous term. If the previous term is odd, the next term is 3 times the previous term plus 1. The conjecture states the sequence will always reach 1 regaardess of starting n.
def collatz_sequence(n): """Collatz conjecture: start with any positive integer n.Next termis obtained from the previous term as follows: if the previous term is even, the next term is one half the previous term. If the previous term is odd, the next term is 3 times the previous term plus 1. The conjecture states the sequence will always reach 1 regaardess of starting n.""" sequence = [n] while n != 1: if n % 2 == 0:# even n //= 2 else: n = 3*n +1 sequence.append(n) return sequence
Consider all integer combinations of ab for 2 <= a <= 5 and 2 <= b <= 5: 22=4, 23=8, 24=16, 25=32 32=9, 33=27, 34=81, 35=243 42=16, 43=64, 44=256, 45=1024 52=25, 53=125, 54=625, 55=3125 If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms: 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 How many distinct terms are in the sequence generated by ab for 2 <= a <= 100 and 2 <= b <= 100?
def main(): """ Consider all integer combinations of ab for 2 <= a <= 5 and 2 <= b <= 5: 22=4, 23=8, 24=16, 25=32 32=9, 33=27, 34=81, 35=243 42=16, 43=64, 44=256, 45=1024 52=25, 53=125, 54=625, 55=3125 If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms: 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 How many distinct terms are in the sequence generated by ab for 2 <= a <= 100 and 2 <= b <= 100? """ collectPowers = set() currentPow = 0 N = 101 # maximum limit for a in range(2, N): for b in range(2, N): currentPow = a**b # calculates the current power collectPowers.add(currentPow) # adds the result to the set print("Number of terms ", len(collectPowers))
Pure implementation of binary search algorithm in Python Be careful collection must be sorted, otherwise result will be unpredictable :param sorted_collection: some sorted collection with comparable items :param item: item value to search :return: index of found item or None if item is not found Examples: >>> binary_search([0, 5, 7, 10, 15], 0) 0 >>> binary_search([0, 5, 7, 10, 15], 15) 4 >>> binary_search([0, 5, 7, 10, 15], 5) 1 >>> binary_search([0, 5, 7, 10, 15], 6)
def binary_search(sorted_collection, item): """Pure implementation of binary search algorithm in Python Be careful collection must be sorted, otherwise result will be unpredictable :param sorted_collection: some sorted collection with comparable items :param item: item value to search :return: index of found item or None if item is not found Examples: >>> binary_search([0, 5, 7, 10, 15], 0) 0 >>> binary_search([0, 5, 7, 10, 15], 15) 4 >>> binary_search([0, 5, 7, 10, 15], 5) 1 >>> binary_search([0, 5, 7, 10, 15], 6) """ left = 0 right = len(sorted_collection) - 1 while left <= right: midpoint = (left + right) // 2 current_item = sorted_collection[midpoint] if current_item == item: return midpoint else: if item < current_item: right = midpoint - 1 else: left = midpoint + 1 return None
Pure implementation of binary search algorithm in Python using stdlib Be careful collection must be sorted, otherwise result will be unpredictable :param sorted_collection: some sorted collection with comparable items :param item: item value to search :return: index of found item or None if item is not found Examples: >>> binary_search_std_lib([0, 5, 7, 10, 15], 0) 0 >>> binary_search_std_lib([0, 5, 7, 10, 15], 15) 4 >>> binary_search_std_lib([0, 5, 7, 10, 15], 5) 1 >>> binary_search_std_lib([0, 5, 7, 10, 15], 6)
def binary_search_std_lib(sorted_collection, item): """Pure implementation of binary search algorithm in Python using stdlib Be careful collection must be sorted, otherwise result will be unpredictable :param sorted_collection: some sorted collection with comparable items :param item: item value to search :return: index of found item or None if item is not found Examples: >>> binary_search_std_lib([0, 5, 7, 10, 15], 0) 0 >>> binary_search_std_lib([0, 5, 7, 10, 15], 15) 4 >>> binary_search_std_lib([0, 5, 7, 10, 15], 5) 1 >>> binary_search_std_lib([0, 5, 7, 10, 15], 6) """ index = bisect.bisect_left(sorted_collection, item) if index != len(sorted_collection) and sorted_collection[index] == item: return index return None
Pure implementation of binary search algorithm in Python by recursion Be careful collection must be sorted, otherwise result will be unpredictable First recursion should be started with left=0 and right=(len(sorted_collection)-1) :param sorted_collection: some sorted collection with comparable items :param item: item value to search :return: index of found item or None if item is not found Examples: >>> binary_search_std_lib([0, 5, 7, 10, 15], 0) 0 >>> binary_search_std_lib([0, 5, 7, 10, 15], 15) 4 >>> binary_search_std_lib([0, 5, 7, 10, 15], 5) 1 >>> binary_search_std_lib([0, 5, 7, 10, 15], 6)
def binary_search_by_recursion(sorted_collection, item, left, right): """Pure implementation of binary search algorithm in Python by recursion Be careful collection must be sorted, otherwise result will be unpredictable First recursion should be started with left=0 and right=(len(sorted_collection)-1) :param sorted_collection: some sorted collection with comparable items :param item: item value to search :return: index of found item or None if item is not found Examples: >>> binary_search_std_lib([0, 5, 7, 10, 15], 0) 0 >>> binary_search_std_lib([0, 5, 7, 10, 15], 15) 4 >>> binary_search_std_lib([0, 5, 7, 10, 15], 5) 1 >>> binary_search_std_lib([0, 5, 7, 10, 15], 6) """ if (right < left): return None midpoint = left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(sorted_collection, item, left, midpoint-1) else: return binary_search_by_recursion(sorted_collection, item, midpoint+1, right)
Check if collection is sorted, if not - raises :py:class:`ValueError` :param collection: collection :return: True if collection is sorted :raise: :py:class:`ValueError` if collection is not sorted Examples: >>> __assert_sorted([0, 1, 2, 4]) True >>> __assert_sorted([10, -1, 5]) Traceback (most recent call last): ... ValueError: Collection must be sorted
def __assert_sorted(collection): """Check if collection is sorted, if not - raises :py:class:`ValueError` :param collection: collection :return: True if collection is sorted :raise: :py:class:`ValueError` if collection is not sorted Examples: >>> __assert_sorted([0, 1, 2, 4]) True >>> __assert_sorted([10, -1, 5]) Traceback (most recent call last): ... ValueError: Collection must be sorted """ if collection != sorted(collection): raise ValueError('Collection must be sorted') return True