Re:Peter Norvig's “pytudes” for Advent of Code 2020
by philshem on Friday January 08, 2021 @03:50AM
(#25682863)
when I saw the first() function, I thought it was some default python that was new to me.
But he defines it above in his commonly used functions:
def first(iterable, default=None) -> object:
"Return first item in iterable, or default."
return next(iter(iterable), default)
Re:Peter Norvig's “pytudes” for Advent of Code 2020
by madhadron on Friday January 08, 2021 @01:19PM
(#25687805)
How to tell he's a Lisper. :) Be glad it wasn't car().
Re:Peter Norvig's “pytudes” for Advent of Code 2020
by norvig on Friday January 08, 2021 @02:05PM
(#25688661)
madhadron, I'm a Common Lisper, so I'm good with `first` and `rest`.
Re:Peter Norvig's “pytudes” for Advent of Code 2020
by tuvistavie on Friday January 08, 2021 @08:57AM
(#25684737)
I am not sure I would advocate for this but, from Python 3.8, this is an instance where assignment expressions could allow the first code without duplication.
first(x * y
for x in nums
if (y := 2020 - x) in nums and x != y)
Re:Peter Norvig's “pytudes” for Advent of Code 2020
by norvig on Friday January 08, 2021 @02:07PM
(#25688687)
I agree, tuvistavie! But my default machine has 3.7 installed, and I didn't want to get too far ahead of readers. Sometime next year I'll go to 3.8, and look forward to using ":="
Re:Peter Norvig's “pytudes” for Advent of Code 2020
by Gupie on Friday January 08, 2021 @05:31AM
(#25683332)
The "x == y" test looks like a bug to me, unless duplicate entries are not allowed. For example [1010,1010,1721,979,366,299,675,1456] should return 1010 * 1010, not 1721 * 299.
Re:Peter Norvig's “pytudes” for Advent of Code 2020
by jstanley on Friday January 08, 2021 @08:24AM
(#25684439)
Given that the comment says "Find 2 distinct numbers that sum to 2020", I expect duplicate entries are not allowed.
Re:Peter Norvig's “pytudes” for Advent of Code 2020
by Gupie on Friday January 08, 2021 @08:38AM
(#25684579)
Yes, but I cannot find the same in the problem definition:
"they need you to find the two entries that sum to 2020 and then multiply those two numbers together"
Re:Peter Norvig's “pytudes” for Advent of Code 2020
by dubya on Friday January 08, 2021 @10:28PM
(#25696304)
There are frequently non-stated properties of the input in Advent of Code that simplify the problem a bit.
Re:Peter Norvig's “pytudes” for Advent of Code 2020
by notretarded on Friday January 08, 2021 @04:57AM
(#25683172)
abstruse
Completely agree, your solution is more clear.
Notice that the input, `nums`, is a set. So he's taking the intersection of two sets. One set always has one item, so the result will be a collection with either 0 or 1 items.
It could have also been written as:
But that has a lot of duplication, so it'd probably be best to just use an imperative approach here and do something like: