如果打印,创建一个集合并存储(a,b),的组合。如果已经在集合中,(b,a)请不要打印:(a,b)
A = 1,2,3,4,5,6,8
B = 1,2,3,4,5,6,8
got = set() # collect (a,b) and (b,a) that you printed already to avoid dupes
for a in A:
for b in B:
if (a * b) == 24:
if (a,b) in got:
continue
got.add((a,b)) # need to add (a,b) and (b,a) to avoid printing
got.add((b,a)) # (b,a) after you already printed (a,b)
print (a, b, a+b)
输出:
3 8 11
4 6 10
让我们比较一下这个和olivn的方法 - 我删除了两个打印语句:
A = 1,2,3,4,5,6,8
B = 1,2,3,4,5,6,8
def ol():
res = set()
for a in A:
for b in B:
if a * b == 24:
if {a, b} not in res:
# print(a, b, a + b)
res.add(frozenset((a, b)))
def pa():
got = set() # collect (a,b) and (b,a) that you printed already to avoid dupes
for a in A:
for b in B:
if (a * b) == 24:
if (a,b) in got:
continue
got.add((a,b)) # need to add (a,b) and (b,a) to avoid printing
got.add((b,a)) # (b,a) after you already printed (a,b)
# print (a, b, a+b)
from timeit import timeit
print("Olivn:", timeit(ol, number=10000))
print("this: ", timeit(pa, number=10000))
输出:
Olivn: 0.60943335
this: 0.6066992629999999