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
  basic binary search deep_logic 4 233 Sep-28-2019, 03:39 PM
Last Post: newbieAuggie2019
  CSV file from Binary to String mr_byte31 2 389 Jul-27-2019, 08:46 PM
Last Post: snippsat
  Re.search misses string end CaptainCsaba 3 727 May-25-2019, 01:46 PM
Last Post: heiner55
  HELP: String of Zero's and One's to binary byte schwasskin 1 1,199 May-19-2019, 07:31 AM
Last Post: heiner55
  search a string backwards Skaperen 2 386 Dec-30-2018, 04:32 AM
Last Post: Skaperen
  converting binary b'0x31303032\n' to "1002" string amygdalas 2 429 Nov-07-2018, 03:50 AM
Last Post: amygdalas
  ldap3 question, using a variable in search string gentoobob 1 758 Apr-28-2018, 11:16 AM
Last Post: gentoobob
  Search for string values in begood321 7 966 Mar-21-2018, 02:36 AM
Last Post: tannishpage
  Help with python code to search string in one file & replace with line in other file mforthman 26 3,311 Dec-19-2017, 07:11 PM
Last Post: Larz60+
  Need help for string search Supradha 1 1,225 May-31-2017, 01:03 AM
Last Post: ichabod801

Forum Jump:


Users browsing this thread: 1 Guest(s)