鉴于列表说,[4,5,5,1,8,3,1,6,2,7]我希望能够在列表中找到第一个上升运行..我想返回列表的起始位置和持续时间。所以这个列表将返回位置0,长度为2(4,5)
如果列表中没有升序运行,则返回-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 :(得分: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)
答案 1 :(得分:1)
您的代码有三个问题:
t == -1
是否为正,而不是测试是否t
。在您给出的示例中,对于x=0
,t
将为1,因此前两个元素是升序。print
(或return
)False
在循环之外。通过这种方式,您将在决定是否没有提升运行之前浏览整个列表。把这一切放在一起:
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