1

I am coming from C# background and I have hard time figuring out how to run python script.

So, I wrote this simple recursive binary search and found online that I can do something like this:

def chop(array, search, lo, high):

    if lo <= high:
         middle = (high + lo) /2
         if array[middle] == search:
             return 'true'
         elif search > array[middle]:
             return chop(array, search, middle + 1, high)
         else:
             return chop(array, search, lo, middle -1)
     return 'false'



if __name__ == '__main__':
    a = [1,2,3,4,5,6,7,8,9,10]
    print chop(a, 21, 0, len(a) -1)

the __main__ will be main my method to call the chop function from but it doesn't work. I have it saved in a test.py file. Also I though I can somehow run just the chop function from Python Shell, but I have no idea how to do it. Please advice. Thank you.

6
  • Which command are you using to run it? Commented Mar 23, 2012 at 0:16
  • I open IDLE and then create new file and just click F5 to run it. Commented Mar 23, 2012 at 0:17
  • it seems that the indentation is wrong, the chop function should be on the same level of indentation as if __name__ == '__main__':. Commented Mar 23, 2012 at 0:17
  • yep nye17, and also return was one space too much to the right. Thanks! Commented Mar 23, 2012 at 0:19
  • Are you getting a traceback, an error or something? Have you tried to run it from command line? $ python myscript.py Commented Mar 23, 2012 at 0:20

2 Answers 2

3

If you are in the directory where the script is located, just run

python test.py

If you want to run the chop function from the interpreter, start the interpreter in the directory where the script is located and execute

import test
test.chop([...]) # your array

That should do it. If it doesn't, you probably have syntax or other errors in your code, like indentation that you already discussed in comments to your question.

Sign up to request clarification or add additional context in comments.

Comments

1

one way -

def chop(array, search, lo, high):

if lo <= high:

....

a = [1,2,3,4,5,6,7,8,9,10]

chop(a, 21, 0, len(a) -1))

And you handle print in main code.

Other way is as Irfy suggested, something like below (consider your file name is chop.py) -

'$ python Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53) [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import chop`

>>> a = [1,2,3,4,5,6,7,8,9,10]

>>> f = chop.chop(a, 21, 0, len(a) -1))

>>> print f

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.