python - 一个支持加法和否定的模整数的python类?
问题描述
我正在尝试为python中的定义添加和否定提供代码。我拥有的最相似的东西是乘法,我在下面复制了它。关于应该改变什么以解释模整数的加法和否定的任何想法?我知道减法只是在这个问题中添加否定。任何帮助将非常感激!!
class Zp:
p = 2 #class attribute
def __init__(self, n):
self.n = n % Zp.p #instance attribute
def __str__(self):
#msg = '[' + str(self.n) + ']'
msg = str(self.n) + ' mod ' + str(Zp.p) + ')'
return msg
def __repr__(self):
return self.__str__()
# def __add__(self, other):
# [a], [b] in Zp ([a], [b] are sets of integers)
# [a]+[b] = [a+b] e.g. a+b mod p
# def __neg__(self, other):
# def __sub__ (self, other): # the addition of negation
def __mul__(self, other): # [a]*[b] = [a*b] e.g. a*b mod p
if Zp.__instancecheck__(other):
return Zp(self.n * other.n)
elif type(other) == int:
return Zp(self.n * other)
else:
raise TypeError('multiplication a Zp with a non-Zp or non-integer')
我尝试添加的内容:
def __add__(self, other): # [a]*[b] = [a*b] e.g. a*b mod p
if Zp.__instancecheck__(other):
return Zp(self.n + other.n)
elif type(other) == int:
return Zp(self.n + other)
解决方案
在对数字进行模运算时,通常可以进行正常运算(加法、减法、乘法),然后将答案模数取模。
例如,
3 * 3 模 2 = 9 模 2 = 1 模 2
为了实现您指定的操作,请执行操作,然后取模。查看 Wikipedia 的文章,了解有关如何进行模运算的更多信息:Modular Arithmetic - Wikipedia
推荐阅读
- python - 如何在 Python 硒测试中处理 Bootstrap3 模态弹出消息?
- c - 如何通过指针从数组中删除元素
- spring-boot - Spring cloud stream中BROKER rabbitMq宕机时如何处理?
- amazon-ec2 - 是否可以在 Bitbucket Pipelines 上使用“pm2 deploy production”进行部署?
- java - 在春季启动单元测试@Async
- botframework - 在 ms 团队中获取团队成员时出错
- java - 没有元素时如何重构for循环方法以中断
- ruby-on-rails - rails:一页上的多个控制器操作
- c# - SonarQube 规则集存在于项目中,但在代码分析中没有生成任何内容
- algorithm - 查找链表中的乱序元素