Exercise on Summing Digits | What's with n // = 10 [duplicate] - python

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the reason for having ‘//’ in Python?
While trying to do an exercise on summing digits, I stumbled on this solution:
def sum_digits(n):
import math
total = 0
for i in range(int(math.log10(n)) + 1):
total += n % 10
n //= 10
return total
My question is, what does the second to last line do? How is that proper syntax?

That implements what is called floor division. Floor division (indicated by // here) truncates the decimal and returns the integer result, while 'normal' division returns the answer you may 'expect' (with decimals). In Python 3.x, a greater distinction was made between the two, meaning that the two operators return different results. Here is an example using Python 3:
>>> 10 / 3
3.3333333333333335
>>> 10 // 3
3
Prior to Python 3.x, there is no difference between the two, unless you use the special built-in from __future__ import division, which then makes the division operators perform as they would in Python 3.x (this is using Python 2.6.5):
In [1]: 10 / 3
Out[1]: 3
In [2]: 10 // 3
Out[2]: 3
In [3]: from __future__ import division
In [4]: 10 / 3
Out[4]: 3.3333333333333335
In [5]: 10 // 3
Out[5]: 3
Therefore when you see something like n //= 10, it is using the same +=/-=/*=/etc syntax that you may have seen, where it takes the current value of n and performs the operation before the equal sign with the following variable as the second argument, returning the result into n. For example:
In [6]: n = 50
In [7]: n += 10
In [8]: n
Out[8]: 60
In [9]: n -= 20
In [10]: n
Out[10]: 40
In [11]: n //= 10
In [12]: n
Out[12]: 4

// is the floor division operator. It always truncates the return value to the largest integer smaller than or equal to the answer.

The second to last line is a combination of operators, in a way, including an uncommon one, which is why it's a little confusing.
Let's piece it apart.
First, // in Python is floor division, which basically is division rounded down to the nearest whole number. Thus,
>>> 16//5
3
>>> 2//1
2
>>> 4//3
1
>>> 2//5
0
Finally, the = is there because of a Python syntax that allows one to perform an operation on a variable, and then immediately reassign the result to the variable. You've probably seen it most commonly in +=, as:
>>> a = 5
>>> a += 7
>>> a
12
In this case, //= means "perform floor division, floor dividing the variable by the second argument, then assign the result to the original input variable." Thus:
>>> a = 10
>>> a //= 6
>>> a
1

for the assignment in Python A += B equals to A = A + B ,A *= B equals to A = A * B
same thing applies to "Floor Divide" as well , A //= B equals to A = A // B
Floor Division means return the truncated integer number
>>> 5 // 3 # 1.6
1 # 0.6 will be throw off

Related

Dividing two numbers and printing the result and adding one to the result if there is a remainder, without using if-statements or imports or function? [duplicate]

This question already has answers here:
Is there a ceiling equivalent of // operator in Python?
(9 answers)
Closed 10 days ago.
I'm trying to divide number into groups in plain python without importing or the use of if-statements, and get the division into groups + remainder forming one extra group so that 200 / 99 would be 3, And 7 / 3 would be 3, but that 8 / 4 would still be just 2, and 4 / 2 would be 2 etc.. I cannot import anything so it needs to be in plain python.
I tried storing the numbers from inputs from user into variables and dividing them, and then adding one. I also tried // and adding 1 but I cannot get it to work.
How about this:
a, b = 200, 99
result, remainder = a // b + int(bool(a % b)), a % b
This computes the result by performing an integer divide a // b and computing the remainder a % b. Converting an integer value to a boolean is False for 0 and True for any other value, and converting that back to an integer gives you the value you want to add to the result. The remainder is computed again to assign it, if you need it.
As user #markransom commented, the conversion to int() isn't even necessary, as bool already 'is' an integer type:
>>> isinstance(True, int)
True
So, this works (although it may be considered a bit less readable):
a, b = 200, 99
result, remainder = a // b + bool(a % b), a % b
If you're using a modern version of Python and really want it to be short, this also works:
result = a // b + bool(remainder := a % b)
This uses the walrus operator to assign the remainder when it is first computed, avoiding having to compute it twice as well.
Python boolean operations short-circuit and return the last value evaluated and you can use that to convert a non-zero remainder to 1 for addition to a quotient
def group_me(dividend, divisor):
quotient, remainder = divmod(dividend, divisor)
return quotient + (remainder and 1 or 0)
print(group_me(200, 99))
print(group_me(7, 3))
print(group_me(8, 4))
Output
3
3
2
If remainder is non-zero, remainder and 1 short-circuits and returns 1. Otherwise, the or now becomes 0 or 0, which retains its last value 0.
You could do an if statement mathematically without using if itself:
n, d = 200, 99
x, y = n/d, n//d + 1
result = int((x%1 == 0) * x + (x%1 != 0) * y)
Essentially it is condition * answer 1 + (1 - condition) * answer 2. Then it switch to whichever answer depending on condition being 1 or 0.

Order of Operations - Python 3

Can someone explain why c is equal to 25 and not 30? I keep getting 30 by multiplying a*(b//a) and then adding b to it after.
a=10
b=3*(a-5)
c=b+(b//a)*a
Just do it step by step and you'll see that you're doing
c = 15 + 1*10
Hence c is 25. b//a is floor division, meaning 15/10 becomes 1
An easy way to understand whats going on is to print each steps:
a=10
b=3*(a-5)
print(b)
print(b//a)
print((b//a)*a)
print(b+(b//a)*a)
c=b+(b//a)*a
output
15
1
10
25
(15//10) is equal to 1 so the formula for c is equivalent to 15+1*10 The // operator is floor division which round down to the nearest integer. In additon all the values you are using are integers. To get 30 you need to use the normal divsion operator / and case one of the operands in the division to a floating point number, like this: c = b+(float(b)/a)*a That code sets c to 30.0.
c = b + (b//a)*a = b + ((b//a)*a) = 15 + ((15//10)*10) = 15 + (1*10) = 25
Does this clear it up?
The crucial part is 15//10, because // performs integer division which rounds down to the next integer. Note the difference between / and // in Python 3.
>>> 15/10
1.5
>>> 15//10
1

Precise math.log(x, 2) in Python

In python, I need to get the rounded down logarithm of positive integers for base 2, including big numbers.
However, since floating point math is used, I might get bad results, for example:
>>> import math
>>> int(math.log(281474976710655, 2))
48
However:
>>> 2 ** 48
281474976710656
So the correct result, rounded down, should be 47.
How can I get the correct value?
In Python 3, integers have a .bit_length method, so you should use that to get your rounded down base 2 logarithm.
Here's a short demo:
m = 2 ** 1000
for n in (281474976710655, m-1, m, m+1):
a = n.bit_length() - 1
b = 2 ** a
print(a, b <= n < 2 * b)
output
47 True
999 True
1000 True
1000 True
In python 3 ints even have an efficient .bit_length() method!
>>> (281474976710655).bit_length()
48
>>> (281474976710656).bit_length()
49
In python 2, instead of using floating point math, count the number of bits:
def log2(n):
assert n >= 1
return len(bin(n)) - 3 # bin() returns a string starting with '0b'
(Edited following this comment)

Python Shorthand Operator?

I was researching some information on the topic of trial division, and I came across this symbol in Python:
//=
I got this from here where the code in the example says:
n //= p
I can't tell what this is supposed to mean, and my research continues to bring poor results in terms of webpages.
// is integer division and the
n //= p
syntax is short for
n = n // p
except the value n is modified directly if it supports this.
When you see an operator followed by an =, that is performing the operation and then assigning it into the variable. For example, x += 2 means x = x + 2 or add 2 to x.
The // operator specifically does integer devision instead of floating point division. For example, 5 // 4 gives you 1, while 5 / 4 gives you 1.25 (in Python 3).
Therefore, x //= 3 means divide x by 3 (in an integer division fashion), and store the value back into x. It is equivalent to x = x // 3
// is the floor division operator, therefore //= is simply the inplace floor division operator.

What is the result of % in Python?

What does the % in a calculation? I can't seem to work out what it does.
Does it work out a percent of the calculation for example: 4 % 2 is apparently equal to 0. How?
The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].
Taken from http://docs.python.org/reference/expressions.html
Example 1:
6%2 evaluates to 0 because there's no remainder if 6 is divided by 2 ( 3 times ).
Example 2: 7%2 evaluates to 1 because there's a remainder of 1 when 7 is divided by 2 ( 3 times ).
So to summarise that, it returns the remainder of a division operation, or 0 if there is no remainder. So 6%2 means find the remainder of 6 divided by 2.
Somewhat off topic, the % is also used in string formatting operations like %= to substitute values into a string:
>>> x = 'abc_%(key)s_'
>>> x %= {'key':'value'}
>>> x
'abc_value_'
Again, off topic, but it seems to be a little documented feature which took me awhile to track down, and I thought it was related to Pythons modulo calculation for which this SO page ranks highly.
An expression like x % y evaluates to the remainder of x ÷ y - well, technically it is "modulus" instead of "reminder" so results may be different if you are comparing with other languages where % is the remainder operator. There are some subtle differences (if you are interested in the practical consequences see also "Why Python's Integer Division Floors" bellow).
Precedence is the same as operators / (division) and * (multiplication).
>>> 9 / 2
4
>>> 9 % 2
1
9 divided by 2 is equal to 4.
4 times 2 is 8
9 minus 8 is 1 - the remainder.
Python gotcha: depending on the Python version you are using, % is also the (deprecated) string interpolation operator, so watch out if you are coming from a language with automatic type casting (like PHP or JS) where an expression like '12' % 2 + 3 is legal: in Python it will result in TypeError: not all arguments converted during string formatting which probably will be pretty confusing for you.
[update for Python 3]
User n00p comments:
9/2 is 4.5 in python. You have to do integer division like so: 9//2 if you want python to tell you how many whole objects is left after division(4).
To be precise, integer division used to be the default in Python 2 (mind you, this answer is older than my boy who is already in school and at the time 2.x were mainstream):
$ python2.7
Python 2.7.10 (default, Oct 6 2017, 22:29:07)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 9 / 2
4
>>> 9 // 2
4
>>> 9 % 2
1
In modern Python 9 / 2 results 4.5 indeed:
$ python3.6
Python 3.6.1 (default, Apr 27 2017, 00:15:59)
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 9 / 2
4.5
>>> 9 // 2
4
>>> 9 % 2
1
[update]
User dahiya_boy asked in the comment session:
Q. Can you please explain why -11 % 5 = 4 - dahiya_boy
This is weird, right? If you try this in JavaScript:
> -11 % 5
-1
This is because in JavaScript % is the "remainder" operator while in Python it is the "modulus" (clock math) operator.
You can get the explanation directly from GvR:
Edit - dahiya_boy
In Java and iOS -11 % 5 = -1 whereas in python and ruby -11 % 5 = 4.
Well half of the reason is explained by the Paulo Scardine, and rest of the explanation is below here
In Java and iOS, % gives the remainder that means if you divide 11 % 5 gives Quotient = 2 and remainder = 1 and -11 % 5 gives Quotient = -2 and remainder = -1.
Sample code in swift iOS.
But when we talk about in python its gives clock modulus. And its work with below formula
mod(a,n) = a - {n * Floor(a/n)}
Thats means,
mod(11,5) = 11 - {5 * Floor(11/5)} => 11 - {5 * 2}
So, mod(11,5) = 1
And
mod(-11,5) = -11 - 5 * Floor(-11/5) => -11 - {5 * (-3)}
So, mod(-11,5) = 4
Sample code in python 3.0.
Why Python's Integer Division Floors
I was asked (again) today to explain why integer division in Python returns the floor of the result instead of truncating towards zero like C.
For positive numbers, there's no surprise:
>>> 5//2
2
But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity):
>>> -5//2
-3
>>> 5//-2
-3
This disturbs some people, but there is a good mathematical reason. The integer division operation (//) and its sibling, the modulo operation (%), go together and satisfy a nice mathematical relationship (all variables are integers):
a/b = q with remainder r
such that
b*q + r = a and 0 <= r < b
(assuming a and b are >= 0).
If you want the relationship to extend for negative a (keeping b positive), you have two choices: if you truncate q towards zero, r will become negative, so that the invariant changes to 0 <= abs(r) < otherwise, you can floor q towards negative infinity, and the invariant remains 0 <= r < b. [update: fixed this para]
In mathematical number theory, mathematicians always prefer the latter choice (see e.g. Wikipedia). For Python, I made the same choice because there are some interesting applications of the modulo operation where the sign of a is uninteresting. Consider taking a POSIX timestamp (seconds since the start of 1970) and turning it into the time of day. Since there are 24*3600 = 86400 seconds in a day, this calculation is simply t % 86400. But if we were to express times before 1970 using negative numbers, the "truncate towards zero" rule would give a meaningless result! Using the floor rule it all works out fine.
Other applications I've thought of are computations of pixel positions in computer graphics. I'm sure there are more.
For negative b, by the way, everything just flips, and the invariant becomes:
0 >= r > b.
So why doesn't C do it this way? Probably the hardware didn't do this at the time C was designed. And the hardware probably didn't do it this way because in the oldest hardware, negative numbers were represented as "sign + magnitude" rather than the two's complement representation used these days (at least for integers). My first computer was a Control Data mainframe and it used one's complement for integers as well as floats. A pattern of 60 ones meant negative zero!
Tim Peters, who knows where all Python's floating point skeletons are buried, has expressed some worry about my desire to extend these rules to floating point modulo. He's probably right; the truncate-towards-negative-infinity rule can cause precision loss for x%1.0 when x is a very small negative number. But that's not enough for me to break integer modulo, and // is tightly coupled to that.
PS. Note that I am using // instead of / -- this is Python 3 syntax, and also allowed in Python 2 to emphasize that you know you are invoking integer division. The / operator in Python 2 is ambiguous, since it returns a different result for two integer operands than for an int and a float or two floats. But that's a totally separate story; see PEP 238.
Posted by Guido van Rossum at 9:49 AM
The modulus is a mathematical operation, sometimes described as "clock arithmetic." I find that describing it as simply a remainder is misleading and confusing because it masks the real reason it is used so much in computer science. It really is used to wrap around cycles.
Think of a clock: Suppose you look at a clock in "military" time, where the range of times goes from 0:00 - 23.59. Now if you wanted something to happen every day at midnight, you would want the current time mod 24 to be zero:
if (hour % 24 == 0):
You can think of all hours in history wrapping around a circle of 24 hours over and over and the current hour of the day is that infinitely long number mod 24. It is a much more profound concept than just a remainder, it is a mathematical way to deal with cycles and it is very important in computer science. It is also used to wrap around arrays, allowing you to increase the index and use the modulus to wrap back to the beginning after you reach the end of the array.
Python - Basic Operators
http://www.tutorialspoint.com/python/python_basic_operators.htm
Modulus - Divides left hand operand by right hand operand and returns remainder
a = 10 and b = 20
b % a = 0
In most languages % is used for modulus. Python is no exception.
% Modulo operator can be also used for printing strings (Just like in C) as defined on Google https://developers.google.com/edu/python/strings.
# % operator
text = "%d little pigs come out or I'll %s and %s and %s" % (3, 'huff', 'puff', 'blow down')
This seems to bit off topic but It will certainly help someone.
Also, there is a useful built-in function called divmod:
divmod(a, b)
Take two (non complex) numbers as arguments and return a pair of numbers
consisting of their quotient and
remainder when using long division.
x % y calculates the remainder of the division x divided by y where the quotient is an integer. The remainder has the sign of y.
On Python 3 the calculation yields 6.75; this is because the / does a true division, not integer division like (by default) on Python 2. On Python 2 1 / 4 gives 0, as the result is rounded down.
The integer division can be done on Python 3 too, with // operator, thus to get the 7 as a result, you can execute:
3 + 2 + 1 - 5 + 4 % 2 - 1 // 4 + 6
Also, you can get the Python style division on Python 2, by just adding the line
from __future__ import division
as the first source code line in each source file.
Modulus operator, it is used for remainder division on integers, typically, but in Python can be used for floating point numbers.
http://docs.python.org/reference/expressions.html
The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].
It's a modulo operation, except when it's an old-fashioned C-style string formatting operator, not a modulo operation. See here for details. You'll see a lot of this in existing code.
It was hard for me to readily find specific use cases for the use of % online ,e.g. why does doing fractional modulus division or negative modulus division result in the answer that it does. Hope this helps clarify questions like this:
Modulus Division In General:
Modulus division returns the remainder of a mathematical division operation. It is does it as follows:
Say we have a dividend of 5 and divisor of 2, the following division operation would be (equated to x):
dividend = 5
divisor = 2
x = 5/2
The first step in the modulus calculation is to conduct integer division:
x_int = 5 // 2 ( integer division in python uses double slash)
x_int = 2
Next, the output of x_int is multiplied by the divisor:
x_mult = x_int * divisor
x_mult = 4
Lastly, the dividend is subtracted from the x_mult
dividend - x_mult = 1
The modulus operation ,therefore, returns 1:
5 % 2 = 1
Application to apply the modulus to a fraction
Example: 2 % 5
The calculation of the modulus when applied to a fraction is the same as above; however, it is important to note that the integer division will result in a value of zero when the divisor is larger than the dividend:
dividend = 2
divisor = 5
The integer division results in 0 whereas the; therefore, when step 3 above is performed, the value of the dividend is carried through (subtracted from zero):
dividend - 0 = 2 —> 2 % 5 = 2
Application to apply the modulus to a negative
Floor division occurs in which the value of the integer division is rounded down to the lowest integer value:
import math
x = -1.1
math.floor(-1.1) = -2
y = 1.1
math.floor = 1
Therefore, when you do integer division you may get a different outcome than you expect!
Applying the steps above on the following dividend and divisor illustrates the modulus concept:
dividend: -5
divisor: 2
Step 1: Apply integer division
x_int = -5 // 2 = -3
Step 2: Multiply the result of the integer division by the divisor
x_mult = x_int * 2 = -6
Step 3: Subtract the dividend from the multiplied variable, notice the double negative.
dividend - x_mult = -5 -(-6) = 1
Therefore:
-5 % 2 = 1
Be aware that
(3 +2 + 1 - 5) + (4 % 2) - (1/4) + 6
even with the brackets results in 6.75 instead of 7 if calculated in Python 3.4.
And the '/' operator is not that easy to understand, too (python2.7): try...
- 1/4
1 - 1/4
This is a bit off-topic here, but should be considered when evaluating the above expression :)
The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type.
3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 = 7
This is based on operator precedence.
% is modulo. 3 % 2 = 1, 4 % 2 = 0
/ is (an integer in this case) division, so:
3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
1 + 4%2 - 1/4 + 6
1 + 0 - 0 + 6
7
It's a modulo operation
http://en.wikipedia.org/wiki/Modulo_operation
http://docs.python.org/reference/expressions.html
So with order of operations, that works out to
(3+2+1-5) + (4%2) - (1/4) + 6
(1) + (0) - (0) + 6
7
The 1/4=0 because we're doing integer math here.
It is, as in many C-like languages, the remainder or modulo operation. See the documentation for numeric types — int, float, long, complex.
Modulus - Divides left hand operand by right hand operand and returns remainder.
If it helps:
1:0> 2%6
=> 2
2:0> 8%6
=> 2
3:0> 2%6 == 8%6
=> true
... and so on.
I have found that the easiest way to grasp the modulus operator (%) is through long division. It is the remainder and can be useful in determining a number to be even or odd:
4%2 = 0
2
2|4
-4
0
11%3 = 2
3
3|11
-9
2
def absolute(c):
if c>=0:
return c
else:
return c*-1
x=int(input("Enter the value:"))
a=absolute(x)
print(a)

Categories

Resources