Home > OS >  How is it possible to count the number of defined letter from surrounding squares?
How is it possible to count the number of defined letter from surrounding squares?

Time:10-28

The function gets one square as an argument and it has to count how many letter N:s it has around it. I think it requires two for loops within right range but I'm stuck on how to set to bounds for counting the letters. If given square is on a letter, it is counted in aswell.

room = [['N', ' ', ' ', ' ', ' '],
        ['N', 'N', 'N', 'N', ' '],
        ['N', ' ', 'N', ' ', ' '],
        ['N', 'N', 'N', ' ', ' '],
        [' ', ' ', ' ', ' ', ' '],
        [' ', ' ', ' ', ' ', ' ']]  

def count_n(x, y, room):

    for y in range(y, len(room)):
        #print(y)
        for x in range(x, len(room[y])):
            #print(x)
            if x == "N":
                n=n 1
    return n

CodePudding user response:

If "around" means the 8 neighbours and the cell itself, you can do the following:

def count_n(x, y, room):
    x_lo, x_hi = max(x-1, 0), min(x 2, len(room))
    y_lo, y_hi = max(y-1, 0), min(y 2, len(room[x]))
    n = 0
    for row in room[x_lo:x_hi]:
        for val in row[y_lo:y_hi]:
            if val == "N":
                n = n   1
    return n

This can be shortened:

def count_n(x, y, room):
    x_lo, x_hi = max(x-1, 0), min(x 2, len(room))
    y_lo, y_hi = max(y-1, 0), min(y 2, len(room[x]))
    return sum(val == "N" for row in room[x_lo:x_hi] for val in row[y_lo:y_hi])
  • Related