What exactly does this mean in Python? [duplicate] - python

This question already has answers here:
What is the result of % in Python?
(20 answers)
Closed 9 years ago.
I was working on a project Euler problem and found this code online:
a = 1
b = 2
s = 0
while b <= 4000000:
if not b % 2:
s += b
a, b = b, a + b
print s
I am not entirely sure what if not b % 2: means and was wondering if someone would mind shedding some light on it for me.

From the docs:
The % (modulo) operator yields the remainder from the division of the first argument by the second.
e.g. 5/2 == 2.5 # or 2 remainder 1, 5%2 == 1
The only time a % operation will come out to 0 (which satisfies not x%y) is if it's evenly divisible. In other words, 4 % 2 == 0 because 2 divides 4 evenly.
In your code, it's saying:
while b is less than 4,000,000:
if b is even:
set s equal to s+b

The modulo % operator returns the remainder of the division of b per 2 (in your case).
So if not b % 2 is the same meaning that if b % 2 == 0: it checks if the number is even.

b % 2 is the remainder after dividing by 2. So it will be 1 if b is odd, or 0 otherwise.
if not b % 2 can thus be translated to "if b is even"

Python interprets the value 1 as True and 0 as False:
>>> 1 == True
True
>>> 0 == True
False
The modulo operation x % y returns the remainder when x is divided by y. Therefore b % 2 will be 0 when b is even, and 1 when b is odd.
Combining all this together, the statement if not b % 2: corresponds to "if b is even".

It's just a cute way of writing if b%2==0. The not operator when passed 0 will return True, and False given anything else.

Related

Why is 0^1 = 1 in Python? [duplicate]

This question already has answers here:
What does the caret (^) operator do?
(5 answers)
Closed 25 days ago.
I was looking at a problem solution in Python where the only number without a pair in an array is returned. The solution is below :
def solution(A):
n = len(A)
if A is None or n == 0:
return 0
if n == 1:
return A[0]
result = 0
for i in range(0, n):
result ^= A[i]
return result
How is the loop logic returning back the unique number?
The ^ operator in python is the XOR operator
and what it means is that for each a,b:
a^b = a'b + b'a
and in truth table it looks like this:
a
b
a^b
0
0
0
0
1
1
1
0
1
1
1
0

checking if a very large number is divisible by 2 comes wrong

I am trying some stuff on the 3x+1 problem and noticed when I check if this num is divisible by two comes always true even that the second iteration should be false it goes like this for 20 iterations and then start to act right. I guess it is a long number issue?
num = 3656565605161651626526625291991265161656
while num != 1:
if (num % 2 == 0):
num /= 2
print("2")
else:
num *= 3
num += 1
print("3")
num2=f'{num:.1f}'
print(num2)
Here is the start of the result:
2
1828282802580825918440824287108404346880
2
914141401290412959220412143554202173440
2
457070700645206479610206071777101086720
2
You need to use integer division, not float.
num //= 2
Here are the first 20 lines of the output, where you can see it is working:
2
1828282802580825813263312645995632580828
2
914141401290412906631656322997816290414
2
457070700645206453315828161498908145207
3
1371212101935619359947484484496724435622
2
685606050967809679973742242248362217811
3
2056818152903429039921226726745086653434
2
1028409076451714519960613363372543326717
3
3085227229355143559881840090117629980152
2
1542613614677571779940920045058814990076
2
771306807338785889970460022529407495038

usage of continue loop, and or

I'm quite new in Python. I have searched on site but I couldn't find solution for that pease show me if I missed.
I am trying to understand loops and "and" "or" I did some experiment with these elements but I confused.
Bellow code I was expecting code pass the numbers which isn't dividable by 3 or 5 and print rest. But suprisingly It print the numbers which is dividable by 15! (other words which is dividable by 3 and 5)
for x in range(100):
if x % 3 != 0 or x % 5 != 0:
continue
print(x)
output:
0
15
30
45
60
75
90
And this one I was expecting it will pass the number which isn't dividable 3 and 5 But it prints the numbers which is dividable 3 or 5 as I wanted in my first example.
for x in range(100):
if x % 3 != 0 and x % 5 != 0:
continue
print(x)
output:
0
3
5
6
9
10
12
15
18
20
.............
I don't understand what I am missing. I'm aware that I can make it happen with if, elif and else form but I wanted to learn more about "continue" usage. I'd appereciate if you help me.
Thank you!
You may have an easier time understanding what's happening just by walking through the numbers and seeing what your logic does for each number. You have walked into a logic equivalence that can be confusing, and is expressed in De Morgan's Laws. Essentially you can say
(x % 3 != 0 or x % 5 != 0) = !(x % 3 == 0 and x % 5 == 0)
so your first logic test is checking whether a number is divisible by both 3 and 5, which are the multiples of 15. And your second test is
x % 3 != 0 and x % 5 != 0 = !(x % 3 == 0 or x % 5 == 0)
so you are testing whether a number is divisible by either 3 or 5.
The continue keyword will essentially end the current iteration of the loop, and jump directly to the start of the loop to re-evaluate the loop condition (see https://docs.python.org/3.8/tutorial/controlflow.html).
So, in your first block of code, any time x is not divisible by 3 or 5, it will not print the number, meaning the only numbers which are printed are those which are divisible by both 3 and 5.
You can clear up the or logic like this:
for x in range(100):
if x % 3 != 0: # skip 1,2,4,5,7,8,10,11,13,14,16....
continue
if x % 5 != 0: # skip 1,2,3,4,6,7,8,9,11,12,13,14,16...
continue
print(x) # only numbers that pass both checks 0,15,30,...
With this, only 0, 15, 30, ... get through
If you convert it with boolean algebra,
if x % 3 != 0 or x % 5 != 0:
is the same as
if x % 3 == 0 and x % 5 == 0:
which gives the same results (0,15,30,...)

Python: How to make numeric triangle with recursion

while I was working on the Python practice, I found a question that I cannot solve by myself.
The question is,
Input one integer(n), and then write the codes that make a triangle using 1 to 'n'. Use the following picture. You should make only one function, and call that function various times to solve the question. The following picture is the result that you should make in the codes.
Receive one integer as an argument, print the number from 1 to the integer received as a factor in a single line, and then print the line break character at the end. Once this function is called, only one line of output should be printed.
So by that question, I found that this is a question that requires the
recursion since I have to call your function only once.
I tried to work on the codes that I made many times, but I couldn't solve it.
global a
a = 1
def printLine(n):
global a
if (n == 0):
return
for i in range(1, a + 1):
print(i, end=" ")
print()
a += 1
for k in range(1, n+1):
print(k, end=" ")
print()
printLine(n - 1)
n = int(input())
printLine(n)
Then I wrote some codes to solve this question, but the ascending and descending part is kept overlapping. :(
What I need to do is to break two ascending and descending parts separately in one function, but I really cannot find how can I do that. So which part should I have to put the recursive function call?
Or is there another way can divide the ascending and descending part in the function?
Any ideas, comments, or solutions are appreciated.
Thx
You can use the below function:
def create_triangle(n, k: int = 1, output: list = []):
if n == 1:
output.append(n)
return output
elif k >= n:
output.append(" ".join([str(i) for i in range(1, n + 1)]))
return create_triangle(n - 1, k)
else:
output.append(" ".join([str(i) for i in range(1, n + 1)[:k]]))
return create_triangle(n, k + 1)
for i in create_triangle(5):
print(i)
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
# function to print all the numbers from 1 to n with spaces
def printLine(k):
# create a range. if k is 4, will create the range: 1, 2, 3, 4
rng = range(1, k + 1)
# convert each number to string
str_rng = map(lambda x: str(x), rng)
# create one long string with spaces
full_line = " ".join(str_rng)
print(full_line)
# capture input
n = int(input())
# start from 1, and up to n, printing the first half of the triangle
for i in range(1, n):
printLine(i)
# now create the bottom part, by creating a descending range
for i in range(n, 0, -1):
printLine(i)
Using default parameter as a dict, you can manipulate it as your function variables, so in that way, you can have a variable in your function that keeps the current iteration you are at and if your function is ascending or descending.
def triangle_line(n, config={'max':1, 'ascending':True}):
print(*range(1, config['max'] + 1))
if config['ascending']:
config['max'] += 1
else:
config['max'] -= 1
if config['max'] > n:
config['ascending'] = False
config['max'] = n
elif config['max'] == 0:
config['ascending'] = True
config['max'] = 1
Each call you make will return one iteration.
>>> triangle_line(4)
1
>>> triangle_line(4)
1 2
>>> triangle_line(4)
1 2 3
>>> triangle_line(4)
1 2 3 4
>>> triangle_line(4)
1 2 3 4
>>> triangle_line(4)
1 2 3
>>> triangle_line(4)
1 2
>>> triangle_line(4)
1
Or you can run on a loop, two times your input size.
>>> n = 4
>>> for i in range(0,n*2):
... triangle_line(n)
...
1
1 2
1 2 3
1 2 3 4
1 2 3 4
1 2 3
1 2
1

python modulo operation for basic mathematics operation [duplicate]

I'm embarrassed to ask such a simple question. My term does not start for two more weeks so I can't ask a professor, and the suspense would kill me.
Why does 2 mod 4 = 2?
Mod just means you take the remainder after performing the division. Since 4 goes into 2 zero times, you end up with a remainder of 2.
Modulo is the remainder, not division.
2 / 4 = 0R2
2 % 4 = 2
The sign % is often used for the modulo operator, in lieu of the word mod.
For x % 4, you get the following table (for 1-10)
x x%4
------
1 1
2 2
3 3
4 0
5 1
6 2
7 3
8 0
9 1
10 2
Modulo (mod, %) is the Remainder operator.
2%2 = 0 (2/2 = 1 remainder 0)
1%2 = 1 (1/2 = 0 remainder 1)
4%2 = 0 (4/2 = 2 remainder 0)
5%2 = 1 (5/2 = 2 remainder 1)
Much easier if u use bananas and a group of people.
Say you have 1 banana and group of 6 people, this you would express: 1 mod 6 / 1 % 6 / 1 modulo 6.
You need 6 bananas for each person in group to be well fed and happy.
So if you then have 1 banana and need to share it with 6 people, but you can only share if you have 1 banana for each group member, that is 6 persons, then you will have 1 banana (remainder, not shared on anyone in group), the same goes for 2 bananas. Then you will have 2 banana as remainder (nothing is shared).
But when you get 6 bananas, then you should be happy, because then there is 1 banana for each member in group of 6 people, and the remainder is 0 or no bananas left when you shared all 6 bananas on 6 people.
Now, for 7 bananas and 6 people in group, you then will have 7 mod 6 = 1, this because you gave 6 people 1 banana each, and 1 banana is the remainder.
For 12 mod 6 or 12 bananas shared on 6 people, each one will have two bananas, and the remainder is then 0.
2 / 4 = 0 with a remainder of 2
I was confused about this, too, only a few minutes ago. Then I did the division long-hand on a piece of paper and it made sense:
4 goes into 2 zero times.
4 times 0 is 0.
You put that zero under the 2 and subtract which leaves 2.
That's as far as the computer is going to take this problem. The computer stops there and returns the 2, which makes sense since that's what "%" (mod) is asking for.
We've been trained to put in the decimal and keep going which is why this can be counterintuitive at first.
Someone contacted me and asked me to explain in more details my answer in the comment of the question. So here is what I replied to that person in case it can help anyone else:
The modulo operation gives you the remainder of the euclidian disivion
(which only works with integer, not real numbers). If you have A such
that A = B * C + D (with D < B), then the quotient of the euclidian division of A
by B is C, and the remainder is D. If you divide 2 by 4, the quotient
is 0 and the remainder is 2.
Suppose you have A objects (that you can't cut). And you want to
distribute the same amount of those objects to B people. As long as
you have more than B objects, you give each of them 1, and repeat.
When you have less than B objects left you stop and keep the remaining
objects. The number of time you have repeated the operation, let's
call that number C, is the quotient. The number of objects you keep at
the end, let's call it D, is the remainder.
If you have 2 objects and 4 people. You already have less than 4
objects. So each person get 0 objects, and you keep 2.
That's why 2 modulo 4 is 2.
The modulo operator evaluates to the remainder of the division of the two integer operands. Here are a few examples:
23 % 10 evaluates to 3 (because 23/10 is 2 with a remainder of 3)
50 % 50 evaluates to 0 (50/50 is 1 with a remainder of 0)
9 % 100 evaluates to 9 (9/100 is 0 with a remainder of 9)
mod means the reaminder when divided by. So 2 divided by 4 is 0 with 2 remaining. Therefore 2 mod 4 is 2.
Modulo is the remainder, expressed as an integer, of a mathematical division expression.
So, lets say you have a pixel on a screen at position 90 where the screen is 100 pixels wide and add 20, it will wrap around to position 10. Why...because 90 + 20 = 110 therefore 110 % 100 = 10.
For me to understand it I consider the modulo is the integer representation of fractional number. Furthermore if you do the expression backwards and process the remainder as a fractional number and then added to the divisor it will give you your original answer.
Examples:
100
(A) --- = 14 mod 2
7
123
(B) --- = 8 mod 3
15
3
(C) --- = 0 mod 3
4
Reversed engineered to:
2 14(7) 2 98 2 100
(A) 14 mod 2 = 14 + --- = ----- + --- = --- + --- = ---
7 7 7 7 7 7
3 8(15) 3 120 3 123
(B) 8 mod 3 = 8 + --- = ----- + --- = --- + --- = ---
15 15 15 15 15 15
3 3
(B) 0 mod 3 = 0 + --- = ---
4 4
When you divide 2 by 4, you get 0 with 2 left over or remaining. Modulo is just the remainder after dividing the number.
I think you are getting confused over how the modulo equation is read.
When we write a division equation such as 2/4 we are dividing 2 by 4.
When a modulo equation is wrote such as 2 % 4 we are dividing 2 by 4 (think 2 over 4) and returning the remainder.
MOD is remainder operator. That is why 2 mod 4 gives 2 as remainder. 4*0=0 and then 2-0=2. To make it more clear try to do same with 6 mod 4 or 8 mod 3.
This is Euclid Algorithm.
e.g
a mod b = k * b + c => a mod b = c, where k is an integer and c is the answer
4 mod 2 = 2 * 2 + 0 => 4 mod 2 = 0
27 mod 5 = 5 * 5 + 2 => 27 mod 5 = 2
so your answer is
2 mod 4 = 0 * 4 + 2 => 2 mod 4 = 2
For:
2 mod 4
We can use this little formula I came up with after thinking a bit, maybe it's already defined somewhere I don't know but works for me, and its really useful.
A mod B = C where C is the answer
K * B - A = |C| where K is how many times B fits in A
2 mod 4 would be:
0 * 4 - 2 = |C|
C = |-2| => 2
Hope it works for you :)
Mod operation works with reminder.
This is called modular arithmetic.
a==b(mod m)
then m|(a-b)
a-b=km
a=b+km
So, 2=2+0*4
To answer a modulo x % y, you ask two questions:
A- How many times y goes in x without remainder ? For 2%4 that's 0.
B- How much do you need to add to get from that back to x ? To get from 0 back to 2 you'll need 2-0, i.e. 2.
These can be summed up in one question like so:
How much will you need to add to the integer-ish result of the division of x by y, to get back at x?
By integer-ish it is meant only whole numbers and not fractions whatsoever are of interest.
A fractional division remainder (e.g. .283849) is not of interest in modulo because modulo only deals with integer numbers.
For a visual way to think about it, picture a clock face that, in your particular example, only goes to 4 instead of 12. If you start at 4 on the clock (which is like starting at zero) and go around it clockwise for 2 "hours", you land on 2, just like going around it clockwise for 6 "hours" would also land you on 2 (6 mod 4 == 2 just like 2 mod 4 == 2).
This could be a good time to mention the modr() function. It returns both the whole and the remainder parts of a division.
print("\n 17 // 3 =",17//3," # Does the same thing as int(17/3)")
print(" 17 % 3 =",17%3," # Modulo division gives the remainder.")
whole, remain = divmod(17,3)
print(" divmod(17,3) returns ->",divmod(17,3),end="")
print(" because 3 goes into 17,",whole,"times with a remainder of",remain,end=".\n\n")
The way I go about it is, 2%4 can be interpreted as what is the highest factor of 4 that is less or equal to 2, and that is 0, therefore 2 (the left operand from 2%4) minus(-) 0 is 2

Categories

Resources