用 Python 编写程序检查每个人是否至少有一个朋友
pythonserver side programmingprogramming更新于 2026/2/1 22:04:17
假设我们有 n 个人,用 0 到 n - 1 的数字表示,我们还有一个朋友元组列表,其中 friends[i][0] 和 friends[i][1] 是朋友。我们必须检查每个人是否至少有一个朋友。
因此,如果输入为 n = 3 friends = [ [0, 1], [1, 2] ],则输出将为 True,因为 Person 0 是 Person 1 的朋友,Person 1 是 Person 0 和 2 的朋友,而 Person 2 是 Person 1 的朋友。
为了解决这个问题,我们将遵循以下步骤 −
- people := 大小为 n 的列表,填充 0
- 对于 friends 中的每个链接,执行
- people[link[0]] := True
- people[link[1]] := True
- 对于 people 中的每个人,执行
- 如果 person 为空,则
- 返回 False
- 如果 person 为空,则
- 返回 True
让我们看看下面的实现以便更好地理解 −
示例
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))
输入
3, [[0, 1],[1, 2]]
输出
True
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

