& Operator Use in Python in Program - python

What does this y & 3 do exactly and how does this if..if y & 3..else statement works ? Please anybody could explain ? Taken from https://www.hackerrank.com/challenges/day-of-the-programmer/leaderboard
y = int(input())
if y < 1918:
ftext = "13.09.{}" if y & 3 else "12.09.{}"
elif y > 1918:
ftext = "13.09.{}" if (y & 3) or (y % 400 and not y % 100) else "12.09.{}"
else:
ftext = "26.09.{}"
print(y & 3)
print(ftext.format(y))

& operator does a bitwise AND between the operands.
y&3 masks the bits of y with the bits of 3.
Thus if y = 11110111 and 3 = 00000011
y&3 will evaluate to 00000011
"13.09.{}" if y & 3 else "12.09.{}" checks the condition whether the last 2 bits of y are not both zero. if the last 2 bits of y are zero, the condition will become false.

Related

What does (x < y) | (x > z) do?

def my_function(x,y,z):
out = True
if(x < y) | (x > z):
out = False
return out
Can you help me understand what this is doing? Is it, "out is True, but if x is less than y or greater than z: out is False"? I am unsure about the | operator.
TL;DR, someone thought they were clever.
This code takes advantage of some implementation details about booleans and then does some binary integer operations.
To understand it we need to cover a few things:
the > and < operators in a comparison will give back boolean True or False.
Boolean True and False are actually subclasses of int and function as 1 and 0 respectively in operations that expect an integer (try running True + 1 in your REPL).
The | operator is bitwise OR (as opposed to logical OR which is just or) which works on integers.
And now we can understand the code: the <> comparisons gives us a bool that gets used as an integer 1 or 0 and ORed bitwise with the result of the other comparison.
An even cleverer person would note that bitwise OR with 1's and 0's would only be 0 if both were 0, and just check for that condition:
1 | 1 # 1
1 | 0 # 1
0 | 1 # 1
0 | 0 # 0
This code is needlessly obfuscated: there's no reason to treat the True/False as 1/0 just to do bit manipulation when regular boolean logic would work. This will work identically:
def my_function(x, y, z):
return y <= x <= z
Best way to wrap your head around code you are not sure about is to test it:
testValues = [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
for x, y, z in testValues:
print("The values are: x = %d, y = %d, z = %d" % (x, y, z))
print("out is:", my_function(x, y, z))
def my_function(x,y,z):
global out
out = True
if(x < y) | (x > z):
out = False
return out
x = 6
y = 2
z = 5
my_function(x,y,z)
The above code outputs True/False based on the values of x,y,z. If x is smaller than y OR if x is greater than z it will change the value of 'out' to False.You can further customize the code to do stuff with the output. Like so:
if out == True:
//some stuff to execute when true
else:
//some stuff to execute when false

I am wondering why the following outputs (529, 23) rather than (484, 22)

for x in range(0,501):
m = x ** 2
if m > 500:
break
print (m,x)
#this outputs a value for the highest square that is above 500 when I want the highest that is below 500
Your code assigns the value of m before breaking, so it stores that value before breaking.
Try this instead:
for x in range(0, 501):
if (x + 1) ** 2 > 500:
m = x ** 2
break
print(x, m)
Notes
Since you're new and it sounds like you're still learning about coding, I will add a few pointers.
First, you don't need to assign value to x to test the value of a function applied to it. Second, a better approach would be to use a while loop rather than a for loop, like this:
x = 0
while (x + 1) ** 2 < 500:
x = x + 1
print(x, x**2)
Additionally, loops are slow, brute force ways to write code. Sometimes that's okay or necessary, but when there's a very efficient way to solve a problem without a loop, it's usually better to use it. For example, to find the smallest integer whose square is less than or equal to x, we can use:
import math
def int_root(x):
return int(math.sqrt(x))
int_root(500)
The problem is you are breaking the loop once the value for m has already exceeded 500. So when you try to print the value for m it is the value that is above 500.
A solution would be to use the value of x and because we know that the desired value would be one less than this, we can compute m like so:
for x in range(501):
m = x ** 2
if m > 500:
break
x -= 1
print(x**2, x)
Yet another approach:
n = 0
for x in range(500):
m, n = n, (x + 1) ** 2
if n > 500:
break
print(m, x) # 484 22
As mentioned by others the issue with your code is that when you check to see if m is greater than 500, if m is exceeding 500 the program breaks the loop, the catch is that m has already been given the value that is over 500 and as such prints that out instead of the desired one before. To counteract this we can add to x and square the result to see if that answer is over 500 and if it is the program will break.
def squareless(top):
for x in range(0, top):
if (x + 1) ** 2 > top + 1:
m = x ** 2
print(x, m)
break
squareless(500)
You break the loop after m already exceeds 500, so (529, 23) is expected. Note that 23 ** 2 = 529. You want to retreat to the previous x and previous m in this case.
for x in range(0,501):
m = x ** 2
if m > 500:
x -= 1
m = x ** 2
break
print (m,x) # 484 22
Or check the next x to break before exceeding 500:
for x in range(0,501):
m = x ** 2
if (x+1) ** 2 > 500:
break

First non zero result bitwise AND python

In numbers like 16, performing bitwise AND on all numbers from 1 to 15 gives result 0. I want to find out the first number that doesn't give 0 when bitwise AND is performed on it.
TLDR : Find smallest x such that x AND y ! = 0
y is given
You can do brute force approach:
while True:
y=int(input('y='))
x=1
while True:
if(x & y !=0):
print(x)
break
x*=2
The solution is to find the first bit from right, which is 1.
For example,
y = 16 = 0b10000
^
y = 12 = 0b1100
^
def get_x(y):
i = 0
while True:
if (y >> i) & 1 == 1:
break
i += 1
return 1 << i
This seems cleverer.
def get_x(y):
return y & (-y)
Find the lowest set bit

'if x % 2: return True' , wouldn't that return True if the number was divisible by 2?

I don't understand how if not x % 2: return True works. Wouldn't that mean this if x is not divisible by two, return True? That's what i see in this code.
I see it as if not x % 2: return True would return the opposite of if a number is divisible by 2, return True.
I just don't understand how that part of the syntax works.
def is_even(x):
if not x % 2:
return True
else:
return False
Wouldn't that mean this if x is not divisible by two, return True?
No, because when x is not divisible by 2 the result of x%2 would be a nonzero value, which will be evaluated as True by Python, so its not would be False.
Read more about Truth value testing in python.
The modulo operator % returns the remainder of a division. If x is divisible by 2 ('even'), then the remainder is zero and x % 2 thus evaluates to zero (=False), which makes the whole expression True.
note, to add to the other answers: x % 2 does not mean "x is divisible by 2"; instead, it is the modulo operator, and returns the value y such that x is congruent to y (mod 2), which is really just the remainder of dividing x by 2.
Here is a fix for your code:
def is_even(x):
if not x % 2 == 0:
# if x is divisible by two, the
# remainder will be 0
return True
else:
return False
See also: The modulo operator, in the python language reference (under "Binary Arithmetic Operators", fourth paragraph down.
If the remainder of X / 2 is 0, then return true
2 % 2 = 0
!0 = true
Simpler and readable is for instance
def is_even(x):
return x % 2 == 0
where it explicitly tells the expression must equate zero in order for the function to return True.
If operation X modulo 2 = 0, function returns true - which means that the number is even.
Operation modulo 2 returns the remainder from division by 2.
Example:
5 % 2 = 1 because 5 = 2*2 + 1
7 % 2 = 1 because use 7 = 3*2 + 1
6 % 2 = 0 because 6 = 3*2 + 0

What's wrong with this Modulo in Python 33

from math import *
def prime():
a = 0
b = 0
x = 2*a+1
y = b
for a in range (1,5000) and b in range (0,5000) and y<x :
ctr = 0
if (x % y == 0):
ctr += 1
return [None]
else:
primes = (x)
ctr+= 1
return [None]
print (primes[999]);
I have a problem I need to solve but when it gets to the modulo ( %) sign it says TypeError: 'bool' object is not iterable"
Instead of comparing the values, you are assigning 0 to x % y, which is not possible. You can fix it like this
if (x % y == 0):
After fixing that,
for a in range (1,5000) and b in range (0,5000) and y<x :
this line will not work, you have to split the loops like this
for a in range (1,5000):
for b in range (0,5000):
...
...
The modulo sign is fine, note the ^ in the error message.
File "so-modulo-test.py", line 11
if (x % y = 0):
^
SyntaxError: invalid syntax
= indicates an assignment statement. You want ==, the equal comparison operator, as in
if x % y == 0:
Additionally, and is the logical AND, and not to be confused with how a human would talk. Your loop should look like:
for a in range (1,5000):
for b in range (0, x):
...

Categories