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
  How to read a file as binary or hex "string" so that I can do regex search? tatahuft 3 2,840 Dec-19-2024, 11:57 AM
Last Post: snippsat
  Basic binary search algorithm - using a while loop Drone4four 1 4,110 Jan-22-2024, 06:34 PM
Last Post: deanhystad
  Writing a Linear Search algorithm - malformed string representation Drone4four 10 5,966 Jan-10-2024, 08:39 AM
Last Post: gulshan212
  Add one to binary string uwl 2 3,192 Sep-11-2022, 05:36 PM
Last Post: uwl
  Search multiple CSV files for a string or strings cubangt 7 16,237 Feb-23-2022, 12:53 AM
Last Post: Pedroski55
  Search string in mutliple .gz files SARAOOF 10 11,647 Aug-26-2021, 01:47 PM
Last Post: SARAOOF
  fuzzywuzzy search string in text file marfer 9 11,896 Aug-03-2021, 02:41 AM
Last Post: deanhystad
  I want to search a variable for a string D90 lostbit 3 4,080 Mar-31-2021, 07:14 PM
Last Post: lostbit
  [HELP] string into binary ZeroPy 2 3,221 Dec-31-2020, 08:15 PM
Last Post: deanhystad
  String search in different excel Kristenl2784 0 2,444 Jul-20-2020, 02:37 PM
Last Post: Kristenl2784

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.