Home > database >  Can any one explain me this question Consider the searching problem
Can any one explain me this question Consider the searching problem

Time:08-02

Can any one explain me this Question?
I am not understanding what it is asking me to do!

Question:
Consider the searching problem.
Input: a sequence of n numbers A = [A1,A2,...An] and a value v.
Output: an index i such that v = A[i] or the special value NIL if v does not appear in A.
Write pseudo-code for linear search, which scans the sequence, looking for v. Using a loop invariant fulfilling the three necessary properties.

My Answer:

a = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

n = int(input("Enter a number :"))

if n in a:
    print(f"{n} is in the sequence")
else:
    print("NIL")

Is this answer correct?

CodePudding user response:

Thank You @Guy

my solution is:

a = [77,33,29,54,97,82,7,44] # a set(list) of numbers assigned to A

n = int(input("Enter a number :")) # taking input from user

# using for else statement

for i in range(len(a)): # looping till the length of A
    v = a[i] # assigning the index value of A to v (Unnecessary) you can directly apply to statement like if a[i] == n
    if v == n: # checking whether the given value is in the sequence of list
        print(f"{n} is in the sequence of a list position at {i}") # Displaying the end result
        break # stoping the loop from continuing till the end of the list length
else: # if the value is not in the it will display NIL
    print("NIL") # Displaying the end result

If there is a better way to solve please do consider to post your answer

CodePudding user response:

You must work with the indexes of the list so the answer might be a code like:

A = [11,10,0,13,6,25,9,17,2,19]

v = 6

for i in range(len(A)):
    if A[i] == v:
        print(i)
        break
else:
    print("NIL") 

For this example the answer will be 4 because the number that is given from the input is 6 and we can find that number ( v ) at the 4th index of our list ( A ). Hope that was helpful.

  • Related