Skip to content

Instantly share code, notes, and snippets.

@aaronshaver
aaronshaver / Java Hashmap Sort By Value.java
Created May 5, 2022 23:24
Java: print HashMap entries sorted by value
// code:
handRankCounts.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue()) // .comparingByValue() returns a comparator so we don't have to build one
.forEach(System.out::println);
// example output:
Four of a kind=1
Straight=1
Three of a kind=3
@aaronshaver
aaronshaver / append_extend.py
Created May 5, 2022 20:55
Python list.append() vs list.extend()
# append adds its argument as a single element to the end of a list.
# The length of the list itself will increase by one.
# extend iterates over its argument adding each element to the list, extending the list
my_list = [1, 2, 3]
my_list.append([4, 5, 6])
# [1, 2, 3, [4, 5, 6]]
my_list = [1, 2, 3]
my_list.extend(4, 5, 6])
# [1, 2, 3, 4, 5, 6]
@aaronshaver
aaronshaver / itertools_product.py
Created April 20, 2022 23:46
Get all combinations of a list of lists using itertools.product
import itertools
sets = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] # lists do not have to be of equal size
combinations = list(itertools.product(*sets))
@aaronshaver
aaronshaver / set difference.py
Created April 20, 2022 18:43
Example of using difference() to get all members in one set that aren't in the other set
# https://leetcode.com/problems/destination-city/submissions/
class Solution:
def destCity(self, paths: List[List[str]]) -> str:
candidates = set()
rejects = set()
for path in paths:
candidates.add(path[1])
rejects.add(path[0])
return list(candidates.difference(rejects))[0] # in candidates but not in rejects
@aaronshaver
aaronshaver / lambda_defaultdict.py
Created April 14, 2022 18:29
Example of super terse lambda to satisfy defaultdict default values
# solves: https://leetcode.com/problems/divide-array-into-equal-pairs/
# when you want to avoid KeyError for missing keys, you need to supply
# a func to the defaultdict constuctor method; here's an example
from collections import defaultdict
class Solution:
def divideArray(self, nums: List[int]) -> bool:
counts = defaultdict(lambda: 0) # argument is a func to return default for missing key
for num in nums:
counts[num] = counts[num] + 1
@aaronshaver
aaronshaver / combinations.py
Created April 11, 2022 21:45
IterTools .combinations() to create all possible subsets, of all sizes, of a larger set
# create all combinations of all subsets, excluding "groups" of single numbers
# e.g. for below would create the original nums, groups of 4, groups of 3, groups of 2
import itertools
nums = [3,5,9,1,3]
groups = []
for group_size in range(2, len(nums) + 1):
for subset in itertools.combinations(nums, group_size):
groups.append(subset)
@aaronshaver
aaronshaver / accumulate.py
Created April 11, 2022 21:42
IterTools accumulate
# this is the classic "return highest altitude" of hill climbing problem
from itertools import accumulate
def largestAltitude(self, A):
return max(0, max(accumulate(A)))
# the reason for the "0, " is because of data sets like [-4,-3,-2,-1,4,3,2]
# where the accumulated addition of those values is -1, yet starting altitude is 0,
# which is higher
@aaronshaver
aaronshaver / find.py
Created April 11, 2022 21:09
find() versus index() in Python
# find() doesn't return an exception, and is perhaps better suited for cases
# where we don't know if the substring exists; it returns -1 if not found
# index() will throw a ValueError exception if the value being searched for doesn't exist
class Solution:
def reversePrefix(self, word: str, ch: str) -> str:
return word[:word.find(ch) + 1][::-1] + word[word.find(ch) + 1:]
# this problem says to reverse the part of the string from 0 to first occurence of character
# then return that reversed output with the rest of the string
@aaronshaver
aaronshaver / set.py
Created April 8, 2022 20:15
Use a set (hashset) when possible
# do:
vowels = set('aeiouAEIOU')
# rather than:
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
# because searching for X in set is O(1) on average for hashset (O(n)) worst
# vs. O(n) on average for array, which is how Python list is implemented
# internally
@aaronshaver
aaronshaver / bit_mask.py
Created April 7, 2022 22:05
Bit mask and bit shifting example
# https://leetcode.com/problems/minimum-bit-flips-to-convert-number/
# this works by making a bit mask using left shift 1 << i, e.g. 1 << 3 == a mask of 1000
# then bitwise AND with the num, gives us a binary num that indicates whether both mask
# and num have a 1 in that digit; e.g. 10 & (1<<2) == 000, and 7 & (1<<2) == 100
# then bit shift right chops off the trailing 0s
# so in this case we'd have 0 for the start decimal num of 10, and 1 for the goal num of 7,
# meaning digit at that place has to change for the start num, and thus our count of
# operations has to increase