Bottom Page

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()
Larz60+ wrote Mar-08-2019, 05:36 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.

Fixed for you this time, please use BBcode tags on all future posts. Thank you.
Quote
#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()
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Interactive Menu, String Search? maggotspawn 3 150 May-11-2020, 05:25 PM
Last Post: menator01
  search binary file and list all founded keyword offset Pyguys 4 249 Mar-17-2020, 06:46 AM
Last Post: Pyguys
  hex file to binary or pcap to binary baran01 1 522 Dec-11-2019, 10:19 PM
Last Post: Larz60+
  basic binary search deep_logic 4 426 Sep-28-2019, 03:39 PM
Last Post: newbieAuggie2019
  CSV file from Binary to String mr_byte31 2 3,249 Jul-27-2019, 08:46 PM
Last Post: snippsat
  Re.search misses string end CaptainCsaba 3 994 May-25-2019, 01:46 PM
Last Post: heiner55
  HELP: String of Zero's and One's to binary byte schwasskin 1 1,440 May-19-2019, 07:31 AM
Last Post: heiner55
  search a string backwards Skaperen 2 548 Dec-30-2018, 04:32 AM
Last Post: Skaperen
  converting binary b'0x31303032\n' to "1002" string amygdalas 2 608 Nov-07-2018, 03:50 AM
Last Post: amygdalas
  ldap3 question, using a variable in search string gentoobob 1 1,112 Apr-28-2018, 11:16 AM
Last Post: gentoobob

Forum Jump:


Users browsing this thread: 1 Guest(s)