Search Results

61 matches found for 'Python'

Python Essentials

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.

Arcade fun with Python and pygame

Source: 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.

String Manipulation in Python 3+

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 vs. Pandas, and other flavors (Dask, Modin, Ray)

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.

Phone Number Mnemonics in Python

... 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.

Recursive multiply function in Python using + and binary shifts

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.

Intro to Python Lambda

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.

Build a Trie in Python

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.

Cyclic Permutation

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.

Detecting a cycle in a linked list

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.

4 Line Depth-first Search

... 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.

Javascript Essentials

... 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.

Paint adjacent boundaries with distinct colors

... 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.

Counting the path of sums

... 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.

Python String Tricks - Performance considerations

... 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.

Overlapping linked lists

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.

Reversing words in a string : the double reverse

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.

Reversing sublists of singly linked lists

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.

Random Permutation

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.

Composite Pattern

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.

Scaling Instragram Infrastructure

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.

Algorithm Handbook

... 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).

Rotate a 2D Matrix

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

Symmetry in a Tree

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.

Seattle Conference on Scalability: YouTube Scalability

... 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.

Useful Links

... Languages General Rust or Go Strings Unicode vs. ASCII Encoding, Encrypting, Hashing Python Awesome Python CPython Time Complexity PyPy vs CPython 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.

Perfect Squares

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.

Machine Learning Basics

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.

Build a Binary Tree with Pre-order and In-order traversal data

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.

A primer on MapReduce

... 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.

Unique Permutations

... 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.

Find the maximum min path

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.

Web Development 101

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.

Buy and Sell Two Stocks

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.

Iterative In-Order Traversal

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 .

AWS Lambda and other Maven projects

... 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.

Atomic operations with Elasticsearch

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.

Replace all occurrences of a space inside an array

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.

Escape from the Strings

... 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.

Queue Reconstruction by Height

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.

Sharding Techniques

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.

DataFrames (a software engineer's perspective)

... 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 .

Javascript Concepts

... 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.

Find a path in a maze from start to finish

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.

Merging Sorted Linked Lists

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").

Merge Intervals

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].

Find the duplicate number

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.

Merge k sorted linked lists

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 - the Radical Databases

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.

Flip adjacent colors in a 2D matrix

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.

Decode number of ways

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).

Google Protocol Buffers

... 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.

Next Permutation

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).

Search in a rotated sorted array

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.

Longest Substring Without Repeating Characters

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.

Compute the max. water trapped by a pair of vertical lines

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.

Topological Sorting

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.

Validate a BST

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 .

Algorithm Interview Problems

... Number Greedy Algorithms Queue Reconstruction By Height Trie Build a Trie in Python Invariant Compute the max. water trapped by a pair of vertical lines