Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
binary search string help
#1
Hi! I'm trying to look for a word in my list by way of binary search. But sth doesn;t work. Can sb have a look at it? ;) Thanks!

infile = open("clean.acc", "r")

firstlist = []
for line in infile:
    firstlist.append(line)

first = 0
last = len(firstlist)-1
done = False 

acc = input("Enter your acc nr")

while first<=last and not done:
    mid = (first+last)//2
    if firstlist[mid] == acc:
        done = True
        print(done)
    else:
        if firstlist[mid] > acc:
            last = mid-1
        else: 
            first = mid+1


infile.close()
Reply
#2
Just a little refactoring and it works. I restructured the if statements into a single if...elif...else. The main problem was the mid assignment. Dividing by 2 generates a float and floats cannot be used in indexing; the interpreter would raise an error when trying firstlist[mid] because it's firstlist[4.5] (supposing a nine item list).

infile = open("clean.acc", "r")

firstlist = []
for line in infile:
    firstlist.append(line)

first = 0
last = len(firstlist)-1
done = False 

acc = input("Enter your acc nr")

while first<=last and not done:
    mid = int((first+last)//2)

    if acc < firstlist[mid]:
        first = mid
    elif acc == firstlist[mid]:
        done = True
        print(done)
    else:
        last = mid

infile.close()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Basic binary search algorithm - using a while loop Drone4four 1 307 Jan-22-2024, 06:34 PM
Last Post: deanhystad
  Writing a Linear Search algorithm - malformed string representation Drone4four 10 832 Jan-10-2024, 08:39 AM
Last Post: gulshan212
  Add one to binary string uwl 2 884 Sep-11-2022, 05:36 PM
Last Post: uwl
  Search multiple CSV files for a string or strings cubangt 7 7,842 Feb-23-2022, 12:53 AM
Last Post: Pedroski55
  Search string in mutliple .gz files SARAOOF 10 6,775 Aug-26-2021, 01:47 PM
Last Post: SARAOOF
  fuzzywuzzy search string in text file marfer 9 4,431 Aug-03-2021, 02:41 AM
Last Post: deanhystad
  I want to search a variable for a string D90 lostbit 3 2,582 Mar-31-2021, 07:14 PM
Last Post: lostbit
  [HELP] string into binary ZeroPy 2 2,024 Dec-31-2020, 08:15 PM
Last Post: deanhystad
  String search in different excel Kristenl2784 0 1,678 Jul-20-2020, 02:37 PM
Last Post: Kristenl2784
  Interactive Menu, String Search? maggotspawn 3 2,540 May-11-2020, 05:25 PM
Last Post: menator01

Forum Jump:

User Panel Messages

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