0

My code is test I'm trying to do to figure out why p & ~(p & (p - 1)) won't test for exponents of 2. anyway, the interpreter doesn't like in = 1 before the while loop for some reason.

code:

def getnumber(str):
    num=0
    for i in str:
        zz = ord(i)-48
        if zz<0 or zz>9:
            num=-1
            break
        else:
            num=(num*10)+zz
    return num

def testexp2(p):
    table = {1:1,2:2,4:3,8:4,16:5,32:6,64:7,128:8,256:9}
    if p & ~(p & (p - 1)):
        print "yes"
    else:
        print "no"


in = 1
while in is not -1:
    in = raw_input("> ")
    in = getnumber(in)
    if in>-1:
        testexp2(in)
    else:
        print "\nDone\n\n"
3
  • 1
    in is a reserved keyword in python. And you should use while inp ! = -1 not while inp is not -1. Commented Aug 4, 2013 at 14:07
  • FYI you can do a power-of-2 test with p & (p-1) == 0, that's somewhat simpler. Commented Aug 4, 2013 at 14:13
  • I did that to exclude 0 from returning true Commented Aug 4, 2013 at 23:25

2 Answers 2

5

Few problems:

  1. in is reserved keyword in python, so you can't use it as a variable name.
  2. while inp is not -1 should be while inp != -1. ( I used inp instead of in)
  3. The getnumber function can be reduced to:

Code:

def getnumber(strs):
    num = int(strs)
    return -1 if num < 0 else num
Sign up to request clarification or add additional context in comments.

4 Comments

@arshajii it would only work for small integers from -5 to 256, and it's a bad idea to compare integers like that. stackoverflow.com/questions/11476190/why-0-6-is-6-false
The small integer caching is a Cpython implementation detail and is manifestly confusing to people having trouble with the is not and != distinction.
@arshajii - even worse, it will work sometimes, but not others. It works when an an interning cache finds the same value, so that identity matching with is will work then. But that cache is just an optimization, not a language feature, so you are not guaranteed that it will always be checked when comparing ints. If you are testing for equality in ints, use '=='.
@PaulMcGuire That's a good point; while in CPython it will always work, it may not work in other implementations.
3

You can't declare a variable called in, that's a reserved word (or keyword) of the language, it's an operator that tests for membership. Simply rename it to something else in your code:

txt = raw_input("> ")
txt = getnumber(txt)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.