Python 基礎知識

最大握手次數

「最大握手次數」問題的詳細指南和 Python 實作。

問題陳述

寫一個函數 max_handshakes(n),它採用一個正整數 n 來表示房間中的人數,並返回如果每個人都與其他人握手一次時可能發生的最大握手次數。

公式為:max_handshakes = n * (n - 1) / 2。這是因為每對人握手一次。

約束條件
  • 1 <= n <= 10^4

範例

Example 1
Input
max_handshakes(5)
Output
10
Explanation

5 people: 5 × 4 / 2 = 10 handshakes. Each of the 5 people shakes hands with 4 others, divided by 2 since each handshake is counted twice.

Example 2
Input
max_handshakes(2)
Output
1
Explanation

2 people can only have 1 handshake between them.

Example 3
Input
max_handshakes(10)
Output
45
Explanation

10 × 9 / 2 = 45 handshakes.

Need a Hint?
考慮使用特定於數字的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。