Home > Net >  I need the code to stop after break and it should not print max(b)
I need the code to stop after break and it should not print max(b)

Time:12-01

Rahul was learning about numbers in list. He came across one word ground of a number.

A ground of a number is defined as the number which is just smaller or equal to the number given to you.Hence he started solving some assignments related to it. He got struck in some questions. Your task is to help him.

O(n) time complexity

O(n) Auxilary space

Input Description: First line contains two numbers ‘n’ denoting number of integers and ‘k’ whose ground is to be check. Next line contains n space separated numbers.

Output Description: Print the index of val.Print -1 if equal or near exqual number

Sample Input : 7 3 1 2 3 4 5 6 7 Sample Output : 2

`

n,k = 7,3
a= [1,2,3,4,5,6,7]
b=[]
for i in range(n):
    if k==a[i]:
        print(i)
        break
    elif a[i]<k:
        b.append(i)
print(max(b))

`

CodePudding user response:

I've found a solution, you can pour in if you've any different views

n,k = 7,12
a= [1,2,3,4,5,6,7]
b=[]
for i in range(n):
    if k==a[i]:
        print(i)
        break
    elif a[i]<k:
        b.append(i)
else:
    print(max(b))

CodePudding user response:

From what I understand, these are the conditions to your question,

  1. If can find number, print the number and break
  2. If cannot find number, get the last index IF it's less than value k

Firstly, it's unsafe to manually input the length of iteration for your list, do it like this:

k = 3
a= [1,7,2,2,5,1,7]
finalindex = 0
for i, val in enumerate(a):
    if val==k:
        finalindex = i   # 1 to index because loop will end prematurely
        break
    elif val>=k:
        continue
    finalindex = i   #skip this if value not more or equal to k
    
print(finalindex)    #this will either be the index of value found OR if not found, 
                     #it will be the latest index which value lesser than k

Basically, you don't need to print twice. because it's mutually exclusive. Either you find the value, print the index or if you don't find it you print the latest index that is lesser than K. You don't need max() because the index only increases, and the latest index would already be your max value.

Another thing that I notice, if you use your else statement like in your answer, if you have two elements in your list that are larger than value K, you will be printing max() twice. It's redundant

else:
    print(max(b))
  • Related