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

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。