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]
I want to print the range from the first given number to the next lowest number after self.
example: Array =[3, 6, 5, 7, 2, 4, 3, 5, 4, 5, 4, 7, 6, 7, 1, 7, 4, 6, 3] given number 3 in index 0 as a starting number.
Let's start with index 0 which has a value of 3 the lowest value after itself is index 4 with a value of 2 i.e subarray = [3, 6, 5, 7, 2]
example 2 let's pick 5 as the next number, then the next lowest number looks like this subarray = [5, 7, 2]
such that I can get the highest peak number from the subarray.
CodePudding user response:
As Mark Ransom & SA.93 suggested, indexing in python starts from 0. Maybe you are more familiar with R... :) For your solution, try this;
def next_lowest_num(Array,num):
lst = []
for i in Array[Array.index(num):]:
if i >= num:
lst.append(i)
else:
lst.append(i)
break
return lst
print(next_lowest_num(Array=[3, 6, 5, 7, 2, 4, 3, 5, 4, 5, 4, 7, 6, 7, 1, 7, 4, 6, 3],num=3))
print(next_lowest_num(Array=[3, 6, 5, 7, 2, 4, 3, 5, 4, 5, 4, 7, 6, 7, 1, 7, 4, 6, 3],num=5))
# Output
[3, 6, 5, 7, 2]
[5, 7, 2]
Hope this Helps...
CodePudding user response:
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
array = [3, 6, 5, 7, 2, 4, 3, 5, 4, 5, 4, 7, 6, 7, 1, 7, 4, 6, 3]
start_index = 0 # the index to start from
# 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
target = array[start_index] # the number in the starting index
for i in range(start_index, len(array)): # loop from the start index till the end
if array[i] < target: # if the current number is smaller than my traget
# split the list from the start index to the current index ( 1 because the slice is not inclusive)
print(array[start_index:i 1])
break
if i == len(array)-1: # if we reached the end of the list
print('fail') # print the rest of the list
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]