如何在Python中计算mod b?

问题:如何在Python中计算mod b?

Python math库中是否有模函数?

是不是15 % 43?但是15 mod 4是1,对吗?

Is there a modulo function in the Python math library?

Isn’t 15 % 4, 3? But 15 mod 4 is 1, right?


回答 0

%路标。这不只是余数,它是模运算。

There’s the % sign. It’s not just for the remainder, it is the modulo operation.


回答 1

您也可以尝试divmod(x, y)返回一个元组(x // y, x % y)

you can also try divmod(x, y) which returns a tuple (x // y, x % y)


回答 2

>>> 15 % 4
3
>>>

模给出整数除后的余数。

>>> 15 % 4
3
>>>

The modulo gives the remainder after integer division.


回答 3

mod = a % b

这会将的结果存储a mod b在变量中mod

没错,15 mod 4是3,这正是python返回的内容:

>>> 15 % 4
3

a %= b 也有效。

mod = a % b

This stores the result of a mod b in the variable mod.

And you are right, 15 mod 4 is 3, which is exactly what python returns:

>>> 15 % 4
3

a %= b is also valid.


回答 4

为什么不使用%?


print 4 % 2 # 0

Why don’t you use % ?


print 4 % 2 # 0

回答 5

我认为您没有完全掌握模数。a % ba mod b只是表示模数的两种不同方式。在这种情况下,python使用%。不,15 mod 4不是115 % 4 == 15 mod 4 == 3

I don’t think you’re fully grasping modulo. a % b and a mod b are just two different ways to express modulo. In this case, python uses %. No, 15 mod 4 is not 1, 15 % 4 == 15 mod 4 == 3.


回答 6

A = [3, 1, 2, 4]
for a in A:
    print(a % 2)

输出:

1
1
0
0
A = [3, 1, 2, 4]
for a in A:
    print(a % 2)

output:

1
1
0
0