88 lines
2.0 KiB
Python
88 lines
2.0 KiB
Python
#!/usr/bin/env python
|
|
# encoding: utf-8
|
|
|
|
|
|
from .operator import Operator
|
|
from ..generic import flatten_list
|
|
|
|
|
|
class Pw(Operator):
|
|
|
|
""" The operator ^
|
|
|
|
>>> pw = Pw()
|
|
>>> pw
|
|
^
|
|
>>> pw(2, 3)
|
|
8
|
|
>>> pw.__tex__('2','3')
|
|
'2^{ 3 }'
|
|
>>> pw.__tex__('2','-3')
|
|
'2^{ -3 }'
|
|
>>> pw.__tex__('-2','3')
|
|
'( -2 )^{ 3 }'
|
|
>>> pw.__txt__('2','3')
|
|
'2 ^ 3'
|
|
>>> pw.__txt__('-2','3')
|
|
'( -2 ) ^ 3'
|
|
>>> pw.__txt__('2','-3')
|
|
'2 ^ ( -3 )'
|
|
"""
|
|
|
|
_CARACT = {
|
|
"operator": "^",
|
|
"name": "pw",
|
|
"priority": 6,
|
|
"arity": 2,
|
|
"actions": ("__pow__", ""),
|
|
"txt": "{op1} ^ {op2}",
|
|
"tex": "{op1}^{{ {op2} }}",
|
|
}
|
|
|
|
def __init__(self):
|
|
""" Initiate Pw Operator """
|
|
super(Pw, self).__init__(**self._CARACT)
|
|
|
|
def __call__(self, op1, op2):
|
|
""" Calling this operator performs the rigth calculus """
|
|
return getattr(op1, "__pow__")(op2)
|
|
|
|
def l_parenthesis(self, opl, str_join=False):
|
|
""" Add parenthesis for left operand if necessary """
|
|
ans = opl
|
|
try:
|
|
if opl.mainOp.priority < self.priority:
|
|
ans = flatten_list(["(", opl, ")"])
|
|
except AttributeError:
|
|
# op has not the attribute priority
|
|
pass
|
|
try:
|
|
if int(opl) < 0:
|
|
ans = ["(", opl, ")"]
|
|
except ValueError:
|
|
pass
|
|
|
|
ans = flatten_list([ans])
|
|
if str_join:
|
|
ans = ' '.join([str(i) for i in ans])
|
|
return ans
|
|
|
|
def __tex__(self, *args):
|
|
"""Tex rendering for ^
|
|
|
|
:*args: Operands for this operation
|
|
:returns: String with operator and his operands
|
|
|
|
"""
|
|
op1 = self.l_parenthesis(args[0], True)
|
|
op2 = args[1]
|
|
ans = self.tex.format(op1=op1, op2=op2)
|
|
|
|
return ans
|
|
|
|
|
|
# -----------------------------
|
|
# Reglages pour 'vim'
|
|
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:
|
|
# cursor: 16 del
|