Python中的divmod()及其应用
divmod()是python标准库的一部分,该库以两个数字作为参数,并将其除法的商和余数作为元组给出。它在许多数学应用中很有用,例如检查数字的可除性并确定数字是否为质数。
语法
Syntax: divmod(a, b) a and b : b divides a a and b are integers or floats
例子
在下面的示例中,查看整数和浮点数的情况。在divmod()它们的应用上,我们得到一个结果元组,该元组也可以包含整数和浮点值。
# with integers
print("5 and 2 give:",divmod(5,2))
print("25 and 5 give:",divmod(25,5))
# with Floats
print("5.6 and 2 give:",divmod(5.6,2))
print("11.3 and 9.2 give:",divmod(11.3,9.2))输出结果
运行上面的代码给我们以下结果-
5 and 2 give: (2, 1) 25 and 5 give: (5, 0) 5.6 and 2 give: (2.0, 1.5999999999999996) 11.3 and 9.2 give: (1.0, 2.1000000000000014)
使用零
如果第一个参数为零,则得到(0,0)。如果第二个参数为零,那么我们将得到预期的Zerodivision错误。
示例
# With first argument as zero
print("0 and 8 give:",divmod(0,8))
# With second argument as zero
print("8 and 0 give:",divmod(8,0))输出结果
运行上面的代码给我们以下结果-
0 and 8 give: (0, 0)
Traceback (most recent call last):
File "xxx.py", line 6, in
print("8 and 0 give:",divmod(8,0))
ZeroDivisionError: integer division or modulo by zero检查除数
如果除后的元组的第二个值是0,那么我们说第一个数字可被第二部分整除。否则它是不可分割的。下面的示例说明了这一点。
示例
m = 12 n = 4 quotient,remainder = divmod(m,n) print(quotient) print(remainder) if (remainder==0): print(m,' is divisible by ',n) else: print(m,' is not divisible by ',n)
输出结果
运行上面的代码给我们以下结果-
3 0 12 is divisible by 4
检查数字是否为素数
divmod()当我们开始将一个数字除以以1开始的每个数字时,我们可以用来跟踪它产生的提醒。对于质数,零余数的计数将仅为1,因为除自身以外的任何数字都无法完美地将其除以。如果零余数的计数大于1,则该数字不是素数。
示例
num = 11
a = num
# counter the number of remainders with value zero
count = 0
while a != 0:
q, r = divmod(num, a)
a -= 1
if r == 0:
count += 1
if count > 2:
print(num, 'is not Prime')
else:
print(num, 'is Prime')输出结果
运行上面的代码给我们以下结果-
11 is Prime