day14
---------------------------------------------------------------
实例022:比赛对手
题目 两个乒乓球队进行比赛,各出三人。甲队为a,b,c三人,乙队为x,y,z三人。已抽签决定比赛名单。有人向队员打听比赛的名单。a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单。
分析:来一个最简单暴力的,很不完美,先是生成所有组合的列表list2,再逐步筛选list2,看这近20行的代码头大。。。
1 jia = ["a","b","c"]
2 yi = ["x","y","z"]
3 list = []
4 for k in jia:
5 for j in yi:
6 list.append(k+j)
7 list2 = []
8 for i in list:
9 for j in list:
10 for k in list:
11 if len(set([i,j,k]))==3:
12 list2.append(i+j+k)
13 for i in list2:
14 if len(set(i)) == len(i) and i[0] == jia[0] and i[2] == jia[1]:
15 for j in ["ax","cx","cz"]:
16 if j in i:
17 break
18 else:
19 print(i)
看看答案:
a=set(['x','y','z'])
b=set(['x','y','z'])
c=set(['x','y','z'])
c-=set(('x','z'))
a-=set('x')
for i in a:
for j in b:
for k in c:
if len(set((i,j,k)))==3:
print('a:%s,b:%s,c:%s'%(i,j,k))
看看其他的:
L1 = ["x", 'y', 'z']
for a in L1:
for b in L1:
# 避免重复参赛
if a != b:
for c in L1:
# 避免重复参赛
if a != c and b != c:
# 根据题意判断
if a != 'x' and c != 'x' and c != 'z':
print('a的对手是%s b的对手是%s c的对手是%s' % (a, b, c))
总结:当然我写的最次,后面两种吧没必要的判断去掉了,我是把两个分开算了,一开始方向就偏了