I have a list of arrays as follows: Array =[3, 6, 5, 7, 2, 4, 3, 5, 4, 5, 4, 7, 6, 7, 1, 7, 4, 6, 3]
example: Value = 3, 6, 5, 7, 2, 4, 3, 5, 4, 5, 4, 7, 6, 7, 1, 7, 4, 6, 3
valley/Peak = v, p, v, p, v, p, v, p, v, p, v, p, v, p, v, p, v, p,v
Advertisement
Answer
logic
assign the index to start from
assign the value of the starting index
make a loop starting from the starting index to the end of the loop
in the loop check if current number is smaller than the starting target
slice the list to create the result sublist
code
JavaScript
x
16
16
1
array = [3, 6, 5, 7, 2, 4, 3, 5, 4, 5, 4, 7, 6, 7, 1, 7, 4, 6, 3]
2
3
start_index = 0 # the index to start from
4
5
# start_index = int(input("Enter the index to start from: ")) # to take this a step further, you could ask the user for the index to start from
6
7
target = array[start_index] # the number in the starting index
8
9
for i in range(start_index, len(array)): # loop from the start index till the end
10
if array[i] < target: # if the current number is smaller than my traget
11
# split the list from the start index to the current index (+1 because the slice is not inclusive)
12
print(array[start_index:i+1])
13
break
14
if i == len(array)-1: # if we reached the end of the list
15
print('fail') # print the rest of the list
16
input
start_index = 0
array = [3, 6, 5, 7, 2, 4, 3, 5, 4, 5, 4, 7, 6, 7, 1, 7, 4, 6, 3]
output
[3, 6, 5, 7, 2]