r/learnpython • • Dec 02 '19

Advent of Code (AoC) 2019 starts today!

https://adventofcode.com/

Advent of Code is an Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

These puzzles are a great way to practice your Python and problem solving skills.

Edit: added description from AoC site.

336 Upvotes

40 comments sorted by

View all comments

2

u/jlamores Dec 02 '19

Talking about the first puzzle.

I am an absolute beginner reading right now through the list chapter of the Python Crash Course. To solve the first puzzle I think I have to make a list with all the data and use a "for loop", but I dont know how to write all this numbers to create my list. How do you do it? You copy and paste in your code? But you don't have the commas so....

5

u/[deleted] Dec 02 '19
empty_list = []
with open('input.txt', 'r') as input_file: 
    for number in input_file.readlines(): 
        empty_list.append(number) 
print(empty_list)

or with list comp

with open('input.txt', 'r') as input_file:
    some_list = [int(number) for number in input_file.readlines()]
    print(some_list)

3

u/MiataCory Dec 02 '19 edited Dec 02 '19

"readline" will read until an "end of line" character.
"readlines" uses readline to return the whole file as a list, which you could access by assigning it to a list: list = file.readlines() and then picking a line like: list(4)

I did the readline though, because I didn't remember readlines!

with open('input.txt', 'r') as file:
    line = file.readline()

That's how I did it anyway. Every time you call file.readline() it'll read the next line. You can do a file.seek(line number) if you want to go to a specific line, though that's usually used for going to beginning of a file, .seek(0)