Created
April 14, 2022 18:29
-
-
Save aaronshaver/9d9dee3e936c2e29cef8c748058eaf20 to your computer and use it in GitHub Desktop.
Example of super terse lambda to satisfy defaultdict default values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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