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
There are three issues with your code:
t == -1
, you should test ift
is positive. In the example you give, forx=0
,t
would be 1, and thus the first two elements are ascending.print
(orreturn
)False
outside the loop. This way you'll go through the whole list before deciding if there isn't an ascending run.Putting this all together:
This should do it:
Demo: