Issue
The code is simple and you will be able to tell what it does once you see it.
n = int(input())
if(n%2!=0):
print 'Weird'
elif(n%2==0):
if(n>=2 & n<=5):
print 'Not Weird'
elif(n>=6 & n<=20):
print 'Weird'
elif(n>20):
print 'Not Weird'
It works fine, but it shows errors for 2 cases only. When input is 18
, its says 'Not Weird'
whereas the output should be 'Weird'
. The same thing is happening when the input is 20
.
Its probably a silly mistake or something but I just can't seem to put my finger on it and I need someone to have a look at it.
Solution
This condition doesn't do what you think it does:
>>> n = 18
>>> n >= 2 & n <= 5
True
It is actually doing this:
>>> n >= (2 & n) <= 5
True
Proof:
>>> import ast
>>> ast.dump(ast.parse('n >= 2 & n <= 5'), annotate_fields=False)
"Module([Expr(Compare(Name('n', Load()), [GtE(), LtE()], [BinOp(Num(2), BitAnd(), Name('n', Load())), Num(5)]))])"
>>> ast.dump(ast.parse('n >= (2 & n) <= 5'), annotate_fields=False)
"Module([Expr(Compare(Name('n', Load()), [GtE(), LtE()], [BinOp(Num(2), BitAnd(), Name('n', Load())), Num(5)]))])"
docs reference on operator precedence is here.
Instead, use this:
2 <= n <= 5
Answered By - wim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.