Skip to content

Instantly share code, notes, and snippets.

@aaronshaver
Created April 14, 2022 18:29
Show Gist options
  • Save aaronshaver/9d9dee3e936c2e29cef8c748058eaf20 to your computer and use it in GitHub Desktop.
Save aaronshaver/9d9dee3e936c2e29cef8c748058eaf20 to your computer and use it in GitHub Desktop.
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
for key in counts.keys():
if counts[key] % 2 != 0:
return False
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment