Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Linear Search
#1
Can someone help me with this .I am having so many difficulties in it .
I am not fully understanding how to proceed with it . 

Setup Linear Search
Write a functiona that takes a list (L) and a number of times to search through it (N), and executes teh following instructions:
Compute the min and max of L
Loop through N times:
Generate a random number between min and max values of L
Use the list index() method to find the randome number
In [ ]:
import random
def linear_search_tester(L, N):
    #Put your code here....
    # random.randrange(0,size)
    return None

X = [1,2,3,4,5,6,7,8,9,10,20,30,40,50,100]
I am trying to use this code. BUt how can i get the max and min in it .

def linear( target, list ):
       """ returns the position of target,if not found 
               returns -1"""
position = 0
if len(list)==0:
   return -1

else:
   while position <= (len(list)+1):
       if target == list[position]:
           return position
       position += 1
           return -1
Reply
#2
First, you need to indent the code below the def statement. Currently it is not part of the function you are defining. Indenting is the way to show that it is part of the function you are defining.

Second, your parameters of target and list do not match the parameters specified in the problem.

Third, you are not doing anything N times. To do something N times, you use:

for times in range(N):
Finally, you can use the min and max functions to find the min and max of a list, and you will need to import the random module to generate random numbers.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
It is difficult to understand what you want.
Maybe this helps.
#python3
import random

def linear_search_tester(L, N):
    minimum = min(L)
    maximum = max(L)
    for _ in range(N):
        position = random.randint(0, len(L)-1)
        rand_num =L[position]
        print("minimum: {0} maximum: {1} random: {2} position: {3}".format(minimum, maximum, rand_num, position))

#test
X = [1,2,3,4,5,6,7,8,9,10,20,30,40,50,100]
print(X)
linear_search_tester(X, 10)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Linear search issue oli_action 5 2,396 Oct-13-2020, 10:02 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020