Home > other >  Trying to make a function to find a specified target
Trying to make a function to find a specified target

Time:07-22

So I am trying to make a searching function. But that doesn't work right everytime. Gives the right output sometimes tough. Here is what i did:

import random

def normal_search(l, target):
    # printing the list
    l1 = l
    x = ' '.join([str(l)])
    print(f'The list is {x}')

    choose = random.choice(l)

    if choose == target:
        index = l.index(choose)
        index  = 1
        print(f"I found it! It's {index}. element.")

    while choose != target:
        l.remove(choose)
        choose = random.choice(l)
        print(choose)
    index = l1.index(choose)
    index  = 1
    print(f"normal_search I found it! It's {index}. element.")

# creating a shuffled list of 0 to 10
a = []
n = 0
while len(a) < 10:
    n  = 1
    a.append(n)
random.shuffle(a)

normal_search(a, 5)

I am trying to get the target as output. What is making the output wrong?

CodePudding user response:

I think the error is due to the fact that every time it does not find the target element the list decreases by 1 and if the removed element is before the target element it will change index.

I think the only solution is to stop removing the wrong elements, this would guarantee the correct functioning of the program but would increase its execution times.

CodePudding user response:

import random

def normal_search(l, target):
    # printing the list
    x = ' '.join([str(l)])
    print(f'The list is {x}')

    while True:
        choose = random.choice(l)
        if choose == target:
            index = l.index(choose)
            index  = 1
            print(f"normal_search I found it! It's {index}. element.")
            break

# creating a shuffled list of 0 to 10
a = list(range(10))
random.shuffle(a)

normal_search(a, 5)

As @FraRomee said, you are removing one element every step, suppose at first you have a list like: [0, 6, 4, 2, 3, 5, 1, 8, 9, 7], and index(5) is 6 and you randomly choose an element: 3 and it is not equal to 5 and you remove it, then you have [0, 6, 4, 2, 5, 1, 8, 9, 7] and length of list is 9 and index(5) is 5 and so on you choose 6 and remove it and you have [0, 4, 2, 5, 1, 8, 9, 7].

so if this time you select 5 correctly, index is 4 and it is correct for new list but is wrong for initial list and you cant use it for your own.

my code points:

  1. you can create a list from a to b using list(range(a,b 1)) and you don't need while loop.
  2. you can choose all elements from first in while body using break statement. if condition is False, so break loop, if not, go on and choose a new element.
  • Related