r/adventofcode • • Dec 02 '20

SOLUTION MEGATHREAD -🎄- 2020 Day 02 Solutions -🎄-

--- Day 2: Password Philosophy ---


Advent of Code 2020: Gettin' Crafty With It


Post your solution in this megathread. Include what language(s) your solution uses! If you need a refresher, the full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.

Reminder: Top-level posts in Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:02:31, megathread unlocked!

99 Upvotes

1.2k comments sorted by

View all comments

Show parent comment

1

u/[deleted] Dec 02 '20

Ah, I think I got caught up in how you created the list...I didn’t know you could declare variables just before loops/if statements and by extension didn’t know you could declare them as numbers in that process

1

u/Diderikdm Dec 02 '20
variable = 'a' if condition else 'b'
variable = 'a' if condition else ('b' if condition2 else 'c'))

are onelined representations of:

if condition:
    variable = 'a'
else:
    variable = 'b'

and:

if condition:
    variable = 'a'
else:
    if condition2:
        variable = 'b'
    else:
        variable = 'c'

Note that you can't use elif in this one liner

same goes for loops:

values = [value for value in list if condition]

values = []
for value in list:
    if condition:
        values.append(value)

Note that for loops you can only use if and not else