Python solution to Advent of Code, day 3
In an effort to stretch my programming muscles, I'm doing the Advent of Code 2018 (https://adventofcode.com/2018) in a language new to me: Python. Coming from a C# background, I'm probably making all kinds of mistakes or are unaware of some usefull things in Python. This is my solution to day 3, and I would like to get a review on my code. I'm interested in both better ways to solve the problem using Python's tools, but also anything that has to do with style (I tried applying PEP8 rules), readability, etc. Thanks!
The full challenge is here (https://adventofcode.com/2018/day/3) and a bit involved, I'll try to keep it a bit shorter here
The challenge
The Elves managed to locate the chimney-squeeze prototype fabric for Santa's suit. Unfortunately, nobody can even agree on how to cut the fabric. The whole piece of fabric they're working on is a very large square - at least 1000 inches on each side.
Each Elf has made a claim about which area of fabric would be ideal for Santa's suit. All claims have an ID and consist of a single rectangle with edges parallel to the edges of the fabric. Each claim's rectangle is defined as follows:
- The number of inches between the left edge of the fabric and the left edge of the rectangle.
- The number of inches between the top edge of the fabric and the top edge of the rectangle.
- The width of the rectangle in inches.
- The height of the rectangle in inches.
A claim like
#123 @ 3,2: 5x4
means that claim ID 123 specifies a rectangle 3 inches from the left edge, 2 inches from the top edge, 5 inches wide, and 4 inches tall. The problem is that many of the claims overlap, causing two or more claims to cover part of the same areas. For example, consider the following claims:
- #1 @ 1,3: 4x4
- #2 @ 3,1: 4x4
- #3 @ 5,5: 2x2
Visually, these claim the following areas:
........
...2222.
...2222.
.11XX22.
.11XX22.
.111133.
.111133.
........
The four square inches marked with X are claimed by both 1 and 2. (Claim 3, while adjacent to the others, does not overlap either of them.) If the Elves all proceed with their own plans, none of them will have enough fabric. How many square inches of fabric are within two or more claims?
This puzzle also comes with custom puzzle input. I can provide mine, but it's 1350 lines long. The example above provides the way the input is formatted.
Day3.py
class Claim(object):
id = None
x = None
y = None
width = None
height = None
def __init__(self, claim_id, x, y, width, height):
self.id = claim_id
self.x = x
self.y = y
self.width = width
self.height = height
def __repr__(self):
return "<Claim #%s - %s, %s - %sx%s>" % (self.id, self.x, self.y, self.width, self.height)
def read_file_lines(file_path, strip_lines=True):
""" Reads the specified file and returns it's lines an array
file_path: the path to the file
strip_lines (default: true): boolean to indicate whether or not to strip leading and trailing whitespace from each line
Returns: An array of the lines in the file as string
"""
with open(file_path, "r") as f:
if strip_lines:
return [l.strip() for l in f.readlines()]
return [l for l in f.readlines()]
def parse_input(lines):
claims =
for line in lines:
parts = line.split(" ")
id = int(parts[0][1:])
x = int(parts[2].split(",")[0])
y = int(parts[2].split(",")[1][:-1])
width = int(parts[3].split("x")[0])
height = int(parts[3].split("x")[1])
claims.append(Claim(id, x, y, width, height))
return claims
def generate_matrix(size):
return [[0]*size for _ in range(size)]
def print_matrix(matrix):
line = ""
for y in range(0, len(matrix[0])):
line = line + str(y) + ": "
for x in range(0, len(matrix[0])):
line = line + str(matrix[x][y])
print(line)
line = ""
if __name__ == '__main__':
content = read_file_lines("input.txt")
claims = parse_input(content)
matrix = generate_matrix(1000)
print_matrix(matrix)
for claim in claims:
x_indexes = range(claim.x, claim.x + claim.width)
y_indexes = range(claim.y, claim.y + claim.height)
for x in x_indexes:
for y in y_indexes:
matrix[x][y] = matrix[x][y] + 1
print_matrix(matrix)
inches_double_claimed = 0
for x in range(0, len(matrix[0])):
for y in range(0, len(matrix[0])):
if matrix[x][y] >= 2:
inches_double_claimed += 1
print("Inches claimed by two or more claims:", inches_double_claimed)
python python-3.x
New contributor
add a comment |
In an effort to stretch my programming muscles, I'm doing the Advent of Code 2018 (https://adventofcode.com/2018) in a language new to me: Python. Coming from a C# background, I'm probably making all kinds of mistakes or are unaware of some usefull things in Python. This is my solution to day 3, and I would like to get a review on my code. I'm interested in both better ways to solve the problem using Python's tools, but also anything that has to do with style (I tried applying PEP8 rules), readability, etc. Thanks!
The full challenge is here (https://adventofcode.com/2018/day/3) and a bit involved, I'll try to keep it a bit shorter here
The challenge
The Elves managed to locate the chimney-squeeze prototype fabric for Santa's suit. Unfortunately, nobody can even agree on how to cut the fabric. The whole piece of fabric they're working on is a very large square - at least 1000 inches on each side.
Each Elf has made a claim about which area of fabric would be ideal for Santa's suit. All claims have an ID and consist of a single rectangle with edges parallel to the edges of the fabric. Each claim's rectangle is defined as follows:
- The number of inches between the left edge of the fabric and the left edge of the rectangle.
- The number of inches between the top edge of the fabric and the top edge of the rectangle.
- The width of the rectangle in inches.
- The height of the rectangle in inches.
A claim like
#123 @ 3,2: 5x4
means that claim ID 123 specifies a rectangle 3 inches from the left edge, 2 inches from the top edge, 5 inches wide, and 4 inches tall. The problem is that many of the claims overlap, causing two or more claims to cover part of the same areas. For example, consider the following claims:
- #1 @ 1,3: 4x4
- #2 @ 3,1: 4x4
- #3 @ 5,5: 2x2
Visually, these claim the following areas:
........
...2222.
...2222.
.11XX22.
.11XX22.
.111133.
.111133.
........
The four square inches marked with X are claimed by both 1 and 2. (Claim 3, while adjacent to the others, does not overlap either of them.) If the Elves all proceed with their own plans, none of them will have enough fabric. How many square inches of fabric are within two or more claims?
This puzzle also comes with custom puzzle input. I can provide mine, but it's 1350 lines long. The example above provides the way the input is formatted.
Day3.py
class Claim(object):
id = None
x = None
y = None
width = None
height = None
def __init__(self, claim_id, x, y, width, height):
self.id = claim_id
self.x = x
self.y = y
self.width = width
self.height = height
def __repr__(self):
return "<Claim #%s - %s, %s - %sx%s>" % (self.id, self.x, self.y, self.width, self.height)
def read_file_lines(file_path, strip_lines=True):
""" Reads the specified file and returns it's lines an array
file_path: the path to the file
strip_lines (default: true): boolean to indicate whether or not to strip leading and trailing whitespace from each line
Returns: An array of the lines in the file as string
"""
with open(file_path, "r") as f:
if strip_lines:
return [l.strip() for l in f.readlines()]
return [l for l in f.readlines()]
def parse_input(lines):
claims =
for line in lines:
parts = line.split(" ")
id = int(parts[0][1:])
x = int(parts[2].split(",")[0])
y = int(parts[2].split(",")[1][:-1])
width = int(parts[3].split("x")[0])
height = int(parts[3].split("x")[1])
claims.append(Claim(id, x, y, width, height))
return claims
def generate_matrix(size):
return [[0]*size for _ in range(size)]
def print_matrix(matrix):
line = ""
for y in range(0, len(matrix[0])):
line = line + str(y) + ": "
for x in range(0, len(matrix[0])):
line = line + str(matrix[x][y])
print(line)
line = ""
if __name__ == '__main__':
content = read_file_lines("input.txt")
claims = parse_input(content)
matrix = generate_matrix(1000)
print_matrix(matrix)
for claim in claims:
x_indexes = range(claim.x, claim.x + claim.width)
y_indexes = range(claim.y, claim.y + claim.height)
for x in x_indexes:
for y in y_indexes:
matrix[x][y] = matrix[x][y] + 1
print_matrix(matrix)
inches_double_claimed = 0
for x in range(0, len(matrix[0])):
for y in range(0, len(matrix[0])):
if matrix[x][y] >= 2:
inches_double_claimed += 1
print("Inches claimed by two or more claims:", inches_double_claimed)
python python-3.x
New contributor
add a comment |
In an effort to stretch my programming muscles, I'm doing the Advent of Code 2018 (https://adventofcode.com/2018) in a language new to me: Python. Coming from a C# background, I'm probably making all kinds of mistakes or are unaware of some usefull things in Python. This is my solution to day 3, and I would like to get a review on my code. I'm interested in both better ways to solve the problem using Python's tools, but also anything that has to do with style (I tried applying PEP8 rules), readability, etc. Thanks!
The full challenge is here (https://adventofcode.com/2018/day/3) and a bit involved, I'll try to keep it a bit shorter here
The challenge
The Elves managed to locate the chimney-squeeze prototype fabric for Santa's suit. Unfortunately, nobody can even agree on how to cut the fabric. The whole piece of fabric they're working on is a very large square - at least 1000 inches on each side.
Each Elf has made a claim about which area of fabric would be ideal for Santa's suit. All claims have an ID and consist of a single rectangle with edges parallel to the edges of the fabric. Each claim's rectangle is defined as follows:
- The number of inches between the left edge of the fabric and the left edge of the rectangle.
- The number of inches between the top edge of the fabric and the top edge of the rectangle.
- The width of the rectangle in inches.
- The height of the rectangle in inches.
A claim like
#123 @ 3,2: 5x4
means that claim ID 123 specifies a rectangle 3 inches from the left edge, 2 inches from the top edge, 5 inches wide, and 4 inches tall. The problem is that many of the claims overlap, causing two or more claims to cover part of the same areas. For example, consider the following claims:
- #1 @ 1,3: 4x4
- #2 @ 3,1: 4x4
- #3 @ 5,5: 2x2
Visually, these claim the following areas:
........
...2222.
...2222.
.11XX22.
.11XX22.
.111133.
.111133.
........
The four square inches marked with X are claimed by both 1 and 2. (Claim 3, while adjacent to the others, does not overlap either of them.) If the Elves all proceed with their own plans, none of them will have enough fabric. How many square inches of fabric are within two or more claims?
This puzzle also comes with custom puzzle input. I can provide mine, but it's 1350 lines long. The example above provides the way the input is formatted.
Day3.py
class Claim(object):
id = None
x = None
y = None
width = None
height = None
def __init__(self, claim_id, x, y, width, height):
self.id = claim_id
self.x = x
self.y = y
self.width = width
self.height = height
def __repr__(self):
return "<Claim #%s - %s, %s - %sx%s>" % (self.id, self.x, self.y, self.width, self.height)
def read_file_lines(file_path, strip_lines=True):
""" Reads the specified file and returns it's lines an array
file_path: the path to the file
strip_lines (default: true): boolean to indicate whether or not to strip leading and trailing whitespace from each line
Returns: An array of the lines in the file as string
"""
with open(file_path, "r") as f:
if strip_lines:
return [l.strip() for l in f.readlines()]
return [l for l in f.readlines()]
def parse_input(lines):
claims =
for line in lines:
parts = line.split(" ")
id = int(parts[0][1:])
x = int(parts[2].split(",")[0])
y = int(parts[2].split(",")[1][:-1])
width = int(parts[3].split("x")[0])
height = int(parts[3].split("x")[1])
claims.append(Claim(id, x, y, width, height))
return claims
def generate_matrix(size):
return [[0]*size for _ in range(size)]
def print_matrix(matrix):
line = ""
for y in range(0, len(matrix[0])):
line = line + str(y) + ": "
for x in range(0, len(matrix[0])):
line = line + str(matrix[x][y])
print(line)
line = ""
if __name__ == '__main__':
content = read_file_lines("input.txt")
claims = parse_input(content)
matrix = generate_matrix(1000)
print_matrix(matrix)
for claim in claims:
x_indexes = range(claim.x, claim.x + claim.width)
y_indexes = range(claim.y, claim.y + claim.height)
for x in x_indexes:
for y in y_indexes:
matrix[x][y] = matrix[x][y] + 1
print_matrix(matrix)
inches_double_claimed = 0
for x in range(0, len(matrix[0])):
for y in range(0, len(matrix[0])):
if matrix[x][y] >= 2:
inches_double_claimed += 1
print("Inches claimed by two or more claims:", inches_double_claimed)
python python-3.x
New contributor
In an effort to stretch my programming muscles, I'm doing the Advent of Code 2018 (https://adventofcode.com/2018) in a language new to me: Python. Coming from a C# background, I'm probably making all kinds of mistakes or are unaware of some usefull things in Python. This is my solution to day 3, and I would like to get a review on my code. I'm interested in both better ways to solve the problem using Python's tools, but also anything that has to do with style (I tried applying PEP8 rules), readability, etc. Thanks!
The full challenge is here (https://adventofcode.com/2018/day/3) and a bit involved, I'll try to keep it a bit shorter here
The challenge
The Elves managed to locate the chimney-squeeze prototype fabric for Santa's suit. Unfortunately, nobody can even agree on how to cut the fabric. The whole piece of fabric they're working on is a very large square - at least 1000 inches on each side.
Each Elf has made a claim about which area of fabric would be ideal for Santa's suit. All claims have an ID and consist of a single rectangle with edges parallel to the edges of the fabric. Each claim's rectangle is defined as follows:
- The number of inches between the left edge of the fabric and the left edge of the rectangle.
- The number of inches between the top edge of the fabric and the top edge of the rectangle.
- The width of the rectangle in inches.
- The height of the rectangle in inches.
A claim like
#123 @ 3,2: 5x4
means that claim ID 123 specifies a rectangle 3 inches from the left edge, 2 inches from the top edge, 5 inches wide, and 4 inches tall. The problem is that many of the claims overlap, causing two or more claims to cover part of the same areas. For example, consider the following claims:
- #1 @ 1,3: 4x4
- #2 @ 3,1: 4x4
- #3 @ 5,5: 2x2
Visually, these claim the following areas:
........
...2222.
...2222.
.11XX22.
.11XX22.
.111133.
.111133.
........
The four square inches marked with X are claimed by both 1 and 2. (Claim 3, while adjacent to the others, does not overlap either of them.) If the Elves all proceed with their own plans, none of them will have enough fabric. How many square inches of fabric are within two or more claims?
This puzzle also comes with custom puzzle input. I can provide mine, but it's 1350 lines long. The example above provides the way the input is formatted.
Day3.py
class Claim(object):
id = None
x = None
y = None
width = None
height = None
def __init__(self, claim_id, x, y, width, height):
self.id = claim_id
self.x = x
self.y = y
self.width = width
self.height = height
def __repr__(self):
return "<Claim #%s - %s, %s - %sx%s>" % (self.id, self.x, self.y, self.width, self.height)
def read_file_lines(file_path, strip_lines=True):
""" Reads the specified file and returns it's lines an array
file_path: the path to the file
strip_lines (default: true): boolean to indicate whether or not to strip leading and trailing whitespace from each line
Returns: An array of the lines in the file as string
"""
with open(file_path, "r") as f:
if strip_lines:
return [l.strip() for l in f.readlines()]
return [l for l in f.readlines()]
def parse_input(lines):
claims =
for line in lines:
parts = line.split(" ")
id = int(parts[0][1:])
x = int(parts[2].split(",")[0])
y = int(parts[2].split(",")[1][:-1])
width = int(parts[3].split("x")[0])
height = int(parts[3].split("x")[1])
claims.append(Claim(id, x, y, width, height))
return claims
def generate_matrix(size):
return [[0]*size for _ in range(size)]
def print_matrix(matrix):
line = ""
for y in range(0, len(matrix[0])):
line = line + str(y) + ": "
for x in range(0, len(matrix[0])):
line = line + str(matrix[x][y])
print(line)
line = ""
if __name__ == '__main__':
content = read_file_lines("input.txt")
claims = parse_input(content)
matrix = generate_matrix(1000)
print_matrix(matrix)
for claim in claims:
x_indexes = range(claim.x, claim.x + claim.width)
y_indexes = range(claim.y, claim.y + claim.height)
for x in x_indexes:
for y in y_indexes:
matrix[x][y] = matrix[x][y] + 1
print_matrix(matrix)
inches_double_claimed = 0
for x in range(0, len(matrix[0])):
for y in range(0, len(matrix[0])):
if matrix[x][y] >= 2:
inches_double_claimed += 1
print("Inches claimed by two or more claims:", inches_double_claimed)
python python-3.x
python python-3.x
New contributor
New contributor
New contributor
asked 8 hours ago
Céryl Wiltink
1112
1112
New contributor
New contributor
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
This is rather good Python, pleasant to read and using good practices already. I'll just focus on making it more Pythonic.
def __repr__(self):
return "<Claim #%s - %s, %s - %sx%s>" % (self.id, self.x, self.y, self.width, self.height)
This should be __str__
, as it is meant for "fancy" formatting like this. Ideally, __repr__
should be build such as eval(repr(x))
will reconstruct x
.
class Claim(object):
id = None
x = None
y = None
width = None
height = None
def __init__(self, claim_id, x, y, width, height):
self.id = claim_id
self.x = x
self.y = y
self.width = width
self.height = height
def __repr__(self):
return "<Claim #%s - %s, %s - %sx%s>" % (self.id, self.x, self.y, self.width, self.height)
This whole class could be replaced by a namedtuple
. Considering the previous remark, I’d write:
from collections import namedtuple
class Claim(namedtuple('Claim', 'id x y width height')):
def __str__(self):
return "<Claim #{} - {}, {} - {}x{}>".format(self.id, self.x, self.y, self.width, self.height)
Note that I replaced old-school %
formating with the prefered str.format
method. Note that there is also f-strings available if you are using Python 3.6+.
Also note that in your original class you defined class variables that were overriden in the constructor. Don't. There is no gain in doing so as these class variables will never be used anyway.
def read_file_lines(file_path, strip_lines=True):
""" Reads the specified file and returns it's lines an array
file_path: the path to the file
strip_lines (default: true): boolean to indicate whether or not to strip leading and trailing whitespace from each line
Returns: An array of the lines in the file as string
"""
with open(file_path, "r") as f:
if strip_lines:
return [l.strip() for l in f.readlines()]
return [l for l in f.readlines()]
You don't need to read the whole file in memory at once and then create an array of the same content again. Instead, I’d suggest using a generator since you are transforming the output of this function anyway, so rather keep it nice with the memory:
def read_file_lines(file_path, strip_lines=True):
""" Reads the specified file and returns it's lines
file_path: the path to the file
strip_lines (default: true): boolean to indicate whether or not to strip leading and trailing whitespace from each line
Generates the lines in the file as string
"""
with open(file_path, "r") as f:
for line in f:
if strip_lines:
yield line.strip()
else:
yield line
def parse_input(lines):
claims =
for line in lines:
parts = line.split(" ")
id = int(parts[0][1:])
x = int(parts[2].split(",")[0])
y = int(parts[2].split(",")[1][:-1])
width = int(parts[3].split("x")[0])
height = int(parts[3].split("x")[1])
claims.append(Claim(id, x, y, width, height))
return claims
You used list-comprehensions in other places so you know how to use them. You should try to extract the parsing logic out of the loop so you can use them here too. I’d write this function as:
def parse_input(lines):
return [Claim.from_input(line) for line in lines]
and rework the Claim
class into:
class Claim(namedtuple('Claim', 'id x y width height')):
def __str__(self):
return "<Claim #{} - {}, {} - {}x{}>".format(self.id, self.x, self.y, self.width, self.height)
@classmethod
def from_input(cls, line):
parts = line.split(" ")
id = int(parts[0][1:])
x = int(parts[2].split(",")[0])
y = int(parts[2].split(",")[1][:-1])
width = int(parts[3].split("x")[0])
height = int(parts[3].split("x")[1])
return cls(id, x, y, width, height)
In fact, I'd probably merge the two previous functions into a single one, but there is no harm in keeping both:
def parse_input(filename):
with open(filename) as f:
return [Claim.from_input(line.strip()) for line in f]
def generate_matrix(size):
return [[0]*size for _ in range(size)]
Nothing to say here, you didn't fall in the trap of writting [[0] * size] * size
.
def print_matrix(matrix):
line = ""
for y in range(0, len(matrix[0])):
line = line + str(y) + ": "
for x in range(0, len(matrix[0])):
line = line + str(matrix[x][y])
print(line)
line = ""
Time to learn to use str.join
:
def print_matrix(matrix):
string = 'n'.join(
'line {}: {}'.format(i, ''.join(map(str, line)))
for i, line in enumerate(matrix))
print(string)
if __name__ == '__main__':
content = read_file_lines("input.txt")
claims = parse_input(content)
matrix = generate_matrix(1000)
print_matrix(matrix)
for claim in claims:
x_indexes = range(claim.x, claim.x + claim.width)
y_indexes = range(claim.y, claim.y + claim.height)
for x in x_indexes:
for y in y_indexes:
matrix[x][y] = matrix[x][y] + 1
print_matrix(matrix)
inches_double_claimed = 0
for x in range(0, len(matrix[0])):
for y in range(0, len(matrix[0])):
if matrix[x][y] >= 2:
inches_double_claimed += 1
print("Inches claimed by two or more claims:", inches_double_claimed)
As you made in the print_matrix
function, you are iterating over indices to access content of the matrix. Instead, you should iterate over the content directly if you need it:
for line in matrix:
for claims in line:
if claims > 1:
inches_double_claimed += 1
And, in fact, these loops could be written in a single generator expression fed to sum
:
inches_double_claimed = sum(claims > 1 for line in matrix for claims in line)
I would also advice you to wrap this code in a main
function parametrized by the file name to read.
There is still room for improvement: maybe defining a Matrix
class to abstract your functions manipulating it, using re
to simplify input parsing, using a defaultdict(defaultdict(int))
to support arbitrary sizes of fabric (and avoid wasting memory on small problems); but it is still fine as it is.
add a comment |
I wrote about Pythonic constructs in an other answer, so I'll focus in introducing helpful modules in this one. All in all, I'd say that converting the input to Claim
objects is wasting resources and you should focus on your intermediate matrix
representation instead.
As such, I would only use the re
module to parse a line and immediately store it into the matrix.
Such matrix should not be pre-allocated and allowed to be arbitrarily large if need be. For such cases, the collections
module features two helpful classes: defaultdict
and Counter
.
Lastly, the fileinput
module make it easy to use a/several file names on the command line or standard input.
My take on this would be:
import re
import fileinput
from collections import defaultdict, Counter
INPUT_PATTERN = re.compile(r'#d+ @ (d+),(d+): (d+)x(d+)')
def parse_input(stream):
fabric = defaultdict(Counter)
for line in stream:
match = INPUT_PATTERN.match(line)
if match:
x, y, width, height = map(int, match.groups())
for row in range(x, x+width):
fabric[row].update(range(y, y+height))
return fabric
def count_overlaping_claims(fabric):
return sum(claims > 1 for row in fabric.values() for claims in row.values())
if __name__ == '__main__':
fabric = parse_input(fileinput.input())
print(count_overlaping_claims(fabric))
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Céryl Wiltink is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210470%2fpython-solution-to-advent-of-code-day-3%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
This is rather good Python, pleasant to read and using good practices already. I'll just focus on making it more Pythonic.
def __repr__(self):
return "<Claim #%s - %s, %s - %sx%s>" % (self.id, self.x, self.y, self.width, self.height)
This should be __str__
, as it is meant for "fancy" formatting like this. Ideally, __repr__
should be build such as eval(repr(x))
will reconstruct x
.
class Claim(object):
id = None
x = None
y = None
width = None
height = None
def __init__(self, claim_id, x, y, width, height):
self.id = claim_id
self.x = x
self.y = y
self.width = width
self.height = height
def __repr__(self):
return "<Claim #%s - %s, %s - %sx%s>" % (self.id, self.x, self.y, self.width, self.height)
This whole class could be replaced by a namedtuple
. Considering the previous remark, I’d write:
from collections import namedtuple
class Claim(namedtuple('Claim', 'id x y width height')):
def __str__(self):
return "<Claim #{} - {}, {} - {}x{}>".format(self.id, self.x, self.y, self.width, self.height)
Note that I replaced old-school %
formating with the prefered str.format
method. Note that there is also f-strings available if you are using Python 3.6+.
Also note that in your original class you defined class variables that were overriden in the constructor. Don't. There is no gain in doing so as these class variables will never be used anyway.
def read_file_lines(file_path, strip_lines=True):
""" Reads the specified file and returns it's lines an array
file_path: the path to the file
strip_lines (default: true): boolean to indicate whether or not to strip leading and trailing whitespace from each line
Returns: An array of the lines in the file as string
"""
with open(file_path, "r") as f:
if strip_lines:
return [l.strip() for l in f.readlines()]
return [l for l in f.readlines()]
You don't need to read the whole file in memory at once and then create an array of the same content again. Instead, I’d suggest using a generator since you are transforming the output of this function anyway, so rather keep it nice with the memory:
def read_file_lines(file_path, strip_lines=True):
""" Reads the specified file and returns it's lines
file_path: the path to the file
strip_lines (default: true): boolean to indicate whether or not to strip leading and trailing whitespace from each line
Generates the lines in the file as string
"""
with open(file_path, "r") as f:
for line in f:
if strip_lines:
yield line.strip()
else:
yield line
def parse_input(lines):
claims =
for line in lines:
parts = line.split(" ")
id = int(parts[0][1:])
x = int(parts[2].split(",")[0])
y = int(parts[2].split(",")[1][:-1])
width = int(parts[3].split("x")[0])
height = int(parts[3].split("x")[1])
claims.append(Claim(id, x, y, width, height))
return claims
You used list-comprehensions in other places so you know how to use them. You should try to extract the parsing logic out of the loop so you can use them here too. I’d write this function as:
def parse_input(lines):
return [Claim.from_input(line) for line in lines]
and rework the Claim
class into:
class Claim(namedtuple('Claim', 'id x y width height')):
def __str__(self):
return "<Claim #{} - {}, {} - {}x{}>".format(self.id, self.x, self.y, self.width, self.height)
@classmethod
def from_input(cls, line):
parts = line.split(" ")
id = int(parts[0][1:])
x = int(parts[2].split(",")[0])
y = int(parts[2].split(",")[1][:-1])
width = int(parts[3].split("x")[0])
height = int(parts[3].split("x")[1])
return cls(id, x, y, width, height)
In fact, I'd probably merge the two previous functions into a single one, but there is no harm in keeping both:
def parse_input(filename):
with open(filename) as f:
return [Claim.from_input(line.strip()) for line in f]
def generate_matrix(size):
return [[0]*size for _ in range(size)]
Nothing to say here, you didn't fall in the trap of writting [[0] * size] * size
.
def print_matrix(matrix):
line = ""
for y in range(0, len(matrix[0])):
line = line + str(y) + ": "
for x in range(0, len(matrix[0])):
line = line + str(matrix[x][y])
print(line)
line = ""
Time to learn to use str.join
:
def print_matrix(matrix):
string = 'n'.join(
'line {}: {}'.format(i, ''.join(map(str, line)))
for i, line in enumerate(matrix))
print(string)
if __name__ == '__main__':
content = read_file_lines("input.txt")
claims = parse_input(content)
matrix = generate_matrix(1000)
print_matrix(matrix)
for claim in claims:
x_indexes = range(claim.x, claim.x + claim.width)
y_indexes = range(claim.y, claim.y + claim.height)
for x in x_indexes:
for y in y_indexes:
matrix[x][y] = matrix[x][y] + 1
print_matrix(matrix)
inches_double_claimed = 0
for x in range(0, len(matrix[0])):
for y in range(0, len(matrix[0])):
if matrix[x][y] >= 2:
inches_double_claimed += 1
print("Inches claimed by two or more claims:", inches_double_claimed)
As you made in the print_matrix
function, you are iterating over indices to access content of the matrix. Instead, you should iterate over the content directly if you need it:
for line in matrix:
for claims in line:
if claims > 1:
inches_double_claimed += 1
And, in fact, these loops could be written in a single generator expression fed to sum
:
inches_double_claimed = sum(claims > 1 for line in matrix for claims in line)
I would also advice you to wrap this code in a main
function parametrized by the file name to read.
There is still room for improvement: maybe defining a Matrix
class to abstract your functions manipulating it, using re
to simplify input parsing, using a defaultdict(defaultdict(int))
to support arbitrary sizes of fabric (and avoid wasting memory on small problems); but it is still fine as it is.
add a comment |
This is rather good Python, pleasant to read and using good practices already. I'll just focus on making it more Pythonic.
def __repr__(self):
return "<Claim #%s - %s, %s - %sx%s>" % (self.id, self.x, self.y, self.width, self.height)
This should be __str__
, as it is meant for "fancy" formatting like this. Ideally, __repr__
should be build such as eval(repr(x))
will reconstruct x
.
class Claim(object):
id = None
x = None
y = None
width = None
height = None
def __init__(self, claim_id, x, y, width, height):
self.id = claim_id
self.x = x
self.y = y
self.width = width
self.height = height
def __repr__(self):
return "<Claim #%s - %s, %s - %sx%s>" % (self.id, self.x, self.y, self.width, self.height)
This whole class could be replaced by a namedtuple
. Considering the previous remark, I’d write:
from collections import namedtuple
class Claim(namedtuple('Claim', 'id x y width height')):
def __str__(self):
return "<Claim #{} - {}, {} - {}x{}>".format(self.id, self.x, self.y, self.width, self.height)
Note that I replaced old-school %
formating with the prefered str.format
method. Note that there is also f-strings available if you are using Python 3.6+.
Also note that in your original class you defined class variables that were overriden in the constructor. Don't. There is no gain in doing so as these class variables will never be used anyway.
def read_file_lines(file_path, strip_lines=True):
""" Reads the specified file and returns it's lines an array
file_path: the path to the file
strip_lines (default: true): boolean to indicate whether or not to strip leading and trailing whitespace from each line
Returns: An array of the lines in the file as string
"""
with open(file_path, "r") as f:
if strip_lines:
return [l.strip() for l in f.readlines()]
return [l for l in f.readlines()]
You don't need to read the whole file in memory at once and then create an array of the same content again. Instead, I’d suggest using a generator since you are transforming the output of this function anyway, so rather keep it nice with the memory:
def read_file_lines(file_path, strip_lines=True):
""" Reads the specified file and returns it's lines
file_path: the path to the file
strip_lines (default: true): boolean to indicate whether or not to strip leading and trailing whitespace from each line
Generates the lines in the file as string
"""
with open(file_path, "r") as f:
for line in f:
if strip_lines:
yield line.strip()
else:
yield line
def parse_input(lines):
claims =
for line in lines:
parts = line.split(" ")
id = int(parts[0][1:])
x = int(parts[2].split(",")[0])
y = int(parts[2].split(",")[1][:-1])
width = int(parts[3].split("x")[0])
height = int(parts[3].split("x")[1])
claims.append(Claim(id, x, y, width, height))
return claims
You used list-comprehensions in other places so you know how to use them. You should try to extract the parsing logic out of the loop so you can use them here too. I’d write this function as:
def parse_input(lines):
return [Claim.from_input(line) for line in lines]
and rework the Claim
class into:
class Claim(namedtuple('Claim', 'id x y width height')):
def __str__(self):
return "<Claim #{} - {}, {} - {}x{}>".format(self.id, self.x, self.y, self.width, self.height)
@classmethod
def from_input(cls, line):
parts = line.split(" ")
id = int(parts[0][1:])
x = int(parts[2].split(",")[0])
y = int(parts[2].split(",")[1][:-1])
width = int(parts[3].split("x")[0])
height = int(parts[3].split("x")[1])
return cls(id, x, y, width, height)
In fact, I'd probably merge the two previous functions into a single one, but there is no harm in keeping both:
def parse_input(filename):
with open(filename) as f:
return [Claim.from_input(line.strip()) for line in f]
def generate_matrix(size):
return [[0]*size for _ in range(size)]
Nothing to say here, you didn't fall in the trap of writting [[0] * size] * size
.
def print_matrix(matrix):
line = ""
for y in range(0, len(matrix[0])):
line = line + str(y) + ": "
for x in range(0, len(matrix[0])):
line = line + str(matrix[x][y])
print(line)
line = ""
Time to learn to use str.join
:
def print_matrix(matrix):
string = 'n'.join(
'line {}: {}'.format(i, ''.join(map(str, line)))
for i, line in enumerate(matrix))
print(string)
if __name__ == '__main__':
content = read_file_lines("input.txt")
claims = parse_input(content)
matrix = generate_matrix(1000)
print_matrix(matrix)
for claim in claims:
x_indexes = range(claim.x, claim.x + claim.width)
y_indexes = range(claim.y, claim.y + claim.height)
for x in x_indexes:
for y in y_indexes:
matrix[x][y] = matrix[x][y] + 1
print_matrix(matrix)
inches_double_claimed = 0
for x in range(0, len(matrix[0])):
for y in range(0, len(matrix[0])):
if matrix[x][y] >= 2:
inches_double_claimed += 1
print("Inches claimed by two or more claims:", inches_double_claimed)
As you made in the print_matrix
function, you are iterating over indices to access content of the matrix. Instead, you should iterate over the content directly if you need it:
for line in matrix:
for claims in line:
if claims > 1:
inches_double_claimed += 1
And, in fact, these loops could be written in a single generator expression fed to sum
:
inches_double_claimed = sum(claims > 1 for line in matrix for claims in line)
I would also advice you to wrap this code in a main
function parametrized by the file name to read.
There is still room for improvement: maybe defining a Matrix
class to abstract your functions manipulating it, using re
to simplify input parsing, using a defaultdict(defaultdict(int))
to support arbitrary sizes of fabric (and avoid wasting memory on small problems); but it is still fine as it is.
add a comment |
This is rather good Python, pleasant to read and using good practices already. I'll just focus on making it more Pythonic.
def __repr__(self):
return "<Claim #%s - %s, %s - %sx%s>" % (self.id, self.x, self.y, self.width, self.height)
This should be __str__
, as it is meant for "fancy" formatting like this. Ideally, __repr__
should be build such as eval(repr(x))
will reconstruct x
.
class Claim(object):
id = None
x = None
y = None
width = None
height = None
def __init__(self, claim_id, x, y, width, height):
self.id = claim_id
self.x = x
self.y = y
self.width = width
self.height = height
def __repr__(self):
return "<Claim #%s - %s, %s - %sx%s>" % (self.id, self.x, self.y, self.width, self.height)
This whole class could be replaced by a namedtuple
. Considering the previous remark, I’d write:
from collections import namedtuple
class Claim(namedtuple('Claim', 'id x y width height')):
def __str__(self):
return "<Claim #{} - {}, {} - {}x{}>".format(self.id, self.x, self.y, self.width, self.height)
Note that I replaced old-school %
formating with the prefered str.format
method. Note that there is also f-strings available if you are using Python 3.6+.
Also note that in your original class you defined class variables that were overriden in the constructor. Don't. There is no gain in doing so as these class variables will never be used anyway.
def read_file_lines(file_path, strip_lines=True):
""" Reads the specified file and returns it's lines an array
file_path: the path to the file
strip_lines (default: true): boolean to indicate whether or not to strip leading and trailing whitespace from each line
Returns: An array of the lines in the file as string
"""
with open(file_path, "r") as f:
if strip_lines:
return [l.strip() for l in f.readlines()]
return [l for l in f.readlines()]
You don't need to read the whole file in memory at once and then create an array of the same content again. Instead, I’d suggest using a generator since you are transforming the output of this function anyway, so rather keep it nice with the memory:
def read_file_lines(file_path, strip_lines=True):
""" Reads the specified file and returns it's lines
file_path: the path to the file
strip_lines (default: true): boolean to indicate whether or not to strip leading and trailing whitespace from each line
Generates the lines in the file as string
"""
with open(file_path, "r") as f:
for line in f:
if strip_lines:
yield line.strip()
else:
yield line
def parse_input(lines):
claims =
for line in lines:
parts = line.split(" ")
id = int(parts[0][1:])
x = int(parts[2].split(",")[0])
y = int(parts[2].split(",")[1][:-1])
width = int(parts[3].split("x")[0])
height = int(parts[3].split("x")[1])
claims.append(Claim(id, x, y, width, height))
return claims
You used list-comprehensions in other places so you know how to use them. You should try to extract the parsing logic out of the loop so you can use them here too. I’d write this function as:
def parse_input(lines):
return [Claim.from_input(line) for line in lines]
and rework the Claim
class into:
class Claim(namedtuple('Claim', 'id x y width height')):
def __str__(self):
return "<Claim #{} - {}, {} - {}x{}>".format(self.id, self.x, self.y, self.width, self.height)
@classmethod
def from_input(cls, line):
parts = line.split(" ")
id = int(parts[0][1:])
x = int(parts[2].split(",")[0])
y = int(parts[2].split(",")[1][:-1])
width = int(parts[3].split("x")[0])
height = int(parts[3].split("x")[1])
return cls(id, x, y, width, height)
In fact, I'd probably merge the two previous functions into a single one, but there is no harm in keeping both:
def parse_input(filename):
with open(filename) as f:
return [Claim.from_input(line.strip()) for line in f]
def generate_matrix(size):
return [[0]*size for _ in range(size)]
Nothing to say here, you didn't fall in the trap of writting [[0] * size] * size
.
def print_matrix(matrix):
line = ""
for y in range(0, len(matrix[0])):
line = line + str(y) + ": "
for x in range(0, len(matrix[0])):
line = line + str(matrix[x][y])
print(line)
line = ""
Time to learn to use str.join
:
def print_matrix(matrix):
string = 'n'.join(
'line {}: {}'.format(i, ''.join(map(str, line)))
for i, line in enumerate(matrix))
print(string)
if __name__ == '__main__':
content = read_file_lines("input.txt")
claims = parse_input(content)
matrix = generate_matrix(1000)
print_matrix(matrix)
for claim in claims:
x_indexes = range(claim.x, claim.x + claim.width)
y_indexes = range(claim.y, claim.y + claim.height)
for x in x_indexes:
for y in y_indexes:
matrix[x][y] = matrix[x][y] + 1
print_matrix(matrix)
inches_double_claimed = 0
for x in range(0, len(matrix[0])):
for y in range(0, len(matrix[0])):
if matrix[x][y] >= 2:
inches_double_claimed += 1
print("Inches claimed by two or more claims:", inches_double_claimed)
As you made in the print_matrix
function, you are iterating over indices to access content of the matrix. Instead, you should iterate over the content directly if you need it:
for line in matrix:
for claims in line:
if claims > 1:
inches_double_claimed += 1
And, in fact, these loops could be written in a single generator expression fed to sum
:
inches_double_claimed = sum(claims > 1 for line in matrix for claims in line)
I would also advice you to wrap this code in a main
function parametrized by the file name to read.
There is still room for improvement: maybe defining a Matrix
class to abstract your functions manipulating it, using re
to simplify input parsing, using a defaultdict(defaultdict(int))
to support arbitrary sizes of fabric (and avoid wasting memory on small problems); but it is still fine as it is.
This is rather good Python, pleasant to read and using good practices already. I'll just focus on making it more Pythonic.
def __repr__(self):
return "<Claim #%s - %s, %s - %sx%s>" % (self.id, self.x, self.y, self.width, self.height)
This should be __str__
, as it is meant for "fancy" formatting like this. Ideally, __repr__
should be build such as eval(repr(x))
will reconstruct x
.
class Claim(object):
id = None
x = None
y = None
width = None
height = None
def __init__(self, claim_id, x, y, width, height):
self.id = claim_id
self.x = x
self.y = y
self.width = width
self.height = height
def __repr__(self):
return "<Claim #%s - %s, %s - %sx%s>" % (self.id, self.x, self.y, self.width, self.height)
This whole class could be replaced by a namedtuple
. Considering the previous remark, I’d write:
from collections import namedtuple
class Claim(namedtuple('Claim', 'id x y width height')):
def __str__(self):
return "<Claim #{} - {}, {} - {}x{}>".format(self.id, self.x, self.y, self.width, self.height)
Note that I replaced old-school %
formating with the prefered str.format
method. Note that there is also f-strings available if you are using Python 3.6+.
Also note that in your original class you defined class variables that were overriden in the constructor. Don't. There is no gain in doing so as these class variables will never be used anyway.
def read_file_lines(file_path, strip_lines=True):
""" Reads the specified file and returns it's lines an array
file_path: the path to the file
strip_lines (default: true): boolean to indicate whether or not to strip leading and trailing whitespace from each line
Returns: An array of the lines in the file as string
"""
with open(file_path, "r") as f:
if strip_lines:
return [l.strip() for l in f.readlines()]
return [l for l in f.readlines()]
You don't need to read the whole file in memory at once and then create an array of the same content again. Instead, I’d suggest using a generator since you are transforming the output of this function anyway, so rather keep it nice with the memory:
def read_file_lines(file_path, strip_lines=True):
""" Reads the specified file and returns it's lines
file_path: the path to the file
strip_lines (default: true): boolean to indicate whether or not to strip leading and trailing whitespace from each line
Generates the lines in the file as string
"""
with open(file_path, "r") as f:
for line in f:
if strip_lines:
yield line.strip()
else:
yield line
def parse_input(lines):
claims =
for line in lines:
parts = line.split(" ")
id = int(parts[0][1:])
x = int(parts[2].split(",")[0])
y = int(parts[2].split(",")[1][:-1])
width = int(parts[3].split("x")[0])
height = int(parts[3].split("x")[1])
claims.append(Claim(id, x, y, width, height))
return claims
You used list-comprehensions in other places so you know how to use them. You should try to extract the parsing logic out of the loop so you can use them here too. I’d write this function as:
def parse_input(lines):
return [Claim.from_input(line) for line in lines]
and rework the Claim
class into:
class Claim(namedtuple('Claim', 'id x y width height')):
def __str__(self):
return "<Claim #{} - {}, {} - {}x{}>".format(self.id, self.x, self.y, self.width, self.height)
@classmethod
def from_input(cls, line):
parts = line.split(" ")
id = int(parts[0][1:])
x = int(parts[2].split(",")[0])
y = int(parts[2].split(",")[1][:-1])
width = int(parts[3].split("x")[0])
height = int(parts[3].split("x")[1])
return cls(id, x, y, width, height)
In fact, I'd probably merge the two previous functions into a single one, but there is no harm in keeping both:
def parse_input(filename):
with open(filename) as f:
return [Claim.from_input(line.strip()) for line in f]
def generate_matrix(size):
return [[0]*size for _ in range(size)]
Nothing to say here, you didn't fall in the trap of writting [[0] * size] * size
.
def print_matrix(matrix):
line = ""
for y in range(0, len(matrix[0])):
line = line + str(y) + ": "
for x in range(0, len(matrix[0])):
line = line + str(matrix[x][y])
print(line)
line = ""
Time to learn to use str.join
:
def print_matrix(matrix):
string = 'n'.join(
'line {}: {}'.format(i, ''.join(map(str, line)))
for i, line in enumerate(matrix))
print(string)
if __name__ == '__main__':
content = read_file_lines("input.txt")
claims = parse_input(content)
matrix = generate_matrix(1000)
print_matrix(matrix)
for claim in claims:
x_indexes = range(claim.x, claim.x + claim.width)
y_indexes = range(claim.y, claim.y + claim.height)
for x in x_indexes:
for y in y_indexes:
matrix[x][y] = matrix[x][y] + 1
print_matrix(matrix)
inches_double_claimed = 0
for x in range(0, len(matrix[0])):
for y in range(0, len(matrix[0])):
if matrix[x][y] >= 2:
inches_double_claimed += 1
print("Inches claimed by two or more claims:", inches_double_claimed)
As you made in the print_matrix
function, you are iterating over indices to access content of the matrix. Instead, you should iterate over the content directly if you need it:
for line in matrix:
for claims in line:
if claims > 1:
inches_double_claimed += 1
And, in fact, these loops could be written in a single generator expression fed to sum
:
inches_double_claimed = sum(claims > 1 for line in matrix for claims in line)
I would also advice you to wrap this code in a main
function parametrized by the file name to read.
There is still room for improvement: maybe defining a Matrix
class to abstract your functions manipulating it, using re
to simplify input parsing, using a defaultdict(defaultdict(int))
to support arbitrary sizes of fabric (and avoid wasting memory on small problems); but it is still fine as it is.
edited 5 hours ago
answered 7 hours ago
Mathias Ettinger
23.5k33182
23.5k33182
add a comment |
add a comment |
I wrote about Pythonic constructs in an other answer, so I'll focus in introducing helpful modules in this one. All in all, I'd say that converting the input to Claim
objects is wasting resources and you should focus on your intermediate matrix
representation instead.
As such, I would only use the re
module to parse a line and immediately store it into the matrix.
Such matrix should not be pre-allocated and allowed to be arbitrarily large if need be. For such cases, the collections
module features two helpful classes: defaultdict
and Counter
.
Lastly, the fileinput
module make it easy to use a/several file names on the command line or standard input.
My take on this would be:
import re
import fileinput
from collections import defaultdict, Counter
INPUT_PATTERN = re.compile(r'#d+ @ (d+),(d+): (d+)x(d+)')
def parse_input(stream):
fabric = defaultdict(Counter)
for line in stream:
match = INPUT_PATTERN.match(line)
if match:
x, y, width, height = map(int, match.groups())
for row in range(x, x+width):
fabric[row].update(range(y, y+height))
return fabric
def count_overlaping_claims(fabric):
return sum(claims > 1 for row in fabric.values() for claims in row.values())
if __name__ == '__main__':
fabric = parse_input(fileinput.input())
print(count_overlaping_claims(fabric))
add a comment |
I wrote about Pythonic constructs in an other answer, so I'll focus in introducing helpful modules in this one. All in all, I'd say that converting the input to Claim
objects is wasting resources and you should focus on your intermediate matrix
representation instead.
As such, I would only use the re
module to parse a line and immediately store it into the matrix.
Such matrix should not be pre-allocated and allowed to be arbitrarily large if need be. For such cases, the collections
module features two helpful classes: defaultdict
and Counter
.
Lastly, the fileinput
module make it easy to use a/several file names on the command line or standard input.
My take on this would be:
import re
import fileinput
from collections import defaultdict, Counter
INPUT_PATTERN = re.compile(r'#d+ @ (d+),(d+): (d+)x(d+)')
def parse_input(stream):
fabric = defaultdict(Counter)
for line in stream:
match = INPUT_PATTERN.match(line)
if match:
x, y, width, height = map(int, match.groups())
for row in range(x, x+width):
fabric[row].update(range(y, y+height))
return fabric
def count_overlaping_claims(fabric):
return sum(claims > 1 for row in fabric.values() for claims in row.values())
if __name__ == '__main__':
fabric = parse_input(fileinput.input())
print(count_overlaping_claims(fabric))
add a comment |
I wrote about Pythonic constructs in an other answer, so I'll focus in introducing helpful modules in this one. All in all, I'd say that converting the input to Claim
objects is wasting resources and you should focus on your intermediate matrix
representation instead.
As such, I would only use the re
module to parse a line and immediately store it into the matrix.
Such matrix should not be pre-allocated and allowed to be arbitrarily large if need be. For such cases, the collections
module features two helpful classes: defaultdict
and Counter
.
Lastly, the fileinput
module make it easy to use a/several file names on the command line or standard input.
My take on this would be:
import re
import fileinput
from collections import defaultdict, Counter
INPUT_PATTERN = re.compile(r'#d+ @ (d+),(d+): (d+)x(d+)')
def parse_input(stream):
fabric = defaultdict(Counter)
for line in stream:
match = INPUT_PATTERN.match(line)
if match:
x, y, width, height = map(int, match.groups())
for row in range(x, x+width):
fabric[row].update(range(y, y+height))
return fabric
def count_overlaping_claims(fabric):
return sum(claims > 1 for row in fabric.values() for claims in row.values())
if __name__ == '__main__':
fabric = parse_input(fileinput.input())
print(count_overlaping_claims(fabric))
I wrote about Pythonic constructs in an other answer, so I'll focus in introducing helpful modules in this one. All in all, I'd say that converting the input to Claim
objects is wasting resources and you should focus on your intermediate matrix
representation instead.
As such, I would only use the re
module to parse a line and immediately store it into the matrix.
Such matrix should not be pre-allocated and allowed to be arbitrarily large if need be. For such cases, the collections
module features two helpful classes: defaultdict
and Counter
.
Lastly, the fileinput
module make it easy to use a/several file names on the command line or standard input.
My take on this would be:
import re
import fileinput
from collections import defaultdict, Counter
INPUT_PATTERN = re.compile(r'#d+ @ (d+),(d+): (d+)x(d+)')
def parse_input(stream):
fabric = defaultdict(Counter)
for line in stream:
match = INPUT_PATTERN.match(line)
if match:
x, y, width, height = map(int, match.groups())
for row in range(x, x+width):
fabric[row].update(range(y, y+height))
return fabric
def count_overlaping_claims(fabric):
return sum(claims > 1 for row in fabric.values() for claims in row.values())
if __name__ == '__main__':
fabric = parse_input(fileinput.input())
print(count_overlaping_claims(fabric))
edited 4 hours ago
answered 5 hours ago
Mathias Ettinger
23.5k33182
23.5k33182
add a comment |
add a comment |
Céryl Wiltink is a new contributor. Be nice, and check out our Code of Conduct.
Céryl Wiltink is a new contributor. Be nice, and check out our Code of Conduct.
Céryl Wiltink is a new contributor. Be nice, and check out our Code of Conduct.
Céryl Wiltink is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210470%2fpython-solution-to-advent-of-code-day-3%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown