简体   繁体   English

我如何优化此代码到一个循环或最小的可能

[英]How do I optimise this code to one loop or minimal possible

I need to restrict this code to maximum one loop or fewer if possible: 如果可能,我需要将此代码限制为最多一个循环或更少的循环:

for i in range(1,count+1):

  for j in range(i+1,count+1):

     newcount+=1

Basically what it does is find possible combinations without repition . 基本上,它所做的就是找到没有限制的可能组合。

It looks like a triangular number between 1 and count - 1 : 它看起来像是介于1count - 1之间的三角数

count * (count - 1) // 2

Here's a small test: 这是一个小测试:

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

I would recommend itertools.combinations 我会推荐itertools.combinations

In your case, you can iterator over itertools.combinations(xrange(1, count+1), 2) 就您而言,您可以迭代itertools.combinations(xrange(1, count+1), 2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM