如何减少循环次数或复杂度

问题描述:

所以我想要做的是找到交替数字的数量,使它交替与-ve和正号 例如:1 -2 3 -4会让我4 3 2 1从1到-4包括两个数字,有4个数字。 Simillarly for 1 1 -3 2会让我1 3 2 1 现在我有代码,但我无法优化它,并且它会返回超出时间限制的错误,即使它适用于中等输入流。使用for循环而不是while循环为避免你的一些变量赋值如何减少循环次数或复杂度

j=0 
count=0 
length=(raw_input()) 
st=map(int,raw_input().split()) 
while j+1 < len(st): 
    k=j+1 
    count=0 
    temp=j 
    while k<len(st) and ((st[k]<0 and st[j]>0) or (st[k]>0 and st[j]<0)): 
     count+=1 
     k+=1 
     j+=1 
    print count+1, 
    j=temp+1 
print 1 
+1

你的问题是题外话。但你可以试试[代码评论](https://codereview.stackexchange.com/) –

+0

如果你想获得不同数字的计数,那么只需将所有内容添加到一组并获得设置长度 –

+4

这属于https ://codereview.stackexchange.com – Torxed

尝试:

st = map(int, raw_input().split()) 
length = len(st)-1 
for i in range(length): 
    count = 1 
    for j in range(i, length): 
     if (st[j]<0 and st[j+1]>0) or (st[j+1]<0 and st[j]>0): 
      count += 1 
     else: 
      break 
    print(count) 
print(1) 

这将给:

<< 1 -2 3 4 
>> 4 
>> 3 
>> 2 
>> 1 

<< 1 1 -3 2 
>> 1 
>> 3 
>> 2 
>> 1 

它也可能是一个快一点,如果你从列表中提取一次而不是两次:

st = map(int, raw_input().split()) 
length = len(st)-1 
for i in range(length): 
    count = 1 
    for j in range(i, length): 
     first, second = st[j:j+2] 
     if (first<0 and second>0) or (first>0 and second<0): 
      count += 1 
     else: 
      break 
    print(count) 
print(1) 

的最后一件事我会尝试正在检查他们SIGS可用单comparisson不同,但我真的不希望这是更快:

st = map(int, raw_input().split()) 
length = len(st)-1 
for i in range(length): 
    count = 1 
    for j in range(i, length): 
     product = st[j] * st[j+1] 
     if product != abs(product): 
      count += 1 
     else: 
      break 
    print(count) 
print(1) 
+0

我把'len(st) - 1'从循环中拿出来,这样只需要计算一次。 – Adirio

+0

谢谢@Adirio。复杂性不会降低。你有没有其他办法。 –

+0

我添加了一些选项,但我不确定他们是否会减少它。最后一种方法取决于实数,因为高值需要更长的时间才能乘以。 – Adirio