Python 练习实例22
题目:两个乒乓球队进行比赛,各出三人。甲队为a,b,c三人,乙队为x,y,z三人。已抽签决定比赛名单。有人向队员打听比赛的名单。a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单。
程序源代码:
实例
#!/usr/bin/python
# -*- coding: UTF-8 -*-
for i in range(ord('x'),ord('z') + 1):
for j in range(ord('x'),ord('z') + 1):
if i != j:
for k in range(ord('x'),ord('z') + 1):
if (i != k) and (j != k):
if (i != ord('x')) and (k != ord('x')) and (k != ord('z')):
print ('order is a -- %s\t b -- %s\tc--%s' % (chr(i),chr(j),chr(k)))
以上实例输出结果为:
order is a -- z b -- x c--y
Python 100例
逝者如斯
596***456@qq.com
参考解法:
#!/usr/bin/python # -*- coding: UTF-8 -*- for a in ['x','y','z']: for b in ['x', 'y', 'z']: for c in ['x', 'y', 'z']: if(a!=b)and(b!=c)and(c!=a) and (a!='x') and (c!='x') and (c!='z'): print 'a和%s比赛,b和%s比赛,c和%s比赛' %(a,b,c)逝者如斯
596***456@qq.com
Kunz
sun***gup@163.com
参考方法:
#!/usr/bin/python # -*- coding: UTF-8 -*- n=['a','b','c'] m=[] for i in range(3): if n[i]!='a' and n[i]!='c': m.insert(i,'x') elif n[i]!='c': m.insert(i,'z') else: m.insert(i,'y') print 'a--%s, b--%s, c--%s' %(m[0], m[1], m[2])Kunz
sun***gup@163.com
途途
maq***dream@163.com
参考方法:
#coding:UTF-8 n=['a','b','c'] m=['x','y','z'] L=[] for i in range(0,3): for j in range(0,3): L.append(n[i]+m[j]) L.remove('ax') L.remove('ay') L.remove('by') L.remove('bz') L.remove('cx') L.remove('cz') print(L)途途
maq***dream@163.com
苏格拉顶
qia***avie@163.com
Python2.x 与 Python3.x 均可执行:
#!/usr/bin/python # -*- coding: UTF-8 -*- import itertools A = ["a", "b", "c"] B = ["x", "y", "z"] team = [] # 存储比赛名单 rankB = [list(each) for each in itertools.permutations(B)] # 将对手的全部组合方式列出来 while True: flag = 0 team = list(zip(A, B)) # 匹配选手 print(team) for each in team: if (("a" in each) and ("x" in each)) or (("c" in each) and (("x" in each) or ("z" in each))): # 判断是否符合对阵要求 flag = 1 # 如不符合则打个标记 break if flag: B = rankB.pop() # 改变一下对手位置 else: break for v1, v2 in team: print("%s 对阵 %s" % (v1, v2))苏格拉顶
qia***avie@163.com