
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- Related Articles
- Program to check every sublist in a list containing at least one unique element in Python
- Program to check whether every rotation of a number is prime or not in Python
- How to check if a string has at least one letter and one number in Python?
- Program to check whether one value is present in BST or not in Python
- Program to check if binary string has at most one segment of ones or not using Python
- Program to check whether one tree is subtree of other or not in Python
- Program to check whether all leaves are at same level or not in Python
- Program to check whether one point can be converted to another or not in Python
- Python program to check whether a list is empty or not?
- Program to check whether parentheses are balanced or not in Python
- Program to check whether one string swap can make strings equal or not using Python
- Python program to check whether a given string is Heterogram or not
- Program to check whether a binary tree is complete or not in Python
- Program to check whether a binary tree is BST or not in Python
- Program to check whether all can get a seat or not in Python

Advertisements