简体   繁体   中英

How do I reduce the number of loops or complexity

So what I am trying to do is to find count of alternating numbers such that it alternates with -ve and positive sign for eg: 1 -2 3 -4 would get me 4 3 2 1 as from 1 to -4 including the two numbers there are 4 numbers. Simillarly for 1 1 -3 2 would get me 1 3 2 1 Now I have the code but I cannot optimise it and it returns me a time limit exceeded error even though it works for moderate input stream.

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

Try using for loops instead of while loops as that avoids you some variable assignments:

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)

This will give:

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

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

It may also be a bit faster if you extract the numbers from the list once instead of twice:

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)

The last thing I would try is checking that they sigs are different with a single comparisson but I do not really expect this to be faster:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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