2017-10-09 656 views
-1

所以我想要做的是找到交替數字的數量,使它交替與-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

回答

0

嘗試:

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