61 matches found for 'Python'

Scopes
**Python** has closures, similar to Javascript, since functions are first class objects. But unlike Javascript, there are some subtle gotchas in regards to working with function scopes.

Source: https://github.com/rkenmi/R-Typo I recently configured one of my pet projects to work with pyinstaller, which happens to be a nifty tool for creating one-file executables with multi-platform support.

There are a few ways to search for a string in **Python** (3+):
String operations
str.find(sub[, start[, end]])]
"shadow walker".find('w') => 5
This gives you the index of the first match.

NumPy
NumPy is a **Python** library for numerical computing that offers multi-dimensional arrays and indices as data structures and additional high-level math utilities.
ndarray
The unique offering of NumPy is the ndarray data structure, which stands for n-dimensional array.

... choices represented by any particular digit, a for loop is helpful.
Solution
The following **Python** code implements the mnemonic algorithm using a dictionary, closures, and recursion.

Here is one way to do an arithmetic multiply on two positive integers only using <<, >>, and +, without using the * or / operators. The idea is to keep shifting n1 to the left by 1, as n2 is shifted to the right by 1.

Lambdas are simply anonymous functions for **Python**. We often don't want to write a whole new function with a name if the function itself only consists of one line of code. It is tedious, even though it might be less scary to see.

Problem In computer science, a trie (pronounced "try"), also called digital tree, radix tree or prefix tree, is a kind of search treeāan ordered tree data structure used to store a dynamic set or associative array where the keys are usually strings.

This is an array/list trick that saves about O(n) in space complexity by taking advantage of a given array with integers representing indices. For this example problem, suppose that we want to apply some permutation P to an array A.

Problem Detect a cycle in a linked list and return the node that represents the start of the cycle. Input head: a pointer to the linked list Approach First, lets concentrate on how to detect a cycle in a linked list.

... modify our DFS algorithm above to account for this.
First we'll define some global stack list. **Python** Lists can be used very much like stacks with its append/pop that are synonymous to a Stack data structure's push/pop.

... in {"a": "b"} => false // "c" is not a property (or key) of the object
WARNING: Unlike **Python**'s in keyword, in Javascript this can work against you. For example, if you try to use in like you do in **Python** with arrays, you will be doing a property lookup, rather than a value lookup.

... the colors, I was given a domain of set(['red','blue','white','yellow','green']). Additionally, a **Python** dictionary is given that contains each country and their adjacent countries.
For example, Egypt is right next to Libya and Sudan.

... in the hash table, we can look them up in constant time O(1).
Here is a working pseudocode in **Python**.
def count_paths_with_sum(node, target_sum, running_sum, hash_table):
if node is None:
return 0
running_sum += node.

Let's discuss primes! A natural number is considered a prime if it is: Greater than 1 Its divisors are only 1 and itself Examples: \(5\) has two divisors: \(\frac{5}{1} = 5\) and \(\frac{5}{5} = 1\) Which means \(5\) is a prime.

... like entries are being deleted.
Do note that you cannot do index assignments with strings in **Python**. This is because strings are immutable.
Consider the consequences of += and = operators
This is naturally ~\(O(n)\) in time complexity because you are allocating a new string and copying over \n\ elements, where \n\ represents the amount of characters in the new string.

Given two linked list nodes, one might overlap the other. That is, one linked list might contain a sequence that is already in the other linked list. The two linked lists share a common node. Problem Build a function that takes two singly linked lists and returns a boolean output that signifies whether or not the two linked lists share a common node.

Problem Reverse all words (separated by space) in a string Input \(s\) - a string Approach Nice case and point for really examining the examples. First, a few examples of reversing words in a string.

Singly linked lists can be tricky in its own right. Without the convenience of having a pointer to the previous node that is provided in doubly-linked lists, it can be really easy to be wasteful in performance with singly linked lists.

Problem Given an array of integers, and an integer index \(k\), randomly permute the array up to index \(k\). Input \(A\) - Array of integers \(k\) - integer index representing the indices to permute up to Approach Key insights into random permutation with arrays: If only k elements are permuted in an array of size n, the algorithm for random permutation should only cost k in time complexity.

The Composition design pattern helps you unify individual objects and nested objects. Here is one use case for the composition design pattern. Meet Frank A man named F. Frank decides to write an autobiography of himself.

Notes
Sending notifications to a person whose photo you liked: RabbitMQ -> Celery
Django / **Python** for web server / application
PostgreSQL to store users, medias, friendships, etc.

... not a 0, then the bit at \(i\) is a 1.
Strings
When constructing strings, use a list in **Python** and add characters accordingly. The entire string can be returned via "".join(list_variable).

... = \(y_\max - y\)
The solutions below were written years ago and are still applicable for **Python**istas who like **Python** shortcuts (such as the ~ operator) to write as little code as possible.

var jsav = new JSAV("av-sym"); jsav.label("Symmetric tree"); var bt = jsav.ds.binarytree(); bt.root("5"); // set the value of the root bt.root().left("3"); // set left child bt.

... that great at serving static content for a large number of requests vs. NetScaler load balancing
**Python** is fast enough
There are many other bottlenecks such as waiting for calls from DB, cache, etc.

...
Languages
General
Rust or Go
Strings
Unicode vs. ASCII
Encoding, Encrypting, Hashing
**Python**
Awesome **Python**
C**Python** Time Complexity
PyPy vs C**Python**
strings and bytesarray (**Python** 3+)
Performance Tips
Javascript, ES6
ES6 Destructuring
Classes suck in Javascript
React
Hooking up React Redux with Django Backend
Import issues with IntelliJ / WebStorm
jQuery
jQuery Cheat Sheet
Chaining vs.

Problem Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. Examples: Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4.

Supervised Learning In supervised learning, we take some data and predict an output in a pre-defined structure. There are two categories: Regression: When a function is given some input variables, what is the continuous output? i.

Problem Given a pre-order traversal array of integers and an in-order traversal array of integers, construct a binary tree. Input preorder - array of integers inorder - array of integers # Definition for a binary tree node.

... In the code snippet below, a second reducer is used to output sorted rating counts by movie ID.
**Python** example: MapReduce for counting IMDB movie ratings sorted by popularity:
from mrjob.

... is improved by only storing unique permutations.
Solution
There is one caveat with **Python** here: Lists cannot be hashed. Lists cannot be hashed because they are mutable data structures.

Problem Given a matrix of integers, there are many paths to take from the top left to the bottom right. For each path, the smallest number in the path is the min of the path. Of all the min paths, find the maximum min path.

HTTP vs. HTTPS HTTP stands for Hypertext Transfer Protocol. It typically runs on TCP port 80. It is a protocol for sending data through browsers in the form of webpages and such. One major flaw with HTTP is that it is vulnerable to man in the middle attacks.

Problem Given an array of integers representing stock prices, with each index representing a different day, find the maximum profit by selling at most two stocks. The buy/sell dates must not overlap.

Problem Return the values of a binary tree using in-order traversal, iteratively. Input node: Has 3 properties .val: Integer value of the node .left: A pointer to another node object, or None if null .

... Lambda can be done in many ways; as of this writing, one can write a AWS Lambda application with **Python**, Node.js, or Java 8. To build AWS Lambda applications, an open-source framework called AWS SAM (Serverless Application Model) can be used.

Preface Elasticsearch is a distributed, open source search and analytics engine for all types of data, including textual, numerical, geospatial, structured, and unstructured. Key Terms: Document - Serialized JSON data.

Problem Given an array of characters, replace all occurrences of a space with another string. Assume that the array has enough space to contain all of the replacements. Input A - An array of characters which may or may not have spaces word - The string to replace spaces with.

... interpolation to escape variables:
Javascript:
let foo = "bar";
console.log(`Hi ${foo}`);
**Python**:
foo = "bar"
print(f"Hi {foo}")
C#:
string foo = "bar";
Console.Wri

Authentication Authentication means to verify who you are. Basic Auth Sensitive data required for login is encoded with Base64. Base64 is very easy to decode. Not recommended and probably the least secure authentication method, but easy to implement.

Problem Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h.

Introduction Sharding can be summarized as a technique in which a database table can be split into multiple database servers to optimize read/write performance. Benefits include: Optimized query time Instead of having one huge database table, you have multiple smaller tables in more than one machine.

... Java / Scala based, which might be difficult to work with when passing datasets over from **Python**.
DataFrames data are distributed across a cluster of machines, not just cores .

... this leads to the function acting like a class in other notable languages like C++, Java, or **Python**.
Since functions are first-class, callbacks are possible, as well as anonymous functions and closures.

Problem Given a 2D array which represents a maze, a start point, and an end point, find a path from the start point to the end point if it exists. Input maze: 2D boolean array of size greater than 1 x 1, where False represents a wall (not traversable) and True represents an empty space (traversable) start: an object with x, y coordinates end: an object with x, y coordinates Approach The key to solving this problem is DFS.

var jsav = new JSAV("ll"); jsav.label("Two sorted lists"); var ll1 = jsav.ds.list(); var ll2 = jsav.ds.list(); ll1.addLast("5").addLast("7").addLast("9"); ll2.addLast("1").addLast("2").

Problem Given a collection of intervals, merge all overlapping intervals. Example 1: Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].

Problem Given an array nums containing \(n + 1\) integers where each integer is between \(1\) and \(n\) (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

Problem Merge \(k\) sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example: Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6 Input lists - an array of linked list pointers # Definition for singly-linked list.

NoSQL NoSQL is a category of databases that aren't relational. For example, MySQL would be a relational database, where as MongoDB would be a NoSQL database. Back then, relational databases were the tried-and-true, prevalent and reliable data stores.

Problem Given a 2D array of black-and-white points and an entry point, flip the color of all points connected to the entry point (including the entry point itself). Input A: 2D boolean array of size greater than \(n\) \times \(m\), where False represents the color black and True represents the color white.

Problem A message containing letters from A-Z can be encoded into numbers using the following mapping: 'A' -> "1" 'B' -> "2" ... 'Z' -> "26" To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways).

... languages or systems; it allows you to compile schemas for your data in popular languages such as **Python**, C++, Go, Java, etc.
protobuf is backwards-compatible, meaning that your program can still use deprecated data without breaking anything.

Problem Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

var jsav = new JSAV("av-sym"); jsav.label("A sorted array rotated to the left by 3"); var arr = jsav.ds.array([25, 28, 29, 34, 1, 15, 20]); Problem Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

Problem Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3.

Problem An array of integers naturally defines a set of lines parallel to the Y-axis, starting from x = 0 as illustrated in the figure above. The goal of this problem is to find the pair of lines that together with the X-axis "trap" the most water.

There are two ways to do topological sorts: DFS To perform a topological sort via DFS, you will need the following: Adjacency Lists A "visited" set Recursion Recall that DFS itself will not give you nodes in topological ordering.

Problem With a binary tree as input, determine if the tree is a BST or not Input node: Has 3 properties .val: Integer value of the node .left: A pointer to another node object, or None if null .