Related
In the tutorial there is an example for finding prime numbers:
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
I understand that the double == is a test for equality, but I don't understand the if n % x part. Like I can verbally walk through each part and say what the statement does for the example. But I don't understand how the percentage sign falls in.
What does if n % x actually say?
The % does two things, depending on its arguments. In this case, it acts as the modulo operator, meaning when its arguments are numbers, it divides the first by the second and returns the remainder. 34 % 10 == 4 since 34 divided by 10 is three, with a remainder of four.
If the first argument is a string, it formats it using the second argument. This is a bit involved, so I will refer to the documentation, but just as an example:
>>> "foo %d bar" % 5
'foo 5 bar'
However, the string formatting behavior is supplemented as of Python 3.1 in favor of the string.format() mechanism:
The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer str.format() interface helps avoid these errors, and also provides a generally more powerful, flexible and extensible approach to formatting text.
And thankfully, almost all of the new features are also available from python 2.6 onwards.
Modulus operator; gives the remainder of the left value divided by the right value. Like:
3 % 1 would equal zero (since 3 divides evenly by 1)
3 % 2 would equal 1 (since dividing 3 by 2 results in a remainder of 1).
What does the percentage sign mean?
It's an operator in Python that can mean several things depending on the context. A lot of what follows was already mentioned (or hinted at) in the other answers but I thought it could be helpful to provide a more extensive summary.
% for Numbers: Modulo operation / Remainder / Rest
The percentage sign is an operator in Python. It's described as:
x % y remainder of x / y
So it gives you the remainder/rest that remains if you "floor divide" x by y. Generally (at least in Python) given a number x and a divisor y:
x == y * (x // y) + (x % y)
For example if you divide 5 by 2:
>>> 5 // 2
2
>>> 5 % 2
1
>>> 2 * (5 // 2) + (5 % 2)
5
In general you use the modulo operation to test if a number divides evenly by another number, that's because multiples of a number modulo that number returns 0:
>>> 15 % 5 # 15 is 3 * 5
0
>>> 81 % 9 # 81 is 9 * 9
0
That's how it's used in your example, it cannot be a prime if it's a multiple of another number (except for itself and one), that's what this does:
if n % x == 0:
break
If you feel that n % x == 0 isn't very descriptive you could put it in another function with a more descriptive name:
def is_multiple(number, divisor):
return number % divisor == 0
...
if is_multiple(n, x):
break
Instead of is_multiple it could also be named evenly_divides or something similar. That's what is tested here.
Similar to that it's often used to determine if a number is "odd" or "even":
def is_odd(number):
return number % 2 == 1
def is_even(number):
return number % 2 == 0
And in some cases it's also used for array/list indexing when wrap-around (cycling) behavior is wanted, then you just modulo the "index" by the "length of the array" to achieve that:
>>> l = [0, 1, 2]
>>> length = len(l)
>>> for index in range(10):
... print(l[index % length])
0
1
2
0
1
2
0
1
2
0
Note that there is also a function for this operator in the standard library operator.mod (and the alias operator.__mod__):
>>> import operator
>>> operator.mod(5, 2) # equivalent to 5 % 2
1
But there is also the augmented assignment %= which assigns the result back to the variable:
>>> a = 5
>>> a %= 2 # identical to: a = a % 2
>>> a
1
% for strings: printf-style String Formatting
For strings the meaning is completely different, there it's one way (in my opinion the most limited and ugly) for doing string formatting:
>>> "%s is %s." % ("this", "good")
'this is good'
Here the % in the string represents a placeholder followed by a formatting specification. In this case I used %s which means that it expects a string. Then the string is followed by a % which indicates that the string on the left hand side will be formatted by the right hand side. In this case the first %s is replaced by the first argument this and the second %s is replaced by the second argument (good).
Note that there are much better (probably opinion-based) ways to format strings:
>>> "{} is {}.".format("this", "good")
'this is good.'
% in Jupyter/IPython: magic commands
To quote the docs:
To Jupyter users: Magics are specific to and provided by the IPython kernel. Whether magics are available on a kernel is a decision that is made by the kernel developer on a per-kernel basis. To work properly, Magics must use a syntax element which is not valid in the underlying language. For example, the IPython kernel uses the % syntax element for magics as % is not a valid unary operator in Python. While, the syntax element has meaning in other languages.
This is regularly used in Jupyter notebooks and similar:
In [1]: a = 10
b = 20
%timeit a + b # one % -> line-magic
54.6 ns ± 2.7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
In [2]: %%timeit # two %% -> cell magic
a ** b
362 ns ± 8.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
The % operator on arrays (in the NumPy / Pandas ecosystem)
The % operator is still the modulo operator when applied to these arrays, but it returns an array containing the remainder of each element in the array:
>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a % 2
array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1])
Customizing the % operator for your own classes
Of course you can customize how your own classes work when the % operator is applied to them. Generally you should only use it to implement modulo operations! But that's a guideline, not a hard rule.
Just to provide a simple example that shows how it works:
class MyNumber(object):
def __init__(self, value):
self.value = value
def __mod__(self, other):
print("__mod__ called on '{!r}'".format(self))
return self.value % other
def __repr__(self):
return "{self.__class__.__name__}({self.value!r})".format(self=self)
This example isn't really useful, it just prints and then delegates the operator to the stored value, but it shows that __mod__ is called when % is applied to an instance:
>>> a = MyNumber(10)
>>> a % 2
__mod__ called on 'MyNumber(10)'
0
Note that it also works for %= without explicitly needing to implement __imod__:
>>> a = MyNumber(10)
>>> a %= 2
__mod__ called on 'MyNumber(10)'
>>> a
0
However you could also implement __imod__ explicitly to overwrite the augmented assignment:
class MyNumber(object):
def __init__(self, value):
self.value = value
def __mod__(self, other):
print("__mod__ called on '{!r}'".format(self))
return self.value % other
def __imod__(self, other):
print("__imod__ called on '{!r}'".format(self))
self.value %= other
return self
def __repr__(self):
return "{self.__class__.__name__}({self.value!r})".format(self=self)
Now %= is explicitly overwritten to work in-place:
>>> a = MyNumber(10)
>>> a %= 2
__imod__ called on 'MyNumber(10)'
>>> a
MyNumber(0)
While this is slightly off-topic, since people will find this by searching for "percentage sign in Python" (as I did), I wanted to note that the % sign is also used to prefix a "magic" function in iPython: https://ipython.org/ipython-doc/3/interactive/tutorial.html#magic-functions
In python 2.6 the '%' operator performed a modulus. I don't think they changed it in 3.0.1
The modulo operator tells you the remainder of a division of two numbers.
It checks if the modulo of the division. For example, in the case you are iterating over all numbers from 2 to n and checking if n is divisible by any of the numbers in between. Simply put, you are checking if a given number n is prime. (Hint: You could check up to n/2).
The modulus operator. The remainder when you divide two number.
For Example:
>>> 5 % 2 = 1 # remainder of 5 divided by 2 is 1
>>> 7 % 3 = 1 # remainer of 7 divided by 3 is 1
>>> 3 % 1 = 0 # because 1 divides evenly into 3
x % n == 0
which means the x/n and the value of reminder will taken as a result and compare with zero....
example:
4/5==0
4/5 reminder is 4
4==0 (False)
I wrote this code and it's alright with positive numbers, but when I tried negative numbers it crashes. Can you give any hints on how to make it work with negative numbers as well? It needs to be recursive, not iterative, and to calculate the sum of the digits of an integer.
def sum_digits(n):
if n != 0:
return (n % 10 + sum_digits(n // 10))
else:
return 0
if __name__=='__main__':
print(sum_digits(123))
Input: 123
Output: 6
On the assumption that the 'sum' of the three digits of a negative number is the same as that of the absolute value of that number, this will work:
def sum_digits(n):
if n < 0:
return sum_digits(-n)
elif n != 0:
return (n % 10 + sum_digits(n // 10))
else:
return 0
That said, your actual problem here is that Python's handling of modulo for a negative number is different than you expect:
>>> -123 % 10
7
Why is that? It's because of the use of trunc() in the division. This page has a good explanation, but the short answer is that when you divide -123 by 10, in order to figure out the remainder, Python truncates in a different direction than you'd expect. (For good, if obscure, reasons.) Thus, in the above, instead of getting the expected 3 you get 7 (which is 10, your modulus, minus 3, the leftover).
Similarly, it's handling of integer division is different:
>>> -123 // 10
-13
>>> 123 // 10
12
This is un-intuitively correct because it is rounding 'down' rather than 'towards zero'. So a -12.3 rounds 'down' to -13.
These reasons are why the easiest solution to your particular problem is to simply take the absolute value prior to doing your actual calculation.
Separate your function into two functions: one, a recursive function that must always be called with a non-negative number, and two, a function that checks its argument can calls the recursive function with an appropriate argument.
def sum_digits(n):
return _recursive_sum_digits(abs(n))
def _recursive_sum_digits(n):
if n != 0:
return (n % 10 + sum_digits(n // 10))
else:
return 0
Since _recursive_sum_digits can assume its argument is non-negative, you can dispense with checking its sign on every recursive call, and guarantee that n // 10 will eventually produce 0.
If you want to just sum the digits that come after the negative sign, remove the sign by taking the absolute value of the number. If you're considering the first digit of the negative number to be a negative digit, then manually add that number in after performing this function on the rest of the digits.
Here is your hint. This is happening because the modulo operator always yields a result with the same sign as its second operand (or zero). Look at these examples:
>>> 13 % 10
3
>>> -13 % 10
7
In your specific case, a solution is to first get the absolute value of the number, and then you can go on with you approach:
def sum_digits(n):
n = abs(n)
if n != 0:
return (n % 10 + sum_digits(n // 10))
else:
return 0
Why does the bit length of 0 return 0 and not 1?
>>> int(0).bit_length()
0
>>> int(2).bit_length()
2
2 in binary is 0x10 which represents two bits, doesn't zero in binary still techincally take up 1 bit since its representation in hex is 0x0?
The Python documentation states
More precisely, if x is nonzero, then x.bit_length() is the unique
positive integer k such that 2**(k-1) <= abs(x) < 2**k. Equivalently,
when abs(x) is small enough to have a correctly rounded logarithm,
then k = 1 + int(log(abs(x), 2)).
If x is zero, then x.bit_length()
returns 0.
https://docs.python.org/3/library/stdtypes.html#int.bit_length
Please read documentation on https://docs.python.org/3/library/stdtypes.html
It is explained.
That's how the function works. if you send it 0, it'll output 0
If x is zero, then x.bit_length() returns 0.
I am trying to find the largest cube root that is a whole number, that is less than 12,000.
processing = True
n = 12000
while processing:
n -= 1
if n ** (1/3) == #checks to see if this has decimals or not
I am not sure how to check if it is a whole number or not though! I could convert it to a string then use indexing to check the end values and see whether they are zero or not, that seems rather cumbersome though. Is there a simpler way?
To check if a float value is a whole number, use the float.is_integer() method:
>>> (1.0).is_integer()
True
>>> (1.555).is_integer()
False
The method was added to the float type in Python 2.6.
Take into account that in Python 2, 1/3 is 0 (floor division for integer operands!), and that floating point arithmetic can be imprecise (a float is an approximation using binary fractions, not a precise real number). But adjusting your loop a little this gives:
>>> for n in range(12000, -1, -1):
... if (n ** (1.0/3)).is_integer():
... print n
...
27
8
1
0
which means that anything over 3 cubed, (including 10648) was missed out due to the aforementioned imprecision:
>>> (4**3) ** (1.0/3)
3.9999999999999996
>>> 10648 ** (1.0/3)
21.999999999999996
You'd have to check for numbers close to the whole number instead, or not use float() to find your number. Like rounding down the cube root of 12000:
>>> int(12000 ** (1.0/3))
22
>>> 22 ** 3
10648
If you are using Python 3.5 or newer, you can use the math.isclose() function to see if a floating point value is within a configurable margin:
>>> from math import isclose
>>> isclose((4**3) ** (1.0/3), 4)
True
>>> isclose(10648 ** (1.0/3), 22)
True
For older versions, the naive implementation of that function (skipping error checking and ignoring infinity and NaN) as mentioned in PEP485:
def isclose(a, b, rel_tol=1e-9, abs_tol=0.0):
return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
We can use the modulo (%) operator. This tells us how many remainders we have when we divide x by y - expresses as x % y. Every whole number must divide by 1, so if there is a remainder, it must not be a whole number.
This function will return a boolean, True or False, depending on whether n is a whole number.
def is_whole(n):
return n % 1 == 0
You could use this:
if k == int(k):
print(str(k) + " is a whole number!")
You don't need to loop or to check anything. Just take a cube root of 12,000 and round it down:
r = int(12000**(1/3.0))
print r*r*r # 10648
You can use a modulo operation for that.
if (n ** (1.0/3)) % 1 != 0:
print("We have a decimal number here!")
How about
if x%1==0:
print "is integer"
Wouldn't it be easier to test the cube roots? Start with 20 (20**3 = 8000) and go up to 30 (30**3 = 27000). Then you have to test fewer than 10 integers.
for i in range(20, 30):
print("Trying {0}".format(i))
if i ** 3 > 12000:
print("Maximum integral cube root less than 12000: {0}".format(i - 1))
break
The above answers work for many cases but they miss some. Consider the following:
fl = sum([0.1]*10) # this is 0.9999999999999999, but we want to say it IS an int
Using this as a benchmark, some of the other suggestions don't get the behavior we might want:
fl.is_integer() # False
fl % 1 == 0 # False
Instead try:
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
def is_integer(fl):
return isclose(fl, round(fl))
now we get:
is_integer(fl) # True
isclose comes with Python 3.5+, and for other Python's you can use this mostly equivalent definition (as mentioned in the corresponding PEP)
Just a side info, is_integer is doing internally:
import math
isInteger = (math.floor(x) == x)
Not exactly in python, but the cpython implementation is implemented as mentioned above.
All the answers are good but a sure fire method would be
def whole (n):
return (n*10)%10==0
The function returns True if it's a whole number else False....I know I'm a bit late but here's one of the interesting methods which I made...
Edit: as stated by the comment below, a cheaper equivalent test would be:
def whole(n):
return n%1==0
You can use something like:
num = 1.9899
bool(int(num)-num)
#returns True
if it is True, It means it holds some value, hence not a whole number. Else
num = 1.0
bool(int(num)-num)
# returns False
>>> def is_near_integer(n, precision=8, get_integer=False):
... if get_integer:
... return int(round(n, precision))
... else:
... return round(n) == round(n, precision)
...
>>> print(is_near_integer(10648 ** (1.0/3)))
True
>>> print(is_near_integer(10648 ** (1.0/3), get_integer=True))
22
>>> for i in [4.9, 5.1, 4.99, 5.01, 4.999, 5.001, 4.9999, 5.0001, 4.99999, 5.000
01, 4.999999, 5.000001]:
... print(i, is_near_integer(i, 4))
...
4.9 False
5.1 False
4.99 False
5.01 False
4.999 False
5.001 False
4.9999 False
5.0001 False
4.99999 True
5.00001 True
4.999999 True
5.000001 True
>>>
This problem has been solved, but I would like to propose an additional mathematical-based solution for funcies.
The benefit of this approach is that it calculates the whole number part of your number, which may be beneficial depending on your general task.
Algorithm:
Decompose whole number part of your number its a sum of its decimals (e.g., 327=3*100+2*10+7*1)
take difference between calculated whole number and number itself
decide whether difference is close enough to be considered an integer.
from math import ceil, log, isclose
def is_whole(x: float) -> bool:
n_digits = ceil(log(x,10)) # number of digits of decimals at or above ones
digits = [(n//(10**i))%10 for i in range(n_digits)] # parse digits of `x` at or above ones decimal
whole = 0 # will equal the whole number part of `x`
for i in range(n_digits):
decimal = 10**i
digit = digits[i]
whole += digit*decimal
diff = whole - x
return isclose(diff, 0.0)
NOTE: the idea of parsing digits of a number was realized from here
Try using:
int(val) == val
It will give lot more precision than any other methods.
You can use the round function to compute the value.
Yes in python as many have pointed when we compute the value of a cube root, it will give you an output with a little bit of error. To check if the value is a whole number you can use the following function:
def cube_integer(n):
if round(n**(1.0/3.0))**3 == n:
return True
return False
But remember that int(n) is equivalent to math.floor and because of this if you find the int(41063625**(1.0/3.0)) you will get 344 instead of 345.
So please be careful when using int withe cube roots.
How could I go about finding the division remainder of a number in Python?
For example:
If the number is 26 and divided number is 7, then the division remainder is 5.
(since 7+7+7=21 and 26-21=5.)
For simple divisibility testing, see How do you check whether a number is divisible by another number?.
you are looking for the modulo operator:
a % b
for example:
>>> 26 % 7
5
Of course, maybe they wanted you to implement it yourself, which wouldn't be too difficult either.
The remainder of a division can be discovered using the operator %:
>>> 26%7
5
In case you need both the quotient and the modulo, there's the builtin divmod function:
>>> seconds= 137
>>> minutes, seconds= divmod(seconds, 60)
26 % 7 (you will get remainder)
26 / 7 (you will get divisor, can be float value)
26 // 7 (you will get divisor, only integer value)
If you want to get quotient and remainder in one line of code (more general usecase), use:
quotient, remainder = divmod(dividend, divisor)
#or
divmod(26, 7)
From Python 3.7, there is a new math.remainder() function:
from math import remainder
print(remainder(26,7))
Output:
-2.0 # not 5
Note, as above, it's not the same as %.
Quoting the documentation:
math.remainder(x, y)
Return the IEEE 754-style remainder of x with
respect to y. For finite x and finite nonzero y, this is the
difference x - n*y, where n is the closest integer to the exact value
of the quotient x / y. If x / y is exactly halfway between two
consecutive integers, the nearest even integer is used for n. The
remainder r = remainder(x, y) thus always satisfies abs(r) <= 0.5 *
abs(y).
Special cases follow IEEE 754: in particular, remainder(x, math.inf)
is x for any finite x, and remainder(x, 0) and remainder(math.inf, x)
raise ValueError for any non-NaN x. If the result of the remainder
operation is zero, that zero will have the same sign as x.
On platforms using IEEE 754 binary floating-point, the result of this
operation is always exactly representable: no rounding error is
introduced.
Issue29962 describes the rationale for creating the new function.
If you want to avoid modulo, you can also use a combination of the four basic operations :)
26 - (26 // 7 * 7) = 5
Use the % instead of the / when you divide. This will return the remainder for you. So in your case
26 % 7 = 5
We can solve this by using modulus operator (%)
26 % 7 = 5;
but
26 / 7 = 3 because it will give quotient but % operator will give remainder.
Modulo would be the correct answer, but if you're doing it manually this should work.
num = input("Enter a number: ")
div = input("Enter a divisor: ")
while num >= div:
num -= div
print num
You can find remainder using modulo operator
Example
a=14
b=10
print(a%b)
It will print 4
If you want the remainder of your division problem, just use the actual remainder rules, just like in mathematics. Granted this won't give you a decimal output.
valone = 8
valtwo = 3
x = valone / valtwo
r = valone - (valtwo * x)
print "Answer: %s with a remainder of %s" % (x, r)
If you want to make this in a calculator format, just substitute valone = 8
with valone = int(input("Value One")). Do the same with valtwo = 3, but different vairables obviously.
Here's an integer version of remainder in Python, which should give the same results as C's "%" operator:
def remainder(n, d):
return (-1 if n < 0 else 1) * (abs(n) % abs(d))
Expected results:
remainder(123, 10) == 3
remainder(123, -10) == 3
remainder(-123, 10) == -3
remainder(-123, -10) == -3
you can define a function and call it remainder with 2 values like rem(number1,number2) that returns number1%number2
then create a while and set it to true then print out two inputs for your function holding number 1 and 2 then print(rem(number1,number2)