0

Given a list say, [4, 5, 5, 1, 8, 3, 1, 6, 2, 7] I want to be able to find the first ascending run in the list.. I want to return the starting position of the list and how long it lasts. So this list would return position 0 and length is 2 (4,5)

If there isn't an ascending run in the list, return -1.

Below is what I have so far but I can't seem to fix the "list index out of range" error I get when I run the program. I know why I get the error but not sure how I can fix it.

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)

What I'm asking is, how can get this function to find the first ascension and return the location as well as the length

4

2 回答 2

1

您的代码存在三个问题:

  1. t == -1您应该测试 if 是否t为正,而不是测试是否。在您给出的示例中, forx=0t是 1,因此前两个元素是升序的。
  2. 您应该print(或return)在循环False 之外。这样,您将在决定是否没有上升运行之前浏览整个列表。
  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
于 2013-11-09T21:53:37.823 回答
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)
于 2013-11-09T21:52:29.273 回答