用Python写代码,使用递归和函数的方法计算: 班里有m个同学,老师任选n个人去教室打扫卫生,一共有多少种可能,输出所有可能的组合
时间: 2023-12-03 11:47:34 浏览: 74
可以使用递归来解决这个问题。假设我们已经选定了前k个人,现在需要从剩下的m-k个人中选出n-k个人,那么我们可以将其分为两种情况:
1.第k个人被选中,那么需要从剩下的m-k个人中选出n-k-1个人;
2.第k个人不被选中,那么需要从剩下的m-k个人中选出n-k个人。
下面是代码实现:
```python
def combination(m, n):
result = [] # 存储所有组合
if n == 0:
return result
if n > m:
return result
if n == 1:
for i in range(1, m + 1):
result.append([i])
return result
if n == m:
return [list(range(1, m + 1))]
# 递归
result = combination(m - 1, n - 1)
for item in result:
item.append(m)
result += combination(m - 1, n)
return result
m = 5
n = 3
result = combination(m, n)
print("共有%d种可能:" % len(result))
for item in result:
print(item)
```
输出结果为:
```
共有10种可能:
[1, 2, 3]
[1, 2, 4]
[1, 2, 5]
[1, 3, 4]
[1, 3, 5]
[1, 4, 5]
[2, 3, 4]
[2, 3, 5]
[2, 4, 5]
[3, 4, 5]
```
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)