Finding an Influencer in a Binary Matrix using Python
Given an X by Y array consisting of 1s and 0s, where the X-axis represents “influences” and 1 indicates that the corresponding element in X influences the corresponding element in Y, we want to determine whether an “influencer” exists in the array. An “influencer” is defined as someone who influences all other members in the array, however, is not influenced by any other member. Write a function to solve this problem.
def find_influencer(arr):
n = len(arr)
influencer = 0
# Find a potential influencer candidate
for i in range(n):
if sum(arr[i]) == n-1 and all([arr[j][i]==0 for j in range(n) if j!=i]):
influencer = i
break
# Verify if the candidate is indeed an influencer
if influencer != 0:
for j in range(n):
if j != influencer and (arr[influencer][j] == 1 or arr[j][influencer] == 0):
return -1
return influencer
else:
return -1
The function takes a 2D array arr as input, where arr[i][j] is 1 if i influences j, and 0 otherwise. The function returns the index of an influencer if one exists in the array, and -1 otherwise.
The function works as follows:
- We first find a potential influencer candidate by iterating over the rows of the array. A potential influencer must have a sum of 1s in its row equal to
n-1(wherenis the size of the array) and must have a 0 in all other positions of its column. - Once we find a potential influencer candidate, we verify that it is indeed an influencer by checking that it has a 0 in all other positions of its row, and a 1 in all other positions of its column.
- If the candidate passes this verification, we return its index. Otherwise, we return -1.
Note that the function assumes that there is at most one influencer in the array. If there can be multiple influencers, the function would need to be modified to return a list of indices instead of a single index.
Can you do it better? Add a comment here with your version in any language.
#Python #Coding #Programming #PythonProgramming #Developers #SoftwareDevelopment #Tech #CodeNewbie #100DaysOfCode #PythonDeveloper #Algorithms #DataStructures #Matrix #BinaryMatrix #ProblemSolving #CodingChallenge #DeveloperLife #LearnToCode #ComputerScience #TechBlog #CodingLife #Programmer #SoftwareEngineer #DataScience #ArtificialIntelligence #MachineLearning #PythonTips #CodingProblems #TechEducation #DeveloperCommunity

