We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
import math
import os
import random
import re
import sys
#
Complete the 'hourglassSum' function below.
#
The function is expected to return an INTEGER.
The function accepts 2D_INTEGER_ARRAY arr as parameter.
#
from itertools import product
def hourglassSum(arr):
# Generate all possible center coordinates for the hourglass within the 6x6 grid.
C_coordinate = list(product(range(1, 5), repeat=2))
# Relative positions for the top and bottom parts of the hourglass.
r_pos_x, r_pos_y = [-1, 0, 1], [-1, 1]
# Create a list of tuples representing the relative coordinates for the top and bottom parts.
rel_cp = list(product(r_pos_x, r_pos_y))
# Initialize a list to store the sum of each hourglass.
sum_final = []
# Iterate through each center coordinate.
for x, y in C_coordinate:
# Start with the value at the center of the hourglass.
sum_r_pos = arr[y][x]
# Add the values at the relative positions of the top and bottom parts of the hourglass.
for i, j in rel_cp:
sum_r_pos += arr[y+j][x+i]
# Append the calculated sum to the list of sums.
sum_final.append(sum_r_pos)
# Return the maximum hourglass sum.
return max(sum_final)
if name == 'main':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
arr = []
for _ in range(6):
arr.append(list(map(int, input().rstrip().split())))
result = hourglassSum(arr)
fptr.write(str(result) + '\n')
fptr.close()
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
2D Array - DS
You are viewing a single comment's thread. Return to all comments →
!/bin/python3
import math import os import random import re import sys
#
Complete the 'hourglassSum' function below.
#
The function is expected to return an INTEGER.
The function accepts 2D_INTEGER_ARRAY arr as parameter.
#
from itertools import product
def hourglassSum(arr): # Generate all possible center coordinates for the hourglass within the 6x6 grid. C_coordinate = list(product(range(1, 5), repeat=2))
if name == 'main': fptr = open(os.environ['OUTPUT_PATH'], 'w')