From 5693e1b98bd20d9f7415e647b57419e749ce5c61 Mon Sep 17 00:00:00 2001 From: Alex Karle Date: Fri, 3 Dec 2021 01:01:52 -0500 Subject: [PATCH] day3: Play me some code golf The whole "build up a new array" was a crutch instead of learning filter/lambda, which is a bit cleaner (both in terms of LOC and in terms of space used!) :) --- 3/b.py | 22 +++++----------------- 1 file changed, 5 insertions(+), 17 deletions(-) diff --git a/3/b.py b/3/b.py index 3351074..e8bfdc1 100755 --- a/3/b.py +++ b/3/b.py @@ -11,24 +11,12 @@ def search(nums, maximum): counts[int(n[i])] += 1 # filter the list down to most or least common - def addsome(c): - for n in nums: - if n[i] == c: - new.append(n) - - new = [] - if maximum: - if counts[0] > counts[1]: - addsome('0') - else: - addsome('1') + is_zero = lambda x: x[i] == "0" + is_one = lambda x: x[i] == "1" + if (maximum and counts[0] > counts[1]) or (not maximum and counts[0] <= counts[1]): + nums = list(filter(is_zero, nums)) else: - if counts[0] <= counts[1]: - addsome('0') - else: - addsome('1') - - nums = new + nums = list(filter(is_one, nums)) i+=1 return nums[0] -- libgit2 1.8.1