3 Replies - 279 Views - Last Post: 28 September 2019 - 01:11 AM Rate Topic: -----

#1 DATAfiend   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 17-February 12

Python 3.7 basic binary search

Posted 27 September 2019 - 08:46 PM

Hi all,
I'm a noobie coder and am using a book called "Grokking Algorithms". So, the very first algo is a binary search. I'm typing in this code:
#bin search
#
def binary_search(list, item):
    low = 0
    high = len(list) - 1

    while low <= high:
        mid = (low + high)
        guess = list[mid]
        if guess == item:
            return mid
        if guess > item:
            high = mid - 1
        else:
            low = mid + 1
    return None

my_list = [1, 3, 5, 7, 9]

print binary_search(my_list, 3) # => 1
print binary_search(my_list, -1) # => None

    


But I keep getting a syntax error on the "print binary_search(my_list, 3) # =>"
I'm doing this to teach myself (I have a bad teacher).
Thanks in advance

Is This A Good Question/Topic? 0
  • +

Replies To: Python 3.7 basic binary search

#2 modi123_1   User is offline

  • Suitor #2
  • member icon



Reputation: 15356
  • View blog
  • Posts: 61,557
  • Joined: 12-June 08

Re: Python 3.7 basic binary search

Posted 27 September 2019 - 09:23 PM

Please copy/paste the error here.
Was This Post Helpful? 0
  • +
  • -

#3 DATAfiend   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 17-February 12

Re: Python 3.7 basic binary search

Posted 27 September 2019 - 11:37 PM

View Postmodi123_1, on 27 September 2019 - 09:23 PM, said:

Please copy/paste the error here.

Traceback (most recent call last):
File "C:\Users\araki\AppData\Local\Programs\Python\Python37-32\binary search.py", line 19, in <module>
print (binary_search(numbers, 7)) # => 1
NameError: name 'numbers' is not defined
Was This Post Helpful? 0
  • +
  • -

#4 DK3250   User is offline

  • Pythonian
  • member icon

Reputation: 561
  • View blog
  • Posts: 1,791
  • Joined: 27-December 13

Re: Python 3.7 basic binary search

Posted 28 September 2019 - 01:11 AM

Hm, assuming you execute python ver. 3.x, the only error I see in the code of post #1 is missing parhanteses in the print statements.

The error reported in post #3 is not from the code shown in post #1 - so, the error info is of no use; sic!

One more thing:
"list" is a python keyword - the term should not be used as a variable name.
Better make good habits from the start and avoid such potential danger fields.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1