[英]How do I optimise this code to one loop or minimal possible
如果可能,我需要將此代碼限制為最多一個循環或更少的循環:
for i in range(1,count+1):
for j in range(i+1,count+1):
newcount+=1
基本上,它所做的就是找到沒有限制的可能組合。
它看起來像是介於1
和count - 1
之間的三角數 :
count * (count - 1) // 2
這是一個小測試:
count = 10
newcount = 0
for i in range(1,count+1):
for j in range(i+1,count+1):
newcount+=1
print(newcount)
# 45
print(newcount == count * (count - 1) // 2)
# True
就您而言,您可以迭代itertools.combinations(xrange(1, count+1), 2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.