问题描述
一个口袋中放有12个球,已知其中3个红的,3个白的,6个黑的,现从中任取8个,问共有多少种可能的颜色搭配?
问题分析
可设任取的8个球中红球为m个,白球为n个,则黑球为8-m-n个。已知12个球中有3个红球,3个白球,6个黑球。因此m的取值范围[0,3], n的取值范围为[0,3], 黑球的个数小于等于6,即8-m-n<=6。
算法设计
利用循环结构检测m,n范围内的所有可能取值,再代入8-m-n<=6验证
Code
# !/user/bin/python3
# -*- coding: utf-8 -*-
# @author: HHVic
# @desc: 三色球
import time
# add timer to calculate the performance
# Basic performance
###############################################################
start = time.time()
if __name__=='__main__':
print('\t 红球 \t 白球 \t 黑球')
print('.............................')
num=0
for m in range(0,4):
for n in range(0,4):
if 8-m-n<=6:
num+=1
print('%2d: %d \t\t %d \t\t %d' %(num,m,n,8-m-n))
end = time.time()
print("The Basic Runtime is {0}".format((end-start)))
结果:
红球 白球 黑球
.............................
1: 0 2 6
2: 0 3 5
3: 1 1 6
4: 1 2 5
5: 1 3 4
6: 2 0 6
7: 2 1 5
8: 2 2 4
9: 2 3 3
10: 3 0 5
11: 3 1 4
12: 3 2 3
13: 3 3 2
The Basic Runtime is 0.0