簡體   English   中英

我如何優化此代碼到一個循環或最小的可能

[英]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

基本上,它所做的就是找到沒有限制的可能組合。

它看起來像是介於1count - 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

就您而言,您可以迭代itertools.combinations(xrange(1, count+1), 2)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM