bobek
bobek

Reputation: 8020

different ways of running python script

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.

Upvotes: 1

Views: 370

Answers (2)

Mutant
Mutant

Reputation: 3821

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

Upvotes: 1

Irfy
Irfy

Reputation: 9587

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.

Upvotes: 3

Related Questions