This question already has answers here:
How does the modulo (%) operator work on negative numbers in Python?
(12 answers)
Closed last month.
I found this definition for modulo
mod(a, n) = a - n * floor(a / n)
Doing an integer division and then multiplying it again means finding the biggest number smaller than a that is dividable by n without a remainder. Subtracting this from a yields the remainder of the division and by that the modulo."
source:https://torstencurdt.com/tech/posts/modulo-of-negative-numbers/
It seemed to help me understand intuitively, and it worked for cases where both a and n where positive and also cases where a was negative while b was positive. For example:
-10 mod 3
-12 is the largest number smaller than -10 divisible by 3. So the remainder is -10-(-12)=2 which is correct.
But when I tried doing 10 mod -3 my answer was incorrect. Because while 9 is the largest number smaller than 10 divisible by -3 it will give the wrong answer as it would evaluate to 10-9=1.
Instead it is supposed to be 10 -((-4)*(-3))=10-12=-2.
But 12 isn't the biggest number smaller than a.
I understand how to solve for the answer using the formula a= (a//n)(n)+(a%n) in python. But is there an intuitive definition to help me understand?
I found an anser here https://en.wikipedia.org/wiki/Remainder
it seems there are two types of remainders and a programming languages picks which one to use
The Python 3 documentation gives the identity x == (x//y)*y + (x%y), from which it can be deduced that x%y == x - (x//y)*y. // denotes “floor division”; x//y is the greatest integer not greater than x/y.
For x=10 and y==−3, x/y is −3⅓. floor(−3⅓) is −4. Therefore x//y is −4. Then x - (x//y)*y is 10 − (−4)*−3 = 10−12 = −2.
Here is a graph of x%3:
Here is a graph of x%-3:
while b:
n.append(int(b%10))
b=b/10
return n
Here the while statement is not stopping even when b=0, what is the problem with this?
Let's simplify your while loop and remove the unnecessary parts:
while b:
b = b/10
print(b)
What this does is, it takes a given b, divides it by 10, and assigns this as b. Now the "divide by 10" part is tricky.
If you are using Python 2, it works as an integer division:
19/10 = 1
Let's divide this one more time:
1/10 = 0
But in Python 3, this is an actual, proper division:
19/10 = 1.9
Let's divide this one also one more time:
1.9/10 = 0.19
So in Python 2, your loop will keep rounding the division down, and you will reach 0 eventually. But in Python 3, you will keep dividing your float properly, and will never reach 0. This will mean that your while will never terminate.
Solution: If you want to end up at 0 eventually through integer division so that your loop ends at some point, you can use a//b in Python 3 to get the same behavior of a/b in Python 2.
The most efficient way to compute the reminder and the integer quotient is divmod.
while b:
b, m = divmod(b, 10)
n.append(m)
This loop stops for non-negative b.
I think you want to do integer division, if that is the case your code should have // instead of /
while b:
n.append(int(b%10))
b=b//10
return n
As neither valid answer is accepted, I'll offer the alternative solution, which is to change the stopping condition of the while loop. This lets you keep your floating point division should you need it for some case not in the original question. You can also do the integer division with the shorthand b //= 10.
while int(b): # Or more explicitly: while bool(int(b)):
n.append(int(b%10))
b /= 10
return n
I am writing a simple Python script that generates 6 numbers at random (from 1 to 100) and a larger number (from 100 to 1000). My goals for this script are to:
Calculate all of the possible combinations using at least 2 numbers and any of the simple math operations (adding, subtracting, multiplying and dividing)
Output all of the combinations whose total is within 10 above or below the larger number as 'matches'
The list of numbers need not be exhausted, but repeating numbers isn't accepted. Plus I don't care too much if the code is efficient or not (if anyone decides to post any - I can post mine so far if anyone needs it - preferably post it in Python); as long as it works, I'm happy to optimize it.
I have attempted this myself, only to fail as the program quickly ended with a RunTime Error. I also tried putting in a counter to stop the loop after x passes (where x is a small number such as 50), but that just makes matters worse as it keeps on going infinitely.
I've also done some research, and I found that this (Computing target number from numbers in a set - the second to last answer) is the closest I found to meet my requirements but hasn't got quite there yet.
Thanks for the help! :-)
EDIT: Here is my code:
import random, time, operator
i = 0
numlist = []
while i != 6:
number = random.randint(1, 100)
numlist.append(number)
i += 1
largenumber = random.randint(100, 1000)
print(numlist)
print(largenumber)
def operationTesting():
a, c, m, total = 0, 0, 0, 0
totalnums = 0
operators = ['+', '-', '*', '/']
while total != largenumber:
for a in numlist[m]:
for c in numlist[m+1]:
print(a)
print(c)
if a == c:
operationTesting()
else:
b = random.choice(operators)
if b == '+':
summednums = operator.add(int(a), int(c))
print(summednums)
totalnums = totalnums + summednums
elif b == '-':
summednums = operator.sub(int(a), int(c))
print(summednums)
totalnums = totalnums + summednums
elif b == '*':
summednums = operator.mul(int(a), int(c))
print(summednums)
totalnums = totalnums + summednums
elif b == '/':
summednums = operator.floordiv(int(a), int(c))
print(summednums)
totalnums = totalnums + summednums
print(totalnums)
SystemExit(None)
operationTesting()
A very neat way to do it is using Reverse Polish Notation or Postfix notation. This notation avoids the need for brackets that you would probably want if you were doing it using conventional arithmetic with operator precedence etc.
You can do this with brute force if you are not too bothered about time efficiency. You need to consider what you want to do with division too - if two numbers do not divide exactly, do you want to return the result as 'invalid' in some way (I guess so), or really return a floored division? Note the latter might give you some invalid answers...
Consider the test case of numlist = [1,2,3,4,5,6]. In RPN, we could do something like this
RPN Equivalent to
123456+++++ (1+(2+(3+(4+(5+6)))))
123456++++- (1-(2+(3+(4+(5+6)))))
123456+++-+ (1+(2-(3+(4+(5+6)))))
...
12345+6+-++ (1+(2+(3-((4+5)+6))))
12345+6-+++ (1+(2+(3+((4+5)-6))))
...
And so on. You can probably see that with sufficient combinations, you can get any combinations of numbers, operators and brackets. The brackets are important - to take only 3 numbers obviously
1+2*6
is normally interpreted
(1 + (2*6)) == 13
and is quite different to
((1+2)*6) == 18
In RPN, these would be 126*+ and 12+6* respectively.
So, you've got to generate all your combinations in RPN, then develop an RPN calculator to evaluate them.
Unfortunately, there are quite a lot of permutations with 6 numbers (or any subset thereof). First you can have the numbers in any order, thats 6! = 720 combinations. You will always need n-1 == 5 operators and they can be any one of the 4 operators. So that's 4**5 == 1024 permutations. Finally those 5 operators can be in any one of 5 positions (after first pair of numbers, after first 3, after 4 and so on). You can have maximum 1 operator in the first position, two in the second and so on. That's 5! == 120 permutations. So in total you have 720*1024*120 == 88473600 permutations. Thats roughly 9 * 10**7 Not beyond the realms of computation at all, but it might take 5 minutes or so to generate them all on a fairly quick computer.
You could significantly improve on this by "chopping" the search tree
Loads of the RPN combinations will be arithmetically identical (e.g. 123456+++++ == 12345+6++++ == 1234+5+6+++ etc) - you could use some prior knowledge to improve generate_RPN_combinations so it didn't generate them
identifying intermediate results that show certain combinations could never satisfy your criterion and not exploring any further combinations down that road.
You then have to send each string to the RPN calculator. These are fairly easy to code and a typical programming exercise - you push values onto a stack and when you come to operators, pop the top two members from the stack, apply the operator and push the result onto the stack. If you don't want to implement that - google minimal python rpn calculator and there are resources there to help you.
Note, you say you don't have to use all 6 numbers. Rather than implementing that separately, I would suggest checking any intermediate results when evaluating the combinations for all 6 numbers, if they satisfy the criterion, keep them too.
I want to implement Karatsuba's 2-split multiplication in Python. However, writing numbers in the form
A=c*x+d
where x is a power of the base (let x=b^m) close to sqrt(A).
How am I supposed to find x, if I can't even use division and multiplication? Should I count the number of digits and shift A to the left by half the number of digits?
Thanks.
Almost. You don't shift A by half the number of digits; you shift 1. Of course, this is only efficient if the base is a power of 2, since "shifting" in base 10 (for example) has to be done with multiplications. (Edit: well, ok, you can multiply with shifts and additions. But it's ever so much simpler with a power of 2.)
If you're using Python 3.1 or greater, counting the bits is easy, because 3.1 introduced the int.bit_length() method. For other versions of Python, you can count the bits by copying A and shifting it right until it's 0. This can be done in O(log N) time (N = # of digits) with a sort of binary search method - shift by many bits, if it's 0 then that was too many, etc.
You already accepted an answer since I started writing this, but:
What Tom said: in Python 3.x you can get n = int.bit_length() directly.
In Python 2.x you get n in O(log2(A)) time by binary-search, like below.
Here is (2.x) code that calculates both. Let the base-2 exponent of x be n, i.e. x = 2**n.
First we get n by binary-search by shifting. (Really we only needed n/2, so that's one unnecessary last iteration).
Then when we know n, getting x,c,d is easy (still no using division)
def karatsuba_form(A,n=32):
"""Binary-search for Karatsuba form using binary shifts"""
# First search for n ~ log2(A)
step = n >> 1
while step>0:
c = A >> n
print 'n=%2d step=%2d -> c=%d' % (n,step,c)
if c:
n += step
else:
n -= step
# More concisely, could say: n = (n+step) if c else (n-step)
step >>= 1
# Then take x = 2^(n/2) ˜ sqrt(A)
ndiv2 = n/2
# Find Karatsuba form
c = (A >> ndiv2)
x = (1 << ndiv2)
d = A - (c << ndiv2)
return (x,c,d)
Your question is already answered in the article to which you referred: "Karatsuba's basic step works for any base B and any m, but the recursive algorithm is most efficient when m is equal to n/2, rounded up" ... n being the number of digits, and 0 <= value_of_digit < B.
Some perspective that might help:
You are allowed (and required!) to use elementary operations like number_of_digits // 2 and divmod(digit_x * digit_x, B) ... in school arithmetic, where B is 10, you are required (for example) to know that divmod(9 * 8, 10) produces (7, 2).
When implementing large number arithmetic on a computer, it is usual to make B the largest power of 2 that will support the elementary multiplication operation conveniently. For example in the CPython implementation on a 32-bit machine, B is chosen to to be 2 ** 15 (i.e. 32768), because then product = digit_x * digit_y; hi = product >> 15; lo = product & 0x7FFF; works without overflow and without concern about a sign bit.
I'm not sure what you are trying to achieve with an implementation in Python that uses B == 2, with numbers represented by Python ints, whose implementation in C already uses the Karatsuba algorithm for multiplying numbers that are large enough to make it worthwhile. It can't be speed.
As a learning exercise, you might like to try representing a number as a list of digits, with the base B being an input parameter.
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)