PrimerPy
https://www.primerpy.com/
Recent content on PrimerPyHugo -- gohugo.ioen-usWed, 17 Jul 2019 23:47:43 -040019. Remove Nth Node From End of List
https://www.primerpy.com/post/leetcoding/content/19-remove-nth-node-from-end/
Wed, 17 Jul 2019 23:47:43 -0400https://www.primerpy.com/post/leetcoding/content/19-remove-nth-node-from-end/Problem Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. Thought Process & White Board
Code class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeFromEnd(self, head, n): assert(n) dummyHead = ListNode(None) dummyHead.Array
https://www.primerpy.com/post/datastructure/content/array/
Tue, 16 Jul 2019 23:21:47 -0400https://www.primerpy.com/post/datastructure/content/array/What are arrays? A data structure that stores data in a continuous space For python, the most commonly used array-like data structure is list For Python, list can hold different types of data To access any element in an array, we can easily use index with time complexity of O(1) Complexity for Python List init O(1) In cpython, the init create a space of 4 to start with.279. Perfect Squares
https://www.primerpy.com/post/leetcoding/content/279-perfectsquares/
Mon, 15 Jul 2019 21:47:07 -0400https://www.primerpy.com/post/leetcoding/content/279-perfectsquares/Problem Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, …) which sum to n.
Example 1:
Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4. Example 2:
Input: n = 13 Output: 2 Explanation: 13 = 4 + 9. Thought Process since 1 is a perfect square, so for any n, there must be a solution, the worst case is n I tried the brute force solution but failed, i.102. Binary Tree Level Order Traversal
https://www.primerpy.com/post/leetcoding/content/102-binarytreelevelordertraversal/
Sun, 14 Jul 2019 19:18:55 -0400https://www.primerpy.com/post/leetcoding/content/102-binarytreelevelordertraversal/Problem Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
For example: Given binary tree [3,9,20,null,null,15,7],
3 / \ 9 20 / \ 15 7 return its level order traversal as:
[ [3], [9,20], [15,7] ] Thought Process This is a typical BFS problem Can solve it with the help of a queue In Python, can use collection.Iterative Traversal for a Binary Tree
https://www.primerpy.com/post/datastructure/content/binary-tree-traversal-nr/
Sat, 13 Jul 2019 11:20:41 -0400https://www.primerpy.com/post/datastructure/content/binary-tree-traversal-nr/Problems There are three ways to traverse a binary tree: preorder, inorder and postorder.
On Leetcode, there are three problems
144. Binary Tree Preorder Traversal Given a binary tree, return the preorder traversal of its nodes’ values.
Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,2,3] 94. Binary Tree Inorder Traversal Given a binary tree, return the inorder traversal of its nodes’ values.
Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,3,2] 145.Preorder, Inorder and Postorder Traversal for a Binary Tree
https://www.primerpy.com/post/datastructure/content/binary-tree-traversal/
Fri, 12 Jul 2019 23:55:34 -0400https://www.primerpy.com/post/datastructure/content/binary-tree-traversal/Problems There are three ways to traverse a binary tree: preorder, inorder and postorder.
On Leetcode, there are three problems
144. Binary Tree Preorder Traversal Given a binary tree, return the preorder traversal of its nodes’ values.
Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,2,3] 94. Binary Tree Inorder Traversal Given a binary tree, return the inorder traversal of its nodes’ values.
Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,3,2] 145.Hash Tables
https://www.primerpy.com/post/datastructure/content/hash-tables/
Fri, 12 Jul 2019 23:55:32 -0400https://www.primerpy.com/post/datastructure/content/hash-tables/Definition What are Hash Tables? Hash Tables are key-value pairs key must be immutable Hash Function Hash functions convert the value to key One big challenge is to calculate the key more evenly to avoid collision One common way is to calculate the mod of a prime number (the number theory is beyond the scope here) but look at two examples below Example 1:237. Delete Node in a Linked List
https://www.primerpy.com/post/leetcoding/content/237-deletenodeinall/
Thu, 11 Jul 2019 12:07:30 -0400https://www.primerpy.com/post/leetcoding/content/237-deletenodeinall/Problem Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Given linked list – head = [4,5,1,9], which looks like following:
4->5->1->9 Example 1:
Input: head = [4,5,1,9], node = 5 Output: [4,1,9] Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.24. Swap Nodes in Pairs
https://www.primerpy.com/post/leetcoding/content/24-swapnodesinpairs/
Thu, 11 Jul 2019 10:18:34 -0400https://www.primerpy.com/post/leetcoding/content/24-swapnodesinpairs/Problem Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list’s nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3. Thought Process For every node pair: front and back front’s next will be pointed to the back’s next back’s next will be pointed to the front front’s previous node’s next will be pointed to back Setting up a dummy head node will be helpful White Board Below is the white board:203. Remove Linked List Elements
https://www.primerpy.com/post/leetcoding/content/203-removelinkedlist/
Wed, 10 Jul 2019 23:20:13 -0400https://www.primerpy.com/post/leetcoding/content/203-removelinkedlist/Problem Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6 Output: 1->2->3->4->5 Thought Process the regular case is simple. e.g. to delete 6 below, we can use a node(delnode) to store 6’s next node
2->6->3 then 2’s next points to delnode’s next node, then 6’s next points to None
The tricky part is the edge case: if the deleted node is None, then return None if the deleted node is head, then delnode = head, delnode.455-AssignCookies
https://www.primerpy.com/post/leetcoding/content/455-assigncookies/
Tue, 09 Jul 2019 22:21:02 -0400https://www.primerpy.com/post/leetcoding/content/455-assigncookies/Problem Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, we can assign the cookie j to the child i, and the child i will be content.70. Climbing Stairs
https://www.primerpy.com/post/leetcoding/content/70-climbingstairs/
Tue, 09 Jul 2019 21:44:40 -0400https://www.primerpy.com/post/leetcoding/content/70-climbingstairs/Problem You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example:
Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps Example 2:226. Invert Binary Tree
https://www.primerpy.com/post/leetcoding/content/226-invertbinarytree/
Mon, 08 Jul 2019 20:55:54 -0400https://www.primerpy.com/post/leetcoding/content/226-invertbinarytree/Problem Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9 Output:
4 / \ 7 2 / \ / \ 9 6 3 1 Thought Process Can solve this question recursively.
if the root is None, return None
else, revert root’s left tree recursively, revert root’s right tree recursively
swap left, right tree
White Board Below is the white board:104. Maximum Depth of Binary Tree
https://www.primerpy.com/post/leetcoding/content/104-maxdepthbinarytree/
Mon, 08 Jul 2019 20:41:28 -0400https://www.primerpy.com/post/leetcoding/content/104-maxdepthbinarytree/Problem Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3 / \ 9 20 / \ 15 7 return its depth = 3.
Thought Process Can solve this question recursively.
find the max d for the left tree recursively find the max d for the right tree recursively return the larger d White Board Below is the white board:20. Valid Parentheses
https://www.primerpy.com/post/leetcoding/content/20-validparentheses/
Sun, 07 Jul 2019 11:30:56 -0400https://www.primerpy.com/post/leetcoding/content/20-validparentheses/Problem Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid.
Example 1:
Input: "()" Output: true Example 2:
Input: "()[]{}" Output: true Example 3:206. Reverse Linked List
https://www.primerpy.com/post/leetcoding/content/206-reversell/
Sun, 07 Jul 2019 10:08:50 -0400https://www.primerpy.com/post/leetcoding/content/206-reversell/Problem Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: NULL<-1<-2<-3<-4<-5 Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both? Thought Process if to reverse a link list iteratively, need three pointers to store
pre => previous node cur => current node nxt => next node (here nxt is different from node’s own next reference) Iterate thru ll, for any given state:447. Number of Boomerangs
https://www.primerpy.com/post/leetcoding/content/447-numberofboomerangs/
Sat, 06 Jul 2019 18:04:36 -0400https://www.primerpy.com/post/leetcoding/content/447-numberofboomerangs/Problem Given n points in the plane that are all pairwise distinct, a “boomerang” is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters). Find the number of boomerangs. You may assume that n will be at most 500 and coordinates of points are all in the range -10000, 10000.454. 4Sum II
https://www.primerpy.com/post/leetcoding/content/454-4sum/
Sat, 06 Jul 2019 13:06:54 -0400https://www.primerpy.com/post/leetcoding/content/454-4sum/Problem Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.
To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -2**28 to 2**28 - 1 and the result is guaranteed to be at most 2**31 - 1.1. Two Sum
https://www.primerpy.com/post/leetcoding/content/1-twosum/
Sat, 06 Jul 2019 12:14:37 -0400https://www.primerpy.com/post/leetcoding/content/1-twosum/Problem Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. Note:350. Intersection of Two Arrays II
https://www.primerpy.com/post/leetcoding/content/350-intertwoarrays/
Sat, 06 Jul 2019 10:50:21 -0400https://www.primerpy.com/post/leetcoding/content/350-intertwoarrays/Problem Given two arrays, write a function to compute their intersection. Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2] Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9] Note:
Each element in the result should appear as many times as it shows in both arrays. The result can be in any order. Thought Process unlike 349, this problem requires each element appear as it shows in original arrays use a dict to store number count, (which I believe is similar to map in C++) for num in nums1, if num exists in nums2 and num does not exist in count, count[num] = 1 if num already exits in count, count[num] += 1 also it’s important to remove the num from nums2 for each iteration to avoid double count return a result that has num (key) * appearance (value) White Board Below is the white board:349. Intersection of Two Arrays
https://www.primerpy.com/post/leetcoding/content/349-intersecttwoarrays/
Fri, 05 Jul 2019 18:58:45 -0400https://www.primerpy.com/post/leetcoding/content/349-intersecttwoarrays/Problem Given two arrays, write a function to compute their intersection. Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2] Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4] Note:
Each element in the result must be unique. The result can be in any order. Thought Process use a dict to store number count for num in nums1, if num exists in nums2 and num does not exist in count, count[num] = 1 for num in nums2, if num exists in nums1 and num does not exist in count, count[num] = 1 return only count keys White Board Below is the white board, and note the 2nd loop is not necessary3. Longest Substring Without Repeating Characters
https://www.primerpy.com/post/leetcoding/content/3-longeststringworepeat/
Fri, 05 Jul 2019 17:59:14 -0400https://www.primerpy.com/post/leetcoding/content/3-longeststringworepeat/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. Example 2:
Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3:
Input: "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.209. Minimize Size Subarray Sum
https://www.primerpy.com/post/leetcoding/content/209-minsizesubarraysum/
Fri, 05 Jul 2019 11:02:30 -0400https://www.primerpy.com/post/leetcoding/content/209-minsizesubarraysum/Problem Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn’t one, return 0 instead.
Example:
Input: s = 7, nums = [2,3,1,2,4,3] Output: 2 Explanation: the subarray [4,3] has the minimal length under the problem constraint. Follow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).167. Two Sum
https://www.primerpy.com/post/leetcoding/content/167-twosum/
Fri, 05 Jul 2019 08:51:11 -0400https://www.primerpy.com/post/leetcoding/content/167-twosum/Problem Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
Your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.75. Sort Colors
https://www.primerpy.com/post/leetcoding/content/75-sortcolors/
Fri, 05 Jul 2019 07:01:23 -0400https://www.primerpy.com/post/leetcoding/content/75-sortcolors/Problem Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are not suppose to use the library’s sort function for this problem.283. Move Zeros
https://www.primerpy.com/post/leetcoding/content/283-movezeroes/
Thu, 04 Jul 2019 22:10:21 -0400https://www.primerpy.com/post/leetcoding/content/283-movezeroes/Problem Given an array nums, write a func to move all 0 s to the end of it while keeping the relative order of the non-zero elements Must do this in-place without making a copy of array Minimize the total number of operations Thought Process Loop through the whole array filter out non-zeros fill the first part of the array with non-zeros fill the rest with 0 White Board Below is the white board:JSON in Python
https://www.primerpy.com/post/python/json/json-in-python/
Fri, 08 Feb 2019 00:00:00 +0000https://www.primerpy.com/post/python/json/json-in-python/What is JSON Definition JSON is Javascript Object Notation. JSON is a light weight data exchange format. JSON string is a string that satisfies JSON format.
{"name": "Isaac Zhou"} {'name': 'Isaac Zhou'} The above is a typical JSON string. JSON has several benefits:
easy to read easy to analyze efficient with the network transaction It can transfer data across different languages Deserialize JSON in Python The original format of JSON is a string, we need to deserialize it in Python.Regex: General
https://www.primerpy.com/post/python/regex/regex-general/
Fri, 08 Feb 2019 00:00:00 +0000https://www.primerpy.com/post/python/regex/regex-general/Table of Contents Regex: General What is regex? Using Built-in Python Function Use Regex module Special char vs. Regular char Using Regex Special string char General char Counts match fixed length match a ranged length Greedy vs. Non-Greedy Search Greedy Non-greedy Matching Times Matching 0 or infinite times Use * Matching 1 or infinite times, Use + Matching 1 or 0 time, use ?Regex: Search and Match
https://www.primerpy.com/post/python/regex/regex-search-match/
Fri, 08 Feb 2019 00:00:00 +0000https://www.primerpy.com/post/python/regex/regex-search-match/Table of Contents search Check the returned value match Check the returned value match only once group There are two more methods in regex: search and match, however I don’t think they are as handy as .sub or .findall. Assume we have a string s=“A8C3721D86”
search
Check the returned value .search returns a re object, search will search for the whole string until the pattern failsRegex: Sub
https://www.primerpy.com/post/python/regex/regex-sub/
Fri, 08 Feb 2019 00:00:00 +0000https://www.primerpy.com/post/python/regex/regex-sub/Table of Contents Introducing re.sub the power of re.sub function as a parameter For regex, there are more than just find. Here I will discuss replacement
Introducing re.sub re.sub matches first then replace the matched string
import re lang = "PythonC#PHPC#C#C#C#" # replace C# with GO r = re.sub("C#", "GO", lang, 0) r 'PythonGOPHPGOGOGOGO' The 4th parameter 0 means to replace C# infinitly. If we change 0 to 1, C# will be replaced only onceInit Method
https://www.primerpy.com/post/python/oop/init-method/
Wed, 06 Feb 2019 00:00:00 +0000https://www.primerpy.com/post/python/oop/init-method/__init__ method define __init__ function class User(): name = "" pwd = "" def __init__(self): print("user") def sign_up(self): print("User Sign Up") __init__ will be invoked automatically when instantiating a class
user = User() # __init__ is seldom called this way user.__init__() user user user.sign_up() User Sign Up Only return None __init__ function can only return a None
class Org(): def __init__(self): return "This is Org" org = Org() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-4-06eab282d464> in <module>() 3 return "This is Org" 4 ----> 5 org = Org() TypeError: __init__() should return None, not 'str' How to take parameters __init__ function can take parameters, for example __init__ will be invoked automatically # This is the wrong way to define the class class Org(): name = "" org_type = "" country = "" def __init__(self, name, org_type, country): # initialize the object attribute name = name org_type = org_type country = country print("{} was successfully created!Class Definition
https://www.primerpy.com/post/python/oop/class-definition/
Tue, 05 Feb 2019 00:00:00 +0000https://www.primerpy.com/post/python/oop/class-definition/Object Oriented Programming (OOP) We need to write meaningful OOP codes, merely having classes doesn’t mean it’s oop. Defining a class Class: defined by class ClassName class Student(): pass Define variables, functions/methods
To use a class, we need to instantiate it first
See examples below
# define a class class Student(): name = "" age = 0 def print_file(): print("name: {} \n age: {}".Class and Object
https://www.primerpy.com/post/python/oop/class-and-object/
Tue, 05 Feb 2019 00:00:00 +0000https://www.primerpy.com/post/python/oop/class-and-object/Class and Object Class: a mapping between computer programs and the entities from real/thinking realm. It’s a blueprint that defines a set of attributes that will characterize any object that is instantiated from this class.
Class encapsulates data (variables) and operations (methods) on those data
A good class design depends on behavior (method) and attribute (variables). Behaviors need to be relevant with the class
For example, for the class definition below, method print_file shouldn’t belong to Student, rather it should belong to PrinterClosure
https://www.primerpy.com/post/python/advanced-python/closure/
Mon, 04 Feb 2019 00:00:00 +0000https://www.primerpy.com/post/python/advanced-python/closure/Everything is an Object In other languages, function is just an executable codes, but in Python everything is an object. So function is a type of object. In python, a function is an object, moreover, a function can be an argument in another function or a function can be a result returned from another function def test(): pass a = test print(type(a)) <class 'function'> 1.1 What is a closure?Decorator
https://www.primerpy.com/post/python/advanced-python/decorator/
Mon, 04 Feb 2019 00:00:00 +0000https://www.primerpy.com/post/python/advanced-python/decorator/Decorator 1.1 Modifying the function decorator is more of a design pattern for exmaple # f1 prints a simple sentence def f1(): print("This is a function") Now, f1 doesn’t fit my need, I want to print out time as well import time def f1_old(): print(time.time()) print("This is a function") # it prints out a Unix timestamp and sentence f1_old() 1549295628.544087 This is a function 1.Decorator Side Effects
https://www.primerpy.com/post/python/advanced-python/decorator-side-effects/
Mon, 04 Feb 2019 00:00:00 +0000https://www.primerpy.com/post/python/advanced-python/decorator-side-effects/Decorator Side Effects 1.1 Decorator might change the function name In this post, we will deep-dive the side effects of decorators. recall our example before, print Unix Time everytime we run the function import time def decorator(func): def wrapper(): print(time.time()) func() return wrapper @decorator def f1(): print("This is a function") f1() 1549311820.0338516 This is a function # Now if f1 is defined without decorator, I want to print out f1's name import time def decorator(func): def wrapper(): print(time.Filter
https://www.primerpy.com/post/python/advanced-python/filter/
Mon, 04 Feb 2019 00:00:00 +0000https://www.primerpy.com/post/python/advanced-python/filter/ Filter Sometimes, we want to conduct some filtering on certain lists. In Python, there’s a really convenient way of doing it: filter
1. Definition Filter out elements not meeting our requirements Takes two parameters: a function or None; an iterable import numpy as np # generate a random list of 50 ints between -100 and 100 # filter out the negative numbers list_x = np.random.randint(-100,100,50) print(list_x) [ 84 80 -16 69 21 -60 11 -77 -84 88 70 13 -77 60 -100 28 -86 39 10 -14 -24 92 93 -67 98 -55 27 -91 -31 -35 -10 -57 66 23 -36 -63 34 3 62 -29 81 -80 61 -46 36 -83 -77 -69 -40 -97] list_x_pos = list(filter(lambda x: True if x > 0 else False, list_x)) print(list_x_pos) [84, 80, 69, 21, 11, 88, 70, 13, 60, 28, 39, 10, 92, 93, 98, 27, 66, 23, 34, 3, 62, 81, 61, 36] # It can be used in a simpler version list_x_neg = list(filter(lambda x: x < 0, list_x)) print(list_x_neg) [-16, -60, -77, -84, -77, -100, -86, -14, -24, -67, -55, -91, -31, -35, -10, -57, -36, -63, -29, -80, -46, -83, -77, -69, -40, -97] Iterator and Generator
https://www.primerpy.com/post/python/pythonic/iterator-generator/
Mon, 04 Feb 2019 00:00:00 +0000https://www.primerpy.com/post/python/pythonic/iterator-generator/Iterator and generator 1.1 Iterator Iterables include list, tuple and set iterator is a class
regular class is not iterable class A: pass # class A is not iterable - we can use iterator to make a class iterable # For Book class, there's no need to be iterable class Book: pass # For a collection of books, e.g. BookCollection, it should be iterable class BookCollection: pass to make a class iterable, we need to methods __iter__ and __next__ class BookCollection: def __init__(self): self.Lambda Expression
https://www.primerpy.com/post/python/advanced-python/lambda-expression/
Mon, 04 Feb 2019 00:00:00 +0000https://www.primerpy.com/post/python/advanced-python/lambda-expression/Lambda Expression 1. Definition Functional programming is a way of thinking. When using lambda, we don’t need to give a function name. It’s very similar to the arrow functions in Javascript (ES6+) lambda would be good for some simple expression in a function, it will not be useful for large chunk of blocks in function # old way of defining a function def add(x,y): return x ** y # lambda parameter_list: expression lambda x, y : x ^ y <function __main__.List Comprehension
https://www.primerpy.com/post/python/pythonic/list-comprehension/
Mon, 04 Feb 2019 00:00:00 +0000https://www.primerpy.com/post/python/pythonic/list-comprehension/List Comprehension Create a new list from another list x is a int list between -100 and 100 get a new list of x square There are at least 3 ways: 1.1 Three methods in Python List comprehension [expression(v) for v in iterables] import matplotlib.pyplot as plt %matplotlib inline x = list(range(-100, 100)) x_square = [v**2 for v in x] plt.Map
https://www.primerpy.com/post/python/advanced-python/map/
Mon, 04 Feb 2019 00:00:00 +0000https://www.primerpy.com/post/python/advanced-python/map/1. Map 1.1 Map Definition map is a class in python, it accepts two parameters, the first one is a function, the second one is an iterable object, e.g. a list, tuple etc. map is usually used converting a list to another list via a function # define a curve list_x = list(range(-100,100)) def curve(x): return x ** 2 list_y = map(curve, list_x) print(list_y) <map object at 0x000002393EB7CEF0> Note that list_y is not a list yet, it’s a map object, we need to apply list on list_y to convert it to a list objectReduce
https://www.primerpy.com/post/python/advanced-python/reduce/
Mon, 04 Feb 2019 00:00:00 +0000https://www.primerpy.com/post/python/advanced-python/reduce/1. Reduce 1.1 Definition Reduce is another important function for functional programming Unlike map, which is a global class, reduce should be imported from functools library reduce takes three parameters: a function (which must takes 2 parameters), a sequence and an initial value reduce conducts a continuous calculation by invoking the function Initially, reduce will take x = 1, y = 2 calculate x + y = 3, then assign 3 to x for the next iteration take the 3rd value 3 and assign to y Loop from functools import reduce result = reduce(lambda x, y: x + y, list(range(1,9))) # 1 + 2 # 1 + 2 + 3 # 1 + 2 + 3 + 4 # .Switch in Python
https://www.primerpy.com/post/python/pythonic/switch-in-python/
Mon, 04 Feb 2019 00:00:00 +0000https://www.primerpy.com/post/python/pythonic/switch-in-python/Switch in Python Python doesn’t have switch, which is common in other languages For example, switch in javascript switch(expression) { case x: // code block break; case y: // code block break; default: // code block } In python, we can use if...elif...elif...else A more pythonic way would be using dictionary day = 0 switcher = { 0: "Sunnday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", } day_name = switcher[day] print(day_name) print(switcher[7]) # this would raise error because we don't have default Sunnday --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-5-ebfdce520e28> in <module> 11 day_name = switcher[day] 12 print(day_name) ---> 13 print(switcher[7]) # this would raise error because we don't have default KeyError: 7 As mentioned above, there’s no default, so the above method might raise error A even more pythonic way, using get(day, default_value) day_name = switcher.Tenary Conditional Expression
https://www.primerpy.com/post/python/advanced-python/tenary-conditional-expression/
Mon, 04 Feb 2019 00:00:00 +0000https://www.primerpy.com/post/python/advanced-python/tenary-conditional-expression/1. Ternary Conditional Operator In simple words, it is just an if-else statement in expression format, it exists in many other languages with a different format, e.g. we want to compare two numbers x, y.
For example in javascript
x > y ? x : y however, in python it’s a bit different. The syntax looks like this:
(return result if condition is true) (if condition else) (return result if condition is false)Functional Programming
https://www.primerpy.com/post/python/advanced-python/functional-programming/
Sun, 03 Feb 2019 00:00:00 +0000https://www.primerpy.com/post/python/advanced-python/functional-programming/Imperative Programming vs. Functional Programming So far, we’ve encountered two types of programming paradigm: Imperative and Functional.
Imperative Programming However hard the logic may be, all the process can be realized with the following three types of objects:
function (def) condition (if else) loop (for) obviously, with OOP, there are objects and modules, but here we just want to focus on the essential imperative programming.
Functional Programming There are four key concepts for functional programming:Class Method
https://www.primerpy.com/post/python/oop/classmethod/
Sat, 02 Feb 2019 00:00:00 +0000https://www.primerpy.com/post/python/oop/classmethod/We can add binary numbers together, just like we can with base 10 numbers
In the example below:
a is in base 10 – because we have 10 possible digits, the highest value we can represent with one digit is 9 When we want to represent a value one higher, we need to add another digit. a now has two digits – we incremented the invisible leading digit, which was 0 and is now 1, and set the last digit back to zero.Enumeration
https://www.primerpy.com/post/python/advanced-python/enumeration/
Sat, 02 Feb 2019 00:00:00 +0000https://www.primerpy.com/post/python/advanced-python/enumeration/Enumeration vs. Class Enumeration is a very common data structure used to define “Type” data, e.g. what types of VIP classes are there for a membership program.
1. Define an Enumeration It’s very easy to define an Enumeration class in Python with enum module, just import as from enum import Enum
from enum import Enum class VIP(Enum): YELLOW = 1 GREEN = 2 BLACK = 3 RED = 4 print(VIP.Advanced Javascript Array Methods
https://www.primerpy.com/post/others/advanced-array-methods/
Thu, 02 Nov 2017 00:00:00 +0000https://www.primerpy.com/post/others/advanced-array-methods/forEach Iterates through an array Runs a callback function on each value in the array always returns “undefined” var arr = [1,2,3,5] arr.forEach(function(d,i,arr){ console.log(d,i); }); How does forEach work var forEach = (arr, callback) => { for(var i = 0; i < arr.length; i++) { callback(arr[i],i,arr); } } Using forEach in a function var halfValues = (arr) => { let newArr = []; arr.JS Closure
https://www.primerpy.com/post/others/js-closure/
Thu, 02 Nov 2017 00:00:00 +0000https://www.primerpy.com/post/others/js-closure/Definition A closure is a function that makes use of variables defined in outer functions that have previously returned We have to “return” the inner function for this to work We can either call the inner function right away by using an extra () or we can store the result of the function in a variable Closure only exists when an inner function makes use of variables defined from an outer function that has returned.Big Image Sample
https://www.primerpy.com/post/others/2017-03-07-bigimg-sample/
Tue, 07 Mar 2017 00:00:00 +0000https://www.primerpy.com/post/others/2017-03-07-bigimg-sample/<p>The image banners at the top of the page are refered to as “bigimg” in this theme. They are optional, and one more more can be specified. If more than one is specified, the images rotate every 10 seconds. In the front matter, bigimgs are specified using an array of hashes.</p>
<p></p>Math Sample
https://www.primerpy.com/post/others/2017-03-05-math-sample/
Sun, 05 Mar 2017 00:00:00 +0000https://www.primerpy.com/post/others/2017-03-05-math-sample/<p>KaTeX can be used to generate complex math formulas server-side.</p>
<p>$$
\phi = \frac{(1+\sqrt{5})}{2} = 1.6180339887\cdots
$$</p>
<p>Additional details can be found on <a href="https://github.com/Khan/KaTeX">GitHub</a> or on the <a href="http://tiddlywiki.com/plugins/tiddlywiki/katex/">Wiki</a>.
</p>Array|数组
https://www.primerpy.com/post/others/array/
Thu, 02 Mar 2017 00:38:33 -0500https://www.primerpy.com/post/others/array/定义 把数据码成一排进行存放 In Java, all data must be of the same type In Python, we can store different data types Index, usually start from 0 (R starts from 1) 数组支持for, forEach因为它具有可迭代，可遍历的能力 (iterable) 二次封装属于我们自己的数组 数组最大的优点：快速查询 索引最好有语义 并非所有有语义的索引都适用于数组 比如ID号，开辟的空间大，可能会浪费 制作属于我们自己的数组类 索引没有语义，如何表示没有元素？ 如何添加元素？如何删除元素？ 增删改查 向指定位置添加元素 确定数组中有足够的空间：size < capacity
确定插入的位置合法：index >= 0 并且 index <= capacity
Dynamic Array Code 用Java实现动态数组
public class DynaArray { private int[] data; private int size; // 构造函数， 传入数组的容量capacity构造DynaArray public DynaArray(int capacity) { data = new int[capacity]; size = 0; } // 无参数的构造函数，默认容量capacity为10 public DynaArray() { this(10); } // 获取数组中的元素个数 public int getSize() { return size; } // 获取数组的容量 public int getCapacity() { return data.Code Sample
https://www.primerpy.com/post/others/2016-03-08-code-sample/
Tue, 08 Mar 2016 00:00:00 +0000https://www.primerpy.com/post/others/2016-03-08-code-sample/<p>The following are two code samples using syntax highlighting.</p>
<p></p>Flake it till you make it
https://www.primerpy.com/post/others/2015-02-26-flake-it-till-you-make-it/
Thu, 26 Feb 2015 00:00:00 +0000https://www.primerpy.com/post/others/2015-02-26-flake-it-till-you-make-it/Under what circumstances should we step off a path? When is it essential that we finish what we start? If I bought a bag of peanuts and had an allergic reaction, no one would fault me if I threw it out. If I ended a relationship with a woman who hit me, no one would say that I had a commitment problem. But if I walk away from a seemingly secure route because my soul has other ideas, I am a flake?Test markdown
https://www.primerpy.com/post/others/2015-02-20-test-markdown/
Fri, 20 Feb 2015 00:00:00 +0000https://www.primerpy.com/post/others/2015-02-20-test-markdown/You can write regular markdown here and Jekyll will automatically convert it to a nice webpage. I strongly encourage you to take 5 minutes to learn how to write in markdown - it’ll teach you how to transform regular text into bold/italics/headings/tables/etc.
Here is some bold text
Here is a secondary heading Here’s a useless table:
Number Next number Previous number Five Six Four Ten Eleven Nine Seven Eight Six Two Three One How about a yummy crepe?To be
https://www.primerpy.com/post/others/2015-02-13-hamlet-monologue/
Fri, 13 Feb 2015 00:00:00 +0000https://www.primerpy.com/post/others/2015-02-13-hamlet-monologue/To be, or not to be–that is the question: Whether ‘tis nobler in the mind to suffer The slings and arrows of outrageous fortune Or to take arms against a sea of troubles And by opposing end them. To die, to sleep– No more–and by a sleep to say we end The heartache, and the thousand natural shocks That flesh is heir to. ‘Tis a consummation Devoutly to be wished. To die, to sleep– To sleep–perchance to dream: ay, there’s the rub, For in that sleep of death what dreams may come When we have shuffled off this mortal coil, Must give us pause.Dear diary
https://www.primerpy.com/post/others/2015-01-27-dear-diary/
Tue, 27 Jan 2015 00:00:00 +0000https://www.primerpy.com/post/others/2015-01-27-dear-diary/What is it with that Mary girl? Dragging me to school every day. As if I had a choice. What you don’t hear in those nursery rhymes is that she starves me if I don’t go to school with her; it’s the only way I can stay alive! I’m thinking about being adopted by Little Bo Peep, sure I may get lost, but anything is better than being with Mary and those little brats at school (shudder, shudder).Soccer
https://www.primerpy.com/post/others/2015-01-19-soccer/
Mon, 19 Jan 2015 00:00:00 +0000https://www.primerpy.com/post/others/2015-01-19-soccer/From Wikipedia:
Association football, more commonly known as football or soccer,[2] is a sport played between two teams of eleven players with a spherical ball. It is played by 250 million players in over 200 countries, making it the world’s most popular sport.[3][4][5][6] The game is played on a rectangular field with a goal at each end. The object of the game is to score by getting the ball into the opposing goal.Pirates arrrr
https://www.primerpy.com/post/others/2015-01-15-pirates/
Thu, 15 Jan 2015 00:00:00 +0000https://www.primerpy.com/post/others/2015-01-15-pirates/Piracy is typically an act of robbery or criminal violence at sea. The term can include acts committed on land, in the air, or in other major bodies of water or on a shore. It does not normally include crimes committed against persons traveling on the same vessel as the perpetrator (e.g. one passenger stealing from others on the same vessel). The term has been used throughout history to refer to raids across land borders by non-state agents.First post!
https://www.primerpy.com/post/others/2015-01-04-first-post/
Mon, 05 Jan 2015 00:00:00 +0000https://www.primerpy.com/post/others/2015-01-04-first-post/This is my first post, how exciting!1. Two Sum
https://www.primerpy.com/post/leetcoding/hashtables/1_twosum/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/hashtables/1_twosum/Problem Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
Note: Each element in the result should appear as many times as it shows in both arrays.102. Binary Tree Level Order Traversal
https://www.primerpy.com/post/leetcoding/binarytree/102_binarytreelevelordertraversal/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/binarytree/102_binarytreelevelordertraversal/Problem Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example: Given binary tree [3,9,20,null,null,15,7],
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
Thought Process This is a typical BFS problem Can solve it with the help of a queue In Python, can use collection.102. Binary Tree Level Order Traversal
https://www.primerpy.com/post/leetcoding/queue/102_binarytreelevelordertraversal/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/queue/102_binarytreelevelordertraversal/Problem Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example: Given binary tree [3,9,20,null,null,15,7],
Example:
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
Thought Process White Board Below is the white board:
Code class ListQueue: # implement Queue based on List def __init__(self): self.array = [] self.104. Maximum Depth of Binary Tree
https://www.primerpy.com/post/leetcoding/binarytree/104_maxdepthbinarytree/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/binarytree/104_maxdepthbinarytree/Problem Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3 / \ 9 20 / \ 15 7
return its depth = 3.
Thought Process Can solve this question recursively. find the max d for the left tree recursively find the max d for the right tree recursively return the larger d White Board Below is the white board:144-Binary Tree Preorder Traversal
https://www.primerpy.com/post/leetcoding/stack/144_binarytreepreordertraversal/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/stack/144_binarytreepreordertraversal/Problem Given a binary tree, return the preorder traversal of its nodes' values.
Example 1:
Input: [1,null,2,3] 1 \ 2 / 3
Output: [1,2,3]
Follow up: Recursive solution is trivial, could you do it iteratively?
Thought Process Solve it recursively node first left tree right tree White Board Below is the white board:
Code class TN: def __init__(self, x): self.val = x self.left = None self.right = None class Sol: def pre(self, root): res = [] if root: res.167. Two Sum
https://www.primerpy.com/post/leetcoding/arrays/167_twosum/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/arrays/167_twosum/Problem Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Note: Your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution and you may not use the same element twice.17. Letter Combinations of a Phone Number
https://www.primerpy.com/post/leetcoding/recursion/17.lettercombinationsofaphonenumber/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/recursion/17.lettercombinationsofaphonenumber/Problem Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example:
Input: "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.19. Remove Nth Node From End of List
https://www.primerpy.com/post/leetcoding/linkedlists/19-remove-nth-node-from-end/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/linkedlists/19-remove-nth-node-from-end/Problem Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Given linked list: 1-2-3-4-5, and n = 2.
After removing the second node from the end, the linked list becomes 1-2-3-5.
Thought Process & White Board Code class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeFromEnd(self, head, n): assert(n) dummyHead = ListNode(None) dummyHead.next = head #initialize p, q = dummyHead, dummyHead for i in range(n+1): assert(q) q = q.20. Valid Parentheses
https://www.primerpy.com/post/leetcoding/stack/20_validparentheses/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/stack/20_validparentheses/Problem Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. Example 1:
Input: "()" Output: true
Example 2:
Input: "()[]{}" Output: true203. Remove Linked List Elements
https://www.primerpy.com/post/leetcoding/linkedlists/203_removelinkedlist/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/linkedlists/203_removelinkedlist/Problem Remove all elements from a linked list of integers that have value val.
Example:
Input: 1-2-6-3-4-5-6, val = 6 Output: 1-2-3-4-5
Thought Process the regular case is simple. e.g. to delete 6 below, we can use a node(delnode) to store 6's next node
2-6-3
then 2's next points to delnode's next node, then 6's next points to None
The tricky part is the edge case: if the deleted node is None, then return None if the deleted node is head, then delnode = head, delnode.206. Reverse Linked List
https://www.primerpy.com/post/leetcoding/linkedlists/206_reversell/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/linkedlists/206_reversell/Problem Reverse a singly linked list.
Example:
Input: 1-2-3-4-5-NULL Output: NULLFollow up:
A linked list can be reversed either iteratively or recursively. Could you implement both? Thought Process if to reverse a link list iteratively, need three pointers to store pre = previous node cur = current node nxt = next node (here nxt is different from node's own next reference) Iterate thru ll, for any given state: cur.209. Minimize Size Subarray Sum
https://www.primerpy.com/post/leetcoding/arrays/209_minsizesubarraysum/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/arrays/209_minsizesubarraysum/Problem Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.
Example:
Input: s = 7, nums = [2,3,1,2,4,3] Output: 2 Explanation: the subarray [4,3] has the minimal length under the problem constraint.
Follow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).219. Contains Duplicate II
https://www.primerpy.com/post/leetcoding/hashtables/219_containsdup/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/hashtables/219_containsdup/Problem Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. Example 1:
Input: nums = [1,2,3,1], k = 3 Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1 Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2 Output: false226. Invert Binary Tree
https://www.primerpy.com/post/leetcoding/binarytree/226_invertbinarytree/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/binarytree/226_invertbinarytree/Problem Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9
Output:
4 / \ 7 2 / \ / \ 9 6 3 1
Thought Process Can solve this question recursively. if the root is None, return None else, revert root's left tree recursively, revert root's right tree recursively swap left, right tree White Board Below is the white board:237. Delete Node in a Linked List
https://www.primerpy.com/post/leetcoding/linkedlists/237-deletenodeinall/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/linkedlists/237-deletenodeinall/Problem Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Given linked list -- head = [4,5,1,9], which looks like following:
4-5-1-9
Example 1:
Input: head = [4,5,1,9], node = 5 Output: [4,1,9] Explanation: You are given the second node with value 5, the linked list should become 4 - 1 - 9 after calling your function.
Example 2:24. Swap Nodes in Pairs
https://www.primerpy.com/post/leetcoding/linkedlists/24-swapnodesinpairs/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/linkedlists/24-swapnodesinpairs/Problem Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given 1-2-3-4, you should return the list as 2-1-4-3.
Thought Process For every node pair: front and back front's next will be pointed to the back's next back's next will be pointed to the front front's previous node's next will be pointed to back Setting up a dummy head node will be helpful White Board Below is the white board:279. Perfect Squares
https://www.primerpy.com/post/leetcoding/graph/279_perfectsquares/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/graph/279_perfectsquares/Problem Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
Example 1:
Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13 Output: 2 Explanation: 13 = 4 + 9.
Thought Process since 1 is a perfect square, so for any n, there must be a solution, the worst case is n I tried the brute force solution but failed, i.283. Move Zeros
https://www.primerpy.com/post/leetcoding/arrays/283_movezeroestemp/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/arrays/283_movezeroestemp/Problem Given an array nums, write a func to move all 0 s to the end of it while keeping the relative order of the non-zero elements Must do this in-place without making a copy of array Minimize the total number of operations Thought Process Loop through the whole array filter out non-zeros fill the first part of the array with non-zeros fill the rest with 0 White Board Below is the white board:3. Longest Substring Without Repeating Characters
https://www.primerpy.com/post/leetcoding/arrays/3_longeststringworepeat/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/arrays/3_longeststringworepeat/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.
Example 2:
Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Note that the answer must be a substring, "349. Intersection of Two Arrays
https://www.primerpy.com/post/leetcoding/hashtables/349_intersecttwoarrays/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/hashtables/349_intersecttwoarrays/Problem Given two arrays, write a function to compute their intersection. Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4]
Note: Each element in the result must be unique. The result can be in any order. Thought Process use a dict to store number count for num in nums1, if num exists in nums2 and num does not exist in count, count[num] = 1 for num in nums2, if num exists in nums1 and num does not exist in count, count[num] = 1 return only count keys White Board Below is the white board:350. Intersection of Two Arrays II
https://www.primerpy.com/post/leetcoding/hashtables/350_intertwoarrays/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/hashtables/350_intertwoarrays/Problem Given two arrays, write a function to compute their intersection. Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9]
Note: Each element in the result should appear as many times as it shows in both arrays. The result can be in any order. Thought Process unlike 349, this problem requires each element appear as it shows in original arrays use a dict to store number count, (which I believe is similar to map in C++) for num in nums1, if num exists in nums2 and num does not exist in count, count[num] = 1 if num already exits in count, count[num] += 1 also it's important to remove the num from nums2 for each iteration to avoid double count return a result that has num (key) * appearance (value) White Board Below is the white board:447. Number of Boomerangs
https://www.primerpy.com/post/leetcoding/hashtables/447_numberofboomerangs/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/hashtables/447_numberofboomerangs/Problem Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters). Find the number of boomerangs. You may assume that n will be at most 500 and coordinates of points are all in the range [-10000, 10000] (inclusive).454. 4Sum II
https://www.primerpy.com/post/leetcoding/hashtables/454_4sum/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/hashtables/454_4sum/Problem Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.
To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -2**28 to 2**28 - 1 and the result is guaranteed to be at most 2**31 - 1.455-AssignCookies
https://www.primerpy.com/post/leetcoding/greedy/455-assigncookies/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/greedy/455-assigncookies/Problem Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj = gi, we can assign the cookie j to the child i, and the child i will be content.70. Climbing Stairs
https://www.primerpy.com/post/leetcoding/dynamicprogramming/70.climbingstairs/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/dynamicprogramming/70.climbingstairs/Problem You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example:
Input: 2 Output: 2 Explanation: There are two ways to climb to the top. step + 1 step steps Example 2:
Input: 3 Output: 3 Explanation: There are three ways to climb to the top.75. Sort Colors
https://www.primerpy.com/post/leetcoding/arrays/75_sortcolors/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/arrays/75_sortcolors/Problem Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are not suppose to use the library's sort function for this problem.About PrimerPy
https://www.primerpy.com/page/about/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/page/about/PrimerPy Primerpy provides a primer on python and related data science topics. It covers all the prerequisites for Deep Learning, Machine Learning, and Artificial Intelligence. It is designated for tech stacks and programming languages used in data science.
So what are those?
Python Python is a clear winner in data science. We cover not only the native Python features, such as loops, functions and objects, but also important libraries such as Numpy, Pandas, Matplotlib, Bokeh, scikit-learn, statsmodels and sqlalchemy etc.Array
https://www.primerpy.com/post/datastructure/array/array/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/datastructure/array/array/What are arrays? A data structure that stores data in a continuous space For python, the most commonly used array-like data structure is list For Python, list can hold different types of data To access any element in an array, we can easily use index with time complexity of O(1) Complexity for Python List init O(1) In cpython, the init create a space of 4 to start with.Hash Tables
https://www.primerpy.com/post/datastructure/hashtables/hashtables/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/datastructure/hashtables/hashtables/Definition What are Hash Tables? Hash Tables are key-value pairs key must be immutable Hash Function Hash functions convert the value to key One big challenge is to calculate the key more evenly to avoid collision One common way is to calculate the mod of a prime number (the number theory is beyond the scope here) but look at two examples below Example 1:
10 % 4 - 2 20 % 4 - 0 30 % 4 - 2 40 % 4 - 0 50 % 4 - 2Iterative Traversal for a Binary Tree
https://www.primerpy.com/post/datastructure/stack/binarytreetraversalnr/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/datastructure/stack/binarytreetraversalnr/Problems There are three ways to traverse a binary tree: preorder, inorder and postorder.
On Leetcode, there are three problems
144. Binary Tree Preorder Traversal Given a binary tree, return the preorder traversal of its nodes' values.
Input: [1,null,2,3] 1 \ 2 / 3
Output: [1,2,3]
94. Binary Tree Inorder Traversal Given a binary tree, return the inorder traversal of its nodes' values.
Input: [1,null,2,3] 1 \ 2 / 3Preorder, Inorder and Postorder Traversal for a Binary Tree
https://www.primerpy.com/post/datastructure/recursion/binarytreetraversal/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/datastructure/recursion/binarytreetraversal/Problems There are three ways to traverse a binary tree: preorder, inorder and postorder.
On Leetcode, there are three problems
144. Binary Tree Preorder Traversal Given a binary tree, return the preorder traversal of its nodes' values.
Input: [1,null,2,3] 1 \ 2 / 3
Output: [1,2,3]
94. Binary Tree Inorder Traversal Given a binary tree, return the inorder traversal of its nodes' values.
Input: [1,null,2,3] 1 \ 2 / 3