commit 5693e1b98bd20d9f7415e647b57419e749ce5c61 (patch) parent e8d93980f59f62d6e372bdb2f66fe32095f91a52 Author: Alex Karle <alex@alexkarle.com> Date: Fri, 3 Dec 2021 01:01:52 -0500 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!) :) Diffstat:
M | 3/b.py | | | 22 | +++++----------------- |
1 file changed, 5 insertions(+), 17 deletions(-)
diff --git 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]