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))
總結:當然我寫的最次,后面兩種吧沒必要的判斷去掉了,我是把兩個分開算了,一開始方向就偏了