Program Arcade Games: Ch 16 Worksheet 2D-Array Algorithm The check_celebrity() function below takes an n*n grid as its parameter and prints the celebrity if there is one.
A celebrity is a person who is known by everybody but doesn't know anybody except himself.
If grid [ i ] [ j ] equals 1,  &quot;i&quot; knows &quot;j&quot;.
If grid [ i ] [ j ] equals 0,  &quot;i&quot; doesn't know &quot;j&quot;.
However, I am not satisfied with this one because there are too many loops inside loops and if checks. Are there any ways I can improve it?
def check_celebrity(grid):
    known = 0
    unknown = 0


    for i in range(len(grid)):
       ## Reset these variable for every person i
        known = 0
        unknown = 0
        for j in range(len(grid)):
            if grid[i][j] == 0:
                unknown += 1

            ## if he doesn't know anybody,
            ## check if every other &quot;j&quot; knows him
            if unknown == len(grid)-1:
                for j in range(len(grid)):
                    if grid[j][i] == 1:
                        known += 1

                    if known == len(grid):
                        print(&quot;#{} is the one.&quot;.format(i))
                        break

#These can be used as test cases

##  0 is a celebrity.
grid = [ [1, 0, 0, 0],
         [1, 0, 0, 0],
         [1, 0, 1, 0],
         [1, 0, 1, 0] ]

## 2 is a celebrity
grid = [ [0, 0, 1, 0, 0],
         [0, 1, 1, 0, 1],
         [0, 0, 1, 0, 0],
         [0, 0, 1, 0, 0],
         [1, 0, 1, 1, 1] ]
Welcome to Code Review, few suggestions:

Instead of calling .format() you can use f-Strings: print(f&quot;#{i} is the one.&quot;)
Is better to return the result, instead of printing in the method and break
You can use all() to test the celebrity and make the code more compact.

Applying the suggestions:
def check_celebrity(grid):
    for i in range(len(grid)):
        # Check if i is a candidate celebrity
        if grid[i][i] == 1 and grid[i].count(1) == 1:
            # Ensure that i is a celebrity
            if all(grid[j][i] == 1 for j in range(len(grid))):
                return i

Test:
grid = [ [1, 0, 0, 0],
         [1, 0, 0, 0],
         [1, 0, 1, 0],
         [1, 0, 1, 0] ]

print(f&quot;#{check_celebrity(grid)} is the one.&quot;)
# Outputs: #0 is a celebrity