Python 基礎知識簡單

n 個人可以佔據 r 個座位的排列

「n 人可以佔據 r 個座位的排列」問題的詳細指南和 Python 實現。

問題陳述

簡單

寫一個函數 compute_nPr(n, r),它接受兩個非負整數 nr (其中 n >= r)並傳回排列數,即從 n 項排列 r 項的方式數。公式為 nPr = n! / (n - r)!.

例如5個人想坐3個座位,則路數為5P3=5! /2! = 120 / 2 = 60。

約束條件
  • 0 <= r <= n <= 20

範例

Example 1
Input
compute_nPr(5, 3)
Output
60
Explanation

5P3 = 5! / (5-3)! = 120 / 2 = 60.

Example 2
Input
compute_nPr(4, 2)
Output
12
Explanation

4P2 = 4! / 2! = 24 / 2 = 12.

Example 3
Input
compute_nPr(6, 6)
Output
720
Explanation

6P6 = 6! / 0! = 720 / 1 = 720.

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 資源

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