- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to check whether every one has at least a friend or not in Python
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
- if person is empty, then
- return True
Let us see the following implementation to get better understanding −
Example
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
Advertisements