adplus-dvertising
Coders Packet

Binary search using Python

By Rutik Santosh Kanade

The goal of binary search is to search whether a given number is present in the string or not. First, check whether it is present in the middle or not then check for front and rear using Python.

import random
passlen = int(input("enter the length of password :"))
x="a[email protected]#$%^&*()?"
p =  "".join(random.sample(x,passlen ))
print (p)
lst = [1, 3, 2, 4, 5, 6, 9, 8, 7, 10]
lst.sort()
first = 0
last = len(lst) - 1
mid = (first + last) // 2
item = int(input("enter the number to be search :"))
found = False
while (first <= last and not found):
    mid = (first + last) // 2
    if lst[mid] == item:
        print(f"found at location {mid}")
        found = True
    else:
        if item < lst[mid]:
            last = mid - 1
        else:
            first = mid + 1

if found == False:
    print("Number not found")

 

Download Complete Code

Comments

No comments yet

Download Packet

Reviews Report

Submitted by Rutik Santosh Kanade (rutikkanade)

Download packets of source code on Coders Packet