Program to check whether every one has at least a friend or not in Python

PythonServer Side ProgrammingProgramming

Suppose we have n people represented as a number from 0 to n - 1, we also have a list of friend’s tuples, where friends[i][0] and friends[i][1] are friends. We have to check whether everyone has at least one friend or not.

So, if the input is like n = 3 friends = [ [0, 1], [1, 2] ], then the output will be True, as Person 0 is friends of Person 1, Person 1 is friends of Person 0 and 2, and Person 2 is friends of Person 1.

To solve this, we will follow these steps −

  • people := a list of size n, filled with 0
  • for each link in friends, do
    • people[link[0]] := True
    • people[link[1]] := True
  • for each person in people, do
    • if person is empty, then
      • return False
  • return True

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, n, friends):
      people = [0 for i in range(n)]
      for link in friends:
         people[link[0]] = True
         people[link[1]] = True
      for person in people:
         if not person:
            return False
      return True
ob = Solution()
n = 3
friends = [ [0, 1], [1, 2] ]
print(ob.solve(n, friends))

Input

3, [[0, 1],[1, 2]]

Output

True
raja
Published on 19-Oct-2020 15:47:12
Advertisements