2013-11-09 37 views
0

給定一個列表,[4,5,5,1,8,3,1,6,2,7]我希望能夠找到第一個升序在列表中運行..我想返回列表的起始位置以及它持續的時間。因此,此列表將返回位置0並且長度爲2(4,5)嘗試查找列表中的第一個升序運行Python

如果列表中沒有升序運行,則返回-1。

下面是我到目前爲止,但我似乎無法修復當我運行該程序時得到的「列表索引超出範圍」錯誤。我知道我爲什麼會遇到錯誤,但不知道如何修復它。

import random 

def generate_integer_list (num_integers, low_range, high_range): 
    assert num_integers > 0, "Value must be greater than 0" 
    assert low_range < high_range, "Value must be less than high_range" 

    x_range = range(num_integers) #Create a range for the below for-loop 
    l = [] #Create an empty list 

    #A for loop that goes on for the amount of integers the user wants and 
    #generates a number within the bounds, then adds that number to the list we created above 
    for _x in x_range: 
     r = random.randint(low_range, high_range) 

     l.append(r) 

    print (l) 

    length = len(l) 
    for x in range(length ): 
     t = l[x+1] - l[x] 

     if t == -1: 
      print (True) 
     else: 
      print (False) 


generate_integer_list (5, 0, 10) 

我問是什麼,如何能得到這個功能來找到第一個上升和返回的位置以及長度

+0

您可能會發現'itertools'模塊和代碼'子列表==排序(子表)'很有用。 – rlms

+1

如果你對'itertools'解決方案感興趣,那麼這個模式[here](http://stackoverflow.com/questions/15276156/python-return-lists-of-continuous-integers-from-list)到組運行一起可能派上用場。 – DSM

回答

1

這應做到:

def solve(lis): 
    run_length = 0 
    ind = 0 
    for i, (x, y) in enumerate(zip(lis, lis[1:])): 
     if run_length and y-x != 1: 
      break 
     if y-x == 1: 
      if not run_length: 
       ind = i 
      run_length += 1 
    if run_length: 
     return run_length+1, ind 
    return -1 

演示:

>>> solve([4, 5, 5, 1, 8, 3, 1, 6, 2, 7]) 
(2, 0) 
>>> solve([1, 1, 1, 2, 3, 5, 1, 1]) 
(3, 2) 
>>> solve([1, 1, 1, 1]) 
-1 
>>> solve([1, 2, 5, 6, 7]) 
(2, 0) 
>>> solve([1, 0, -1, -2, -1, 0, 0]) 
(3, 3) 
+0

試過[1,2,5,6,7],我得到(5,0)這是不正確的。任何想法如何解決這一問題?我正在嘗試自己修復它。 – l00kitsjake

+0

@JacobMammoliti錯誤的方法?你想要升序數字之間的差異只是1? –

+0

不好意思,應該返回的是(2,0)。長度應該代表提升的長度。編輯:當我的意思是提升我的意思是增加一..我爲此道歉。 – l00kitsjake

1

您的代碼有三個問題:

  1. 而不是測試是否t == -1,你應該測試如果t是正面的。在你給的例子中,對於x=0,t應該是1,因此前兩個元素是遞增的。
  2. 您應該print(或returnFalse外部循環。這樣你就可以在決定是否沒有升序運行之前通過整個列表。
  3. 一旦找到兩個升序號碼,您需要開始計算運行持續的時間。

把所有這些組合起來:

length = len(l) 
run_started = False 
for x in range(length-1): 
    t = l[x+1] - l[x] 
    if t > 0 : 
     if run_started: 
      run_length += 1 
     else: 
      run_started = True 
      run_length = 2 
    else: 
     if run_started: 
      print True 
      print 'Run length:', run_length 
      break 
if not run_started: 
    print False 
相關問題