Python Forum

Full Version: Is this code pythonic
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
As a beginner, I aim to write pythonic code because that would get me motivated into doing python the pythonic way. I was doing this challenge on 2d lists (or arrays) from hackerrank, and got the answer right. But the way I wrote the code bugs me. I really did not think it was pythonic. Here is the code:
arr = []
count = []
for _ in range(6):
    arr.append(list(map(int, input().strip().split()))) 
for i in range(4) :
    for j in range(4) :
        if arr[i][j] >= -9 and arr[i][j] <= 9 :
            dlist = [arr[i][j], arr[i][j+1], arr[i][j+2],
            arr[i+1][j+1], arr[i+2][j], arr[i+2][j+1], arr[i+2][j+2]]
            count.append(sum(dlist))
count.sort(reverse=True)
print(count[0])
The part that didn't seem right to me was line 8, dlist, initialization. Also, I thought I could do this using list comprehension, but the if conditional there made me not to go for list comprehension.
Could someone tell if it was pythonic and where I could have improved on it?
Thanks
Here is a perhaps more pythonic code, which is very close to your code
# avoid magic numbers in code by defining constants
# allows us to change these values later without changing the code
N = 6
bound = 9

# get input lines
# separating this allows us later to read in a file for example instead of console
lines = [input() for i in range(N)]

# create array
arr = []
for line in lines:
    arr.append([int(x) for x in line.strip().split()])

# optional: validate input
for row in arr:
    assert len(row) == N
    assert all(-bound < x < bound for x in row)

hourglass = [(0,0), (0,1), (0,2), (1,1), (2,0), (2,1), (2,2)]

count = []
for i in range(N - 2):
    for j in range(N - 2):
        count.append(sum(arr[i+u][j+v] for (u, v) in hourglass))
print(max(count))
Your implementation was wonderful. Now I have learned new tricks. I will go an read up on assert expression. I have not encountered assert in my readings.
Thanks